blob: 7c4dc9028c9f88d5411d8c99b55c0dda65b2c409 [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"
Tobias Grosser75805372011-04-29 06:27:02 +000023#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000024#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000025#include "polly/Support/ScopHelper.h"
Tobias Grosser9737c7b2015-11-22 11:06:51 +000026#include "llvm/ADT/DepthFirstIterator.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000027#include "llvm/ADT/MapVector.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000028#include "llvm/ADT/PostOrderIterator.h"
29#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000030#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000031#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000032#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000033#include "llvm/Analysis/AliasAnalysis.h"
Johannes Doerfert2af10e22015-11-12 03:25:01 +000034#include "llvm/Analysis/AssumptionCache.h"
Johannes Doerfert1dc12af2016-04-23 12:59:18 +000035#include "llvm/Analysis/Loads.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000036#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000037#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000038#include "llvm/Analysis/RegionIterator.h"
39#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Johannes Doerfert48fe86f2015-11-12 02:32:32 +000040#include "llvm/IR/DiagnosticInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000041#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000042#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000043#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000044#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000045#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000046#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000047#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000048#include "isl/schedule.h"
49#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000050#include "isl/set.h"
51#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000052#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000053#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000054#include <sstream>
55#include <string>
56#include <vector>
57
58using namespace llvm;
59using namespace polly;
60
Chandler Carruth95fef942014-04-22 03:30:19 +000061#define DEBUG_TYPE "polly-scops"
62
Tobias Grosser75dc40c2015-12-20 13:31:48 +000063// The maximal number of basic sets we allow during domain construction to
64// be created. More complex scops will result in very high compile time and
65// are also unlikely to result in good code
Michael Krusebc150122016-05-02 12:25:18 +000066static int const MaxDisjunctionsInDomain = 20;
Tobias Grosser75dc40c2015-12-20 13:31:48 +000067
Johannes Doerfert2f705842016-04-12 16:09:44 +000068static cl::opt<bool> PollyRemarksMinimal(
69 "polly-remarks-minimal",
70 cl::desc("Do not emit remarks about assumptions that are known"),
71 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
72
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000073// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000074// operations can overflow easily. Additive reductions and bit operations
75// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000076static cl::opt<bool> DisableMultiplicativeReductions(
77 "polly-disable-multiplicative-reductions",
78 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
79 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000080
Johannes Doerfert9143d672014-09-27 11:02:39 +000081static cl::opt<unsigned> RunTimeChecksMaxParameters(
82 "polly-rtc-max-parameters",
83 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
84 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
85
Tobias Grosser71500722015-03-28 15:11:14 +000086static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
87 "polly-rtc-max-arrays-per-group",
88 cl::desc("The maximal number of arrays to compare in each alias group."),
89 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +000090
Tobias Grosser8a9c2352015-08-16 10:19:29 +000091static cl::opt<std::string> UserContextStr(
92 "polly-context", cl::value_desc("isl parameter set"),
93 cl::desc("Provide additional constraints on the context parameters"),
94 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000095
Tobias Grosserd83b8a82015-08-20 19:08:11 +000096static cl::opt<bool> DetectReductions("polly-detect-reductions",
97 cl::desc("Detect and exploit reductions"),
98 cl::Hidden, cl::ZeroOrMore,
99 cl::init(true), cl::cat(PollyCategory));
100
Tobias Grosser2937b592016-04-29 11:43:20 +0000101static cl::opt<bool>
102 IslOnErrorAbort("polly-on-isl-error-abort",
103 cl::desc("Abort if an isl error is encountered"),
104 cl::init(true), cl::cat(PollyCategory));
105
Michael Kruse7bf39442015-09-10 12:46:52 +0000106//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000107
Michael Kruse046dde42015-08-10 13:01:57 +0000108// Create a sequence of two schedules. Either argument may be null and is
109// interpreted as the empty schedule. Can also return null if both schedules are
110// empty.
111static __isl_give isl_schedule *
112combineInSequence(__isl_take isl_schedule *Prev,
113 __isl_take isl_schedule *Succ) {
114 if (!Prev)
115 return Succ;
116 if (!Succ)
117 return Prev;
118
119 return isl_schedule_sequence(Prev, Succ);
120}
121
Johannes Doerferte7044942015-02-24 11:58:30 +0000122static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
123 const ConstantRange &Range,
124 int dim,
125 enum isl_dim_type type) {
126 isl_val *V;
127 isl_ctx *ctx = isl_set_get_ctx(S);
128
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000129 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
130 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000131 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000132 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
133
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000134 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000135 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000136 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000137 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000138 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
139
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000140 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000141 return isl_set_union(SLB, SUB);
142 else
143 return isl_set_intersect(SLB, SUB);
144}
145
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000146static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
147 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
148 if (!BasePtrLI)
149 return nullptr;
150
Johannes Doerfert952b5302016-05-23 12:40:48 +0000151 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000152 return nullptr;
153
154 ScalarEvolution &SE = *S->getSE();
155
156 auto *OriginBaseSCEV =
157 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
158 if (!OriginBaseSCEV)
159 return nullptr;
160
161 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
162 if (!OriginBaseSCEVUnknown)
163 return nullptr;
164
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000165 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grossera535dff2015-12-13 19:59:01 +0000166 ScopArrayInfo::MK_Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000167}
168
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000169ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grossera535dff2015-12-13 19:59:01 +0000170 ArrayRef<const SCEV *> Sizes, enum MemoryKind Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000171 const DataLayout &DL, Scop *S)
172 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000173 std::string BasePtrName =
Tobias Grossera535dff2015-12-13 19:59:01 +0000174 getIslCompatibleName("MemRef_", BasePtr, Kind == MK_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000175 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000176
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000177 updateSizes(Sizes);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000178 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
179 if (BasePtrOriginSAI)
180 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000181}
182
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000183__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000184 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000185 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
186 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
187 return Space;
188}
189
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000190void ScopArrayInfo::updateElementType(Type *NewElementType) {
191 if (NewElementType == ElementType)
192 return;
193
Tobias Grosserd840fc72016-02-04 13:18:42 +0000194 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
195 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
196
Johannes Doerferta7920982016-02-25 14:08:48 +0000197 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000198 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000199
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000200 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
201 ElementType = NewElementType;
202 } else {
203 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
204 ElementType = IntegerType::get(ElementType->getContext(), GCD);
205 }
206}
207
208bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000209 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
210 int ExtraDimsNew = NewSizes.size() - SharedDims;
211 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Tobias Grosser8286b832015-11-02 11:29:32 +0000212 for (int i = 0; i < SharedDims; i++)
213 if (NewSizes[i + ExtraDimsNew] != DimensionSizes[i + ExtraDimsOld])
214 return false;
215
216 if (DimensionSizes.size() >= NewSizes.size())
217 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000218
219 DimensionSizes.clear();
220 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
221 NewSizes.end());
222 for (isl_pw_aff *Size : DimensionSizesPw)
223 isl_pw_aff_free(Size);
224 DimensionSizesPw.clear();
225 for (const SCEV *Expr : DimensionSizes) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000226 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000227 DimensionSizesPw.push_back(Size);
228 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000229 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000230}
231
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000232ScopArrayInfo::~ScopArrayInfo() {
233 isl_id_free(Id);
234 for (isl_pw_aff *Size : DimensionSizesPw)
235 isl_pw_aff_free(Size);
236}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000237
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000238std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
239
240int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000241 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000242}
243
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000244__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
245 return isl_id_copy(Id);
246}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000247
248void ScopArrayInfo::dump() const { print(errs()); }
249
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000250void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000251 OS.indent(8) << *getElementType() << " " << getName();
252 if (getNumberOfDimensions() > 0)
253 OS << "[*]";
Tobias Grosser26253842015-11-10 14:24:21 +0000254 for (unsigned u = 1; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000255 OS << "[";
256
Tobias Grosser26253842015-11-10 14:24:21 +0000257 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000258 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000259 OS << " " << Size << " ";
260 isl_pw_aff_free(Size);
261 } else {
262 OS << *getDimensionSize(u);
263 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000264
265 OS << "]";
266 }
267
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000268 OS << ";";
269
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000270 if (BasePtrOriginSAI)
271 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
272
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000273 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000274}
275
276const ScopArrayInfo *
277ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
278 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
279 assert(Id && "Output dimension didn't have an ID");
280 return getFromId(Id);
281}
282
283const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
284 void *User = isl_id_get_user(Id);
285 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
286 isl_id_free(Id);
287 return SAI;
288}
289
Michael Kruse3b425ff2016-04-11 14:34:08 +0000290void MemoryAccess::wrapConstantDimensions() {
291 auto *SAI = getScopArrayInfo();
292 auto *ArraySpace = SAI->getSpace();
293 auto *Ctx = isl_space_get_ctx(ArraySpace);
294 unsigned DimsArray = SAI->getNumberOfDimensions();
295
296 auto *DivModAff = isl_multi_aff_identity(isl_space_map_from_domain_and_range(
297 isl_space_copy(ArraySpace), isl_space_copy(ArraySpace)));
298 auto *LArraySpace = isl_local_space_from_space(ArraySpace);
299
300 // Begin with last dimension, to iteratively carry into higher dimensions.
301 for (int i = DimsArray - 1; i > 0; i--) {
302 auto *DimSize = SAI->getDimensionSize(i);
303 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
304
305 // This transformation is not applicable to dimensions with dynamic size.
306 if (!DimSizeCst)
307 continue;
308
309 auto *DimSizeVal = isl_valFromAPInt(Ctx, DimSizeCst->getAPInt(), false);
310 auto *Var = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
311 isl_dim_set, i);
312 auto *PrevVar = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
313 isl_dim_set, i - 1);
314
315 // Compute: index % size
316 // Modulo must apply in the divide of the previous iteration, if any.
317 auto *Modulo = isl_aff_copy(Var);
318 Modulo = isl_aff_mod_val(Modulo, isl_val_copy(DimSizeVal));
319 Modulo = isl_aff_pullback_multi_aff(Modulo, isl_multi_aff_copy(DivModAff));
320
321 // Compute: floor(index / size)
322 auto *Divide = Var;
323 Divide = isl_aff_div(
324 Divide,
325 isl_aff_val_on_domain(isl_local_space_copy(LArraySpace), DimSizeVal));
326 Divide = isl_aff_floor(Divide);
327 Divide = isl_aff_add(Divide, PrevVar);
328 Divide = isl_aff_pullback_multi_aff(Divide, isl_multi_aff_copy(DivModAff));
329
330 // Apply Modulo and Divide.
331 DivModAff = isl_multi_aff_set_aff(DivModAff, i, Modulo);
332 DivModAff = isl_multi_aff_set_aff(DivModAff, i - 1, Divide);
333 }
334
335 // Apply all modulo/divides on the accesses.
336 AccessRelation =
337 isl_map_apply_range(AccessRelation, isl_map_from_multi_aff(DivModAff));
338 AccessRelation = isl_map_detect_equalities(AccessRelation);
339 isl_local_space_free(LArraySpace);
340}
341
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000342void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000343 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000344 auto *ArraySpace = SAI->getSpace();
345 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000346 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000347
348 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
349 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
350 auto DimsMissing = DimsArray - DimsAccess;
351
Michael Kruse375cb5f2016-02-24 22:08:24 +0000352 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000353 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000354 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000355 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000356
Johannes Doerferta90943d2016-02-21 16:37:25 +0000357 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000358 isl_set_universe(AccessSpace),
359 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000360
361 for (unsigned i = 0; i < DimsMissing; i++)
362 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
363
364 for (unsigned i = DimsMissing; i < DimsArray; i++)
365 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
366
367 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000368
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000369 // For the non delinearized arrays, divide the access function of the last
370 // subscript by the size of the elements in the array.
371 //
372 // A stride one array access in C expressed as A[i] is expressed in
373 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
374 // two subsequent values of 'i' index two values that are stored next to
375 // each other in memory. By this division we make this characteristic
376 // obvious again. If the base pointer was accessed with offsets not divisible
377 // by the accesses element size, we will have choosen a smaller ArrayElemSize
378 // that divides the offsets of all accesses to this base pointer.
379 if (DimsAccess == 1) {
380 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
381 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
382 }
383
Michael Kruse3b425ff2016-04-11 14:34:08 +0000384 // We currently do this only if we added at least one dimension, which means
385 // some dimension's indices have not been specified, an indicator that some
386 // index values have been added together.
387 // TODO: Investigate general usefulness; Effect on unit tests is to make index
388 // expressions more complicated.
389 if (DimsMissing)
390 wrapConstantDimensions();
391
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000392 if (!isAffine())
393 computeBoundsOnAccessRelation(ArrayElemSize);
394
Tobias Grosserd840fc72016-02-04 13:18:42 +0000395 // Introduce multi-element accesses in case the type loaded by this memory
396 // access is larger than the canonical element type of the array.
397 //
398 // An access ((float *)A)[i] to an array char *A is modeled as
399 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000400 if (ElemBytes > ArrayElemSize) {
401 assert(ElemBytes % ArrayElemSize == 0 &&
402 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000403 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000404 isl_set_universe(isl_space_copy(ArraySpace)),
405 isl_set_universe(isl_space_copy(ArraySpace)));
406 for (unsigned i = 0; i < DimsArray - 1; i++)
407 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
408
Tobias Grosserd840fc72016-02-04 13:18:42 +0000409 isl_constraint *C;
410 isl_local_space *LS;
411
412 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000413 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
414
415 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
416 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000417 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000418 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
419 Map = isl_map_add_constraint(Map, C);
420
421 C = isl_constraint_alloc_inequality(LS);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000422 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000423 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
424 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
425 Map = isl_map_add_constraint(Map, C);
426 AccessRelation = isl_map_apply_range(AccessRelation, Map);
427 }
428
429 isl_space_free(ArraySpace);
430
Roman Gareev10595a12016-01-08 14:01:59 +0000431 assumeNoOutOfBound();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000432}
433
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000434const std::string
435MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
436 switch (RT) {
437 case MemoryAccess::RT_NONE:
438 llvm_unreachable("Requested a reduction operator string for a memory "
439 "access which isn't a reduction");
440 case MemoryAccess::RT_ADD:
441 return "+";
442 case MemoryAccess::RT_MUL:
443 return "*";
444 case MemoryAccess::RT_BOR:
445 return "|";
446 case MemoryAccess::RT_BXOR:
447 return "^";
448 case MemoryAccess::RT_BAND:
449 return "&";
450 }
451 llvm_unreachable("Unknown reduction type");
452 return "";
453}
454
Johannes Doerfertf6183392014-07-01 20:52:51 +0000455/// @brief Return the reduction type for a given binary operator
456static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
457 const Instruction *Load) {
458 if (!BinOp)
459 return MemoryAccess::RT_NONE;
460 switch (BinOp->getOpcode()) {
461 case Instruction::FAdd:
462 if (!BinOp->hasUnsafeAlgebra())
463 return MemoryAccess::RT_NONE;
464 // Fall through
465 case Instruction::Add:
466 return MemoryAccess::RT_ADD;
467 case Instruction::Or:
468 return MemoryAccess::RT_BOR;
469 case Instruction::Xor:
470 return MemoryAccess::RT_BXOR;
471 case Instruction::And:
472 return MemoryAccess::RT_BAND;
473 case Instruction::FMul:
474 if (!BinOp->hasUnsafeAlgebra())
475 return MemoryAccess::RT_NONE;
476 // Fall through
477 case Instruction::Mul:
478 if (DisableMultiplicativeReductions)
479 return MemoryAccess::RT_NONE;
480 return MemoryAccess::RT_MUL;
481 default:
482 return MemoryAccess::RT_NONE;
483 }
484}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000485
Tobias Grosser75805372011-04-29 06:27:02 +0000486MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000487 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000488 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000489 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000490 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000491}
492
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000493const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
494 isl_id *ArrayId = getArrayId();
495 void *User = isl_id_get_user(ArrayId);
496 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
497 isl_id_free(ArrayId);
498 return SAI;
499}
500
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000501__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000502 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
503}
504
Tobias Grosserd840fc72016-02-04 13:18:42 +0000505__isl_give isl_map *MemoryAccess::getAddressFunction() const {
506 return isl_map_lexmin(getAccessRelation());
507}
508
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000509__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
510 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000511 isl_map *Schedule, *ScheduledAccRel;
512 isl_union_set *UDomain;
513
514 UDomain = isl_union_set_from_set(getStatement()->getDomain());
515 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
516 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000517 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000518 return isl_pw_multi_aff_from_map(ScheduledAccRel);
519}
520
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000521__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000522 return isl_map_copy(AccessRelation);
523}
524
Johannes Doerferta99130f2014-10-13 12:58:03 +0000525std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000526 return stringFromIslObj(AccessRelation);
527}
528
Johannes Doerferta99130f2014-10-13 12:58:03 +0000529__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000530 return isl_map_get_space(AccessRelation);
531}
532
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000533__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000534 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000535}
536
Tobias Grosser6f730082015-09-05 07:46:47 +0000537std::string MemoryAccess::getNewAccessRelationStr() const {
538 return stringFromIslObj(NewAccessRelation);
539}
540
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000541__isl_give isl_basic_map *
542MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000543 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000544 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000545
Tobias Grosser084d8f72012-05-29 09:29:44 +0000546 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000547 isl_basic_set_universe(Statement->getDomainSpace()),
548 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000549}
550
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000551// Formalize no out-of-bound access assumption
552//
553// When delinearizing array accesses we optimistically assume that the
554// delinearized accesses do not access out of bound locations (the subscript
555// expression of each array evaluates for each statement instance that is
556// executed to a value that is larger than zero and strictly smaller than the
557// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000558// dimension for which we do not need to assume any upper bound. At this point
559// we formalize this assumption to ensure that at code generation time the
560// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000561//
562// To find the set of constraints necessary to avoid out of bound accesses, we
563// first build the set of data locations that are not within array bounds. We
564// then apply the reverse access relation to obtain the set of iterations that
565// may contain invalid accesses and reduce this set of iterations to the ones
566// that are actually executed by intersecting them with the domain of the
567// statement. If we now project out all loop dimensions, we obtain a set of
568// parameters that may cause statement instances to be executed that may
569// possibly yield out of bound memory accesses. The complement of these
570// constraints is the set of constraints that needs to be assumed to ensure such
571// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000572void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000573 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000574 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000575 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000576 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000577 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
578 isl_pw_aff *Var =
579 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
580 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
581
582 isl_set *DimOutside;
583
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000584 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000585 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000586 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
587 isl_space_dim(Space, isl_dim_set));
588 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
589 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000590
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000591 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000592
593 Outside = isl_set_union(Outside, DimOutside);
594 }
595
596 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
597 Outside = isl_set_intersect(Outside, Statement->getDomain());
598 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000599
600 // Remove divs to avoid the construction of overly complicated assumptions.
601 // Doing so increases the set of parameter combinations that are assumed to
602 // not appear. This is always save, but may make the resulting run-time check
603 // bail out more often than strictly necessary.
604 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000605 Outside = isl_set_complement(Outside);
Michael Kruse7071e8b2016-04-11 13:24:29 +0000606 const auto &Loc = getAccessInstruction()
607 ? getAccessInstruction()->getDebugLoc()
608 : DebugLoc();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000609 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
610 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000611 isl_space_free(Space);
612}
613
Johannes Doerfertcea61932016-02-21 19:13:19 +0000614void MemoryAccess::buildMemIntrinsicAccessRelation() {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000615 assert(isa<MemIntrinsic>(getAccessInstruction()));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000616 assert(Subscripts.size() == 2 && Sizes.size() == 0);
617
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000618 auto *SubscriptPWA = getPwAff(Subscripts[0]);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000619 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000620
621 isl_map *LengthMap;
622 if (Subscripts[1] == nullptr) {
623 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
624 } else {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000625 auto *LengthPWA = getPwAff(Subscripts[1]);
Johannes Doerferta7920982016-02-25 14:08:48 +0000626 LengthMap = isl_map_from_pw_aff(LengthPWA);
627 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
628 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
629 }
630 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
631 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000632 SubscriptMap =
633 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000634 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
635 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
636 getStatement()->getDomainId());
637}
638
Johannes Doerferte7044942015-02-24 11:58:30 +0000639void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
640 ScalarEvolution *SE = Statement->getParent()->getSE();
641
Johannes Doerfertcea61932016-02-21 19:13:19 +0000642 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000643 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000644 return;
645
646 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000647 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
648 return;
649
650 auto *PtrSCEV = SE->getSCEV(Ptr);
651 if (isa<SCEVCouldNotCompute>(PtrSCEV))
652 return;
653
654 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
655 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
656 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
657
658 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
659 if (Range.isFullSet())
660 return;
661
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000662 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000663 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000664 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000665 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000666 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000667
668 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000669 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000670
671 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
672 AccessRange =
673 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
674 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
675}
676
Michael Krusee2bccbb2015-09-18 19:59:43 +0000677__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000678 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000679 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000680
681 for (int i = Size - 2; i >= 0; --i) {
682 isl_space *Space;
683 isl_map *MapOne, *MapTwo;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000684 isl_pw_aff *DimSize = getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000685
686 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
687 isl_pw_aff_free(DimSize);
688 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
689
690 Space = isl_map_get_space(AccessRelation);
691 Space = isl_space_map_from_set(isl_space_range(Space));
692 Space = isl_space_align_params(Space, SpaceSize);
693
694 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
695 isl_id_free(ParamId);
696
697 MapOne = isl_map_universe(isl_space_copy(Space));
698 for (int j = 0; j < Size; ++j)
699 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
700 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
701
702 MapTwo = isl_map_universe(isl_space_copy(Space));
703 for (int j = 0; j < Size; ++j)
704 if (j < i || j > i + 1)
705 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
706
707 isl_local_space *LS = isl_local_space_from_space(Space);
708 isl_constraint *C;
709 C = isl_equality_alloc(isl_local_space_copy(LS));
710 C = isl_constraint_set_constant_si(C, -1);
711 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
712 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
713 MapTwo = isl_map_add_constraint(MapTwo, C);
714 C = isl_equality_alloc(LS);
715 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
716 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
717 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
718 MapTwo = isl_map_add_constraint(MapTwo, C);
719 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
720
721 MapOne = isl_map_union(MapOne, MapTwo);
722 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
723 }
724 return AccessRelation;
725}
726
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000727/// @brief Check if @p Expr is divisible by @p Size.
728static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000729 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000730 if (Size == 1)
731 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000732
733 // Only one factor needs to be divisible.
734 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
735 for (auto *FactorExpr : MulExpr->operands())
736 if (isDivisible(FactorExpr, Size, SE))
737 return true;
738 return false;
739 }
740
741 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
742 // to be divisble.
743 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
744 for (auto *OpExpr : NAryExpr->operands())
745 if (!isDivisible(OpExpr, Size, SE))
746 return false;
747 return true;
748 }
749
750 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
751 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
752 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
753 return MulSCEV == Expr;
754}
755
Michael Krusee2bccbb2015-09-18 19:59:43 +0000756void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
757 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000758
Johannes Doerfert85676e32016-04-23 14:32:34 +0000759 // Initialize the invalid domain which describes all iterations for which the
760 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000761 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
762 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
763 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000764
Michael Krusee2bccbb2015-09-18 19:59:43 +0000765 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000766 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000767
Michael Krusee2bccbb2015-09-18 19:59:43 +0000768 if (!isAffine()) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000769 if (isa<MemIntrinsic>(getAccessInstruction()))
770 buildMemIntrinsicAccessRelation();
771
Tobias Grosser4f967492013-06-23 05:21:18 +0000772 // We overapproximate non-affine accesses with a possible access to the
773 // whole array. For read accesses it does not make a difference, if an
774 // access must or may happen. However, for write accesses it is important to
775 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000776 if (!AccessRelation)
777 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
778
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000779 AccessRelation =
780 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000781 return;
782 }
783
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000784 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000785 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000786
Michael Krusee2bccbb2015-09-18 19:59:43 +0000787 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000788 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000789 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000790 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000791 }
792
Tobias Grosser5d51afe2016-02-02 16:46:45 +0000793 if (Sizes.size() >= 1 && !isa<SCEVConstant>(Sizes[0]))
Michael Krusee2bccbb2015-09-18 19:59:43 +0000794 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000795
Tobias Grosser79baa212014-04-10 08:38:02 +0000796 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000797 AccessRelation = isl_map_set_tuple_id(
798 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000799 AccessRelation =
800 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
801
Tobias Grosseraa660a92015-03-30 00:07:50 +0000802 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000803 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000804}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000805
Michael Krusecac948e2015-10-02 13:53:07 +0000806MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000807 AccessType AccType, Value *BaseAddress,
808 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000809 ArrayRef<const SCEV *> Subscripts,
810 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000811 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000812 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Johannes Doerfert85676e32016-04-23 14:32:34 +0000813 InvalidDomain(nullptr), BaseAddr(BaseAddress), BaseName(BaseName),
814 ElementType(ElementType), Sizes(Sizes.begin(), Sizes.end()),
815 AccessInstruction(AccessInst), AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000816 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000817 NewAccessRelation(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000818 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Johannes Doerfertcea61932016-02-21 19:13:19 +0000819 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000820
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000821 std::string IdName =
822 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000823 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
824}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000825
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000826void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +0000827 auto *Ctx = Statement->getParent()->getContext();
828 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
829 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +0000830}
831
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000832const std::string MemoryAccess::getReductionOperatorStr() const {
833 return MemoryAccess::getReductionOperatorStr(getReductionType());
834}
835
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000836__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
837
Johannes Doerfertf6183392014-07-01 20:52:51 +0000838raw_ostream &polly::operator<<(raw_ostream &OS,
839 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000840 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000841 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000842 else
843 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000844 return OS;
845}
846
Tobias Grosser75805372011-04-29 06:27:02 +0000847void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000848 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000849 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000850 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000851 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000852 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000853 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000854 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000855 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000856 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000857 break;
858 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000859 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000860 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000861 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000862 if (hasNewAccessRelation())
863 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000864}
865
Tobias Grosser74394f02013-01-14 22:40:23 +0000866void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000867
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000868__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
869 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +0000870 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
871 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
872 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000873}
874
Tobias Grosser75805372011-04-29 06:27:02 +0000875// Create a map in the size of the provided set domain, that maps from the
876// one element of the provided set domain to another element of the provided
877// set domain.
878// The mapping is limited to all points that are equal in all but the last
879// dimension and for which the last dimension of the input is strict smaller
880// than the last dimension of the output.
881//
882// getEqualAndLarger(set[i0, i1, ..., iX]):
883//
884// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
885// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
886//
Tobias Grosserf5338802011-10-06 00:03:35 +0000887static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000888 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000889 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000890 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000891
892 // Set all but the last dimension to be equal for the input and output
893 //
894 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
895 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000896 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000897 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000898
899 // Set the last dimension of the input to be strict smaller than the
900 // last dimension of the output.
901 //
902 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000903 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
904 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000905 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000906}
907
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000908__isl_give isl_set *
909MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000910 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000911 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000912 isl_space *Space = isl_space_range(isl_map_get_space(S));
913 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000914
Sebastian Popa00a0292012-12-18 07:46:06 +0000915 S = isl_map_reverse(S);
916 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000917
Sebastian Popa00a0292012-12-18 07:46:06 +0000918 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
919 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
920 NextScatt = isl_map_apply_domain(NextScatt, S);
921 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000922
Sebastian Popa00a0292012-12-18 07:46:06 +0000923 isl_set *Deltas = isl_map_deltas(NextScatt);
924 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000925}
926
Sebastian Popa00a0292012-12-18 07:46:06 +0000927bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000928 int StrideWidth) const {
929 isl_set *Stride, *StrideX;
930 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000931
Sebastian Popa00a0292012-12-18 07:46:06 +0000932 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000933 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000934 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
935 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
936 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
937 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000938 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000939
Tobias Grosser28dd4862012-01-24 16:42:16 +0000940 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000941 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000942
Tobias Grosser28dd4862012-01-24 16:42:16 +0000943 return IsStrideX;
944}
945
Sebastian Popa00a0292012-12-18 07:46:06 +0000946bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
947 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000948}
949
Sebastian Popa00a0292012-12-18 07:46:06 +0000950bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
951 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000952}
953
Tobias Grosser166c4222015-09-05 07:46:40 +0000954void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
955 isl_map_free(NewAccessRelation);
956 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000957}
Tobias Grosser75805372011-04-29 06:27:02 +0000958
959//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000960
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000961__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +0000962 isl_set *Domain = getDomain();
963 if (isl_set_is_empty(Domain)) {
964 isl_set_free(Domain);
965 return isl_map_from_aff(
966 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
967 }
968 auto *Schedule = getParent()->getSchedule();
969 Schedule = isl_union_map_intersect_domain(
970 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
971 if (isl_union_map_is_empty(Schedule)) {
972 isl_set_free(Domain);
973 isl_union_map_free(Schedule);
974 return isl_map_from_aff(
975 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
976 }
977 auto *M = isl_map_from_union_map(Schedule);
978 M = isl_map_coalesce(M);
979 M = isl_map_gist_domain(M, Domain);
980 M = isl_map_coalesce(M);
981 return M;
982}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000983
Johannes Doerfert3e48ee22016-04-29 10:44:41 +0000984__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
985 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000986 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
987 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +0000988}
989
Tobias Grosser37eb4222014-02-20 21:43:54 +0000990void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
991 assert(isl_set_is_subset(NewDomain, Domain) &&
992 "New domain is not a subset of old domain!");
993 isl_set_free(Domain);
994 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000995}
996
Michael Krusecac948e2015-10-02 13:53:07 +0000997void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000998 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +0000999 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001000 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001001
Tobias Grossera535dff2015-12-13 19:59:01 +00001002 ScopArrayInfo::MemoryKind Ty;
1003 if (Access->isPHIKind())
1004 Ty = ScopArrayInfo::MK_PHI;
1005 else if (Access->isExitPHIKind())
1006 Ty = ScopArrayInfo::MK_ExitPHI;
1007 else if (Access->isValueKind())
1008 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001009 else
Tobias Grossera535dff2015-12-13 19:59:01 +00001010 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001011
Johannes Doerfertadeab372016-02-07 13:57:32 +00001012 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
1013 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001014 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001015 }
1016}
1017
Michael Krusecac948e2015-10-02 13:53:07 +00001018void ScopStmt::addAccess(MemoryAccess *Access) {
1019 Instruction *AccessInst = Access->getAccessInstruction();
1020
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001021 if (Access->isArrayKind()) {
1022 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1023 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001024 } else if (Access->isValueKind() && Access->isWrite()) {
1025 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001026 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001027 assert(!ValueWrites.lookup(AccessVal));
1028
1029 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001030 } else if (Access->isValueKind() && Access->isRead()) {
1031 Value *AccessVal = Access->getAccessValue();
1032 assert(!ValueReads.lookup(AccessVal));
1033
1034 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001035 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1036 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
1037 assert(!PHIWrites.lookup(PHI));
1038
1039 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001040 }
1041
1042 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001043}
1044
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001045void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001046 for (MemoryAccess *MA : *this)
1047 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001048
Johannes Doerferta60ad842016-05-10 12:18:22 +00001049 auto *Ctx = Parent.getContext();
1050 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1051 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001052}
1053
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001054/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
1055static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1056 void *User) {
1057 isl_set **BoundedParts = static_cast<isl_set **>(User);
1058 if (isl_basic_set_is_bounded(BSet))
1059 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1060 else
1061 isl_basic_set_free(BSet);
1062 return isl_stat_ok;
1063}
1064
1065/// @brief Return the bounded parts of @p S.
1066static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1067 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1068 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1069 isl_set_free(S);
1070 return BoundedParts;
1071}
1072
1073/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
1074///
1075/// @returns A separation of @p S into first an unbounded then a bounded subset,
1076/// both with regards to the dimension @p Dim.
1077static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1078partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1079
1080 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001081 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001082
1083 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001084 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001085
1086 // Remove dimensions that are greater than Dim as they are not interesting.
1087 assert(NumDimsS >= Dim + 1);
1088 OnlyDimS =
1089 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1090
1091 // Create artificial parametric upper bounds for dimensions smaller than Dim
1092 // as we are not interested in them.
1093 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1094 for (unsigned u = 0; u < Dim; u++) {
1095 isl_constraint *C = isl_inequality_alloc(
1096 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1097 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1098 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1099 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1100 }
1101
1102 // Collect all bounded parts of OnlyDimS.
1103 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1104
1105 // Create the dimensions greater than Dim again.
1106 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1107 NumDimsS - Dim - 1);
1108
1109 // Remove the artificial upper bound parameters again.
1110 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1111
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001112 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001113 return std::make_pair(UnboundedParts, BoundedParts);
1114}
1115
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001116/// @brief Set the dimension Ids from @p From in @p To.
1117static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1118 __isl_take isl_set *To) {
1119 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1120 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1121 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1122 }
1123 return To;
1124}
1125
1126/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001127static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001128 __isl_take isl_pw_aff *L,
1129 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001130 switch (Pred) {
1131 case ICmpInst::ICMP_EQ:
1132 return isl_pw_aff_eq_set(L, R);
1133 case ICmpInst::ICMP_NE:
1134 return isl_pw_aff_ne_set(L, R);
1135 case ICmpInst::ICMP_SLT:
1136 return isl_pw_aff_lt_set(L, R);
1137 case ICmpInst::ICMP_SLE:
1138 return isl_pw_aff_le_set(L, R);
1139 case ICmpInst::ICMP_SGT:
1140 return isl_pw_aff_gt_set(L, R);
1141 case ICmpInst::ICMP_SGE:
1142 return isl_pw_aff_ge_set(L, R);
1143 case ICmpInst::ICMP_ULT:
1144 return isl_pw_aff_lt_set(L, R);
1145 case ICmpInst::ICMP_UGT:
1146 return isl_pw_aff_gt_set(L, R);
1147 case ICmpInst::ICMP_ULE:
1148 return isl_pw_aff_le_set(L, R);
1149 case ICmpInst::ICMP_UGE:
1150 return isl_pw_aff_ge_set(L, R);
1151 default:
1152 llvm_unreachable("Non integer predicate not supported");
1153 }
1154}
1155
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001156/// @brief Create the conditions under which @p L @p Pred @p R is true.
1157///
1158/// Helper function that will make sure the dimensions of the result have the
1159/// same isl_id's as the @p Domain.
1160static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1161 __isl_take isl_pw_aff *L,
1162 __isl_take isl_pw_aff *R,
1163 __isl_keep isl_set *Domain) {
1164 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1165 return setDimensionIds(Domain, ConsequenceCondSet);
1166}
1167
1168/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001169///
1170/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001171/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1172/// have as many elements as @p SI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001173static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001174buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1175 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001176 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1177
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001178 Value *Condition = getConditionFromTerminator(SI);
1179 assert(Condition && "No condition for switch");
1180
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001181 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001182 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001183 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001184 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001185
1186 unsigned NumSuccessors = SI->getNumSuccessors();
1187 ConditionSets.resize(NumSuccessors);
1188 for (auto &Case : SI->cases()) {
1189 unsigned Idx = Case.getSuccessorIndex();
1190 ConstantInt *CaseValue = Case.getCaseValue();
1191
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001192 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001193 isl_set *CaseConditionSet =
1194 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1195 ConditionSets[Idx] = isl_set_coalesce(
1196 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1197 }
1198
1199 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1200 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1201 for (unsigned u = 2; u < NumSuccessors; u++)
1202 ConditionSetUnion =
1203 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1204 ConditionSets[0] = setDimensionIds(
1205 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1206
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001207 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001208
1209 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001210}
1211
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001212/// @brief Build the conditions sets for the branch condition @p Condition in
1213/// the @p Domain.
1214///
1215/// This will fill @p ConditionSets with the conditions under which control
1216/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001217/// have as many elements as @p TI has successors. If @p TI is nullptr the
1218/// context under which @p Condition is true/false will be returned as the
1219/// new elements of @p ConditionSets.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001220static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001221buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1222 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001223 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1224
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001225 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001226 isl_set *ConsequenceCondSet = nullptr;
1227 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1228 if (CCond->isZero())
1229 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1230 else
1231 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1232 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1233 auto Opcode = BinOp->getOpcode();
1234 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1235
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001236 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1237 ConditionSets) &&
1238 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1239 ConditionSets);
1240 if (!Valid) {
1241 while (!ConditionSets.empty())
1242 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001243 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001244 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001245
1246 isl_set_free(ConditionSets.pop_back_val());
1247 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1248 isl_set_free(ConditionSets.pop_back_val());
1249 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1250
1251 if (Opcode == Instruction::And)
1252 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1253 else
1254 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1255 } else {
1256 auto *ICond = dyn_cast<ICmpInst>(Condition);
1257 assert(ICond &&
1258 "Condition of exiting branch was neither constant nor ICmp!");
1259
1260 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001261 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001262 // For unsigned comparisons we assumed the signed bit of neither operand
1263 // to be set. The comparison is equal to a signed comparison under this
1264 // assumption.
1265 bool NonNeg = ICond->isUnsigned();
1266 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1267 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001268 ConsequenceCondSet =
1269 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1270 }
1271
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001272 // If no terminator was given we are only looking for parameter constraints
1273 // under which @p Condition is true/false.
1274 if (!TI)
1275 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001276 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001277 ConsequenceCondSet = isl_set_coalesce(
1278 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001279
Johannes Doerfertb2885792016-04-26 09:20:41 +00001280 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001281 bool TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001282 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001283
Michael Krusef7a4a942016-05-02 12:25:36 +00001284 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001285 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1286 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001287 TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001288 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001289 }
1290
Michael Krusef7a4a942016-05-02 12:25:36 +00001291 if (TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001292 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001293 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001294 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001295 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001296 }
1297
1298 ConditionSets.push_back(ConsequenceCondSet);
1299 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001300
1301 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001302}
1303
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001304/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1305///
1306/// This will fill @p ConditionSets with the conditions under which control
1307/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1308/// have as many elements as @p TI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001309static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001310buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001311 __isl_keep isl_set *Domain,
1312 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1313
1314 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001315 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001316
1317 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1318
1319 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001320 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001321 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001322 }
1323
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001324 Value *Condition = getConditionFromTerminator(TI);
1325 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001326
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001327 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001328}
1329
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001330void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001331 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001332
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001333 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001334 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001335}
1336
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001337void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP, LoopInfo &LI) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001338 isl_ctx *Ctx = Parent.getIslCtx();
1339 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001340 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001341
1342 // The set of loads that are required to be invariant.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001343 auto &ScopRIL = Parent.getRequiredInvariantLoads();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001344
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001345 std::vector<const SCEV *> Subscripts;
1346 std::vector<int> Sizes;
1347
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001348 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001349
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001350 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001351
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001352 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001353
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001354 auto *NotExecuted = isl_set_complement(isl_set_params(getDomain()));
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001355 for (size_t i = 0; i < Sizes.size(); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001356 auto *Expr = Subscripts[i + IndexOffset];
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001357 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001358
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001359 auto *Scope = LI.getLoopFor(getEntryBlock());
Johannes Doerfert09e36972015-10-07 20:17:36 +00001360 InvariantLoadsSetTy AccessILS;
Johannes Doerfertec8a2172016-04-25 13:32:36 +00001361 if (!isAffineExpr(&Parent.getRegion(), Scope, Expr, SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +00001362 continue;
1363
1364 bool NonAffine = false;
1365 for (LoadInst *LInst : AccessILS)
1366 if (!ScopRIL.count(LInst))
1367 NonAffine = true;
1368
1369 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001370 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001371
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001372 isl_pw_aff *AccessOffset = getPwAff(Expr);
1373 AccessOffset =
1374 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001375
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001376 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1377 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001378
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001379 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1380 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1381 OutOfBound = isl_set_params(OutOfBound);
1382 isl_set *InBound = isl_set_complement(OutOfBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001383
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001384 // A => B == !A or B
1385 isl_set *InBoundIfExecuted =
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001386 isl_set_union(isl_set_copy(NotExecuted), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001387
Roman Gareev10595a12016-01-08 14:01:59 +00001388 InBoundIfExecuted = isl_set_coalesce(InBoundIfExecuted);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00001389 Parent.recordAssumption(INBOUNDS, InBoundIfExecuted, GEP->getDebugLoc(),
1390 AS_ASSUMPTION);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001391 }
1392
1393 isl_local_space_free(LSpace);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001394 isl_set_free(NotExecuted);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001395}
1396
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001397void ScopStmt::deriveAssumptions(LoopInfo &LI) {
Johannes Doerfertd5c369f2016-04-25 18:55:15 +00001398 for (auto *MA : *this) {
1399 if (!MA->isArrayKind())
1400 continue;
1401
1402 MemAccInst Acc(MA->getAccessInstruction());
1403 auto *GEP = dyn_cast_or_null<GetElementPtrInst>(Acc.getPointerOperand());
1404
1405 if (GEP)
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001406 deriveAssumptionsFromGEP(GEP, LI);
Johannes Doerfertd5c369f2016-04-25 18:55:15 +00001407 }
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001408}
1409
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001410void ScopStmt::collectSurroundingLoops() {
1411 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1412 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1413 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1414 isl_id_free(DimId);
1415 }
1416}
1417
Michael Kruse9d080092015-09-11 21:41:48 +00001418ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerferta3519512016-04-23 13:02:23 +00001419 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
1420 R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001421
Tobias Grosser16c44032015-07-09 07:31:45 +00001422 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001423}
1424
Michael Kruse9d080092015-09-11 21:41:48 +00001425ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerferta3519512016-04-23 13:02:23 +00001426 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
1427 R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001428
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001429 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001430}
1431
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001432void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001433 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001434
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001435 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001436 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001437 buildAccessRelations();
1438
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001439 deriveAssumptions(LI);
Michael Krusecac948e2015-10-02 13:53:07 +00001440
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001441 if (DetectReductions)
1442 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001443}
1444
Johannes Doerferte58a0122014-06-27 20:31:28 +00001445/// @brief Collect loads which might form a reduction chain with @p StoreMA
1446///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001447/// Check if the stored value for @p StoreMA is a binary operator with one or
1448/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001449/// used only once (by @p StoreMA) and its load operands are also used only
1450/// once, we have found a possible reduction chain. It starts at an operand
1451/// load and includes the binary operator and @p StoreMA.
1452///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001453/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001454/// escape this block or into any other store except @p StoreMA.
1455void ScopStmt::collectCandiateReductionLoads(
1456 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1457 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1458 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001459 return;
1460
1461 // Skip if there is not one binary operator between the load and the store
1462 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001463 if (!BinOp)
1464 return;
1465
1466 // Skip if the binary operators has multiple uses
1467 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001468 return;
1469
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001470 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001471 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1472 return;
1473
Johannes Doerfert9890a052014-07-01 00:32:29 +00001474 // Skip if the binary operator is outside the current SCoP
1475 if (BinOp->getParent() != Store->getParent())
1476 return;
1477
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001478 // Skip if it is a multiplicative reduction and we disabled them
1479 if (DisableMultiplicativeReductions &&
1480 (BinOp->getOpcode() == Instruction::Mul ||
1481 BinOp->getOpcode() == Instruction::FMul))
1482 return;
1483
Johannes Doerferte58a0122014-06-27 20:31:28 +00001484 // Check the binary operator operands for a candidate load
1485 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1486 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1487 if (!PossibleLoad0 && !PossibleLoad1)
1488 return;
1489
1490 // A load is only a candidate if it cannot escape (thus has only this use)
1491 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001492 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001493 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001494 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001495 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001496 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001497}
1498
1499/// @brief Check for reductions in this ScopStmt
1500///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001501/// Iterate over all store memory accesses and check for valid binary reduction
1502/// like chains. For all candidates we check if they have the same base address
1503/// and there are no other accesses which overlap with them. The base address
1504/// check rules out impossible reductions candidates early. The overlap check,
1505/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001506/// guarantees that none of the intermediate results will escape during
1507/// execution of the loop nest. We basically check here that no other memory
1508/// access can access the same memory as the potential reduction.
1509void ScopStmt::checkForReductions() {
1510 SmallVector<MemoryAccess *, 2> Loads;
1511 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1512
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001513 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001514 // stores and collecting possible reduction loads.
1515 for (MemoryAccess *StoreMA : MemAccs) {
1516 if (StoreMA->isRead())
1517 continue;
1518
1519 Loads.clear();
1520 collectCandiateReductionLoads(StoreMA, Loads);
1521 for (MemoryAccess *LoadMA : Loads)
1522 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1523 }
1524
1525 // Then check each possible candidate pair.
1526 for (const auto &CandidatePair : Candidates) {
1527 bool Valid = true;
1528 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1529 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1530
1531 // Skip those with obviously unequal base addresses.
1532 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1533 isl_map_free(LoadAccs);
1534 isl_map_free(StoreAccs);
1535 continue;
1536 }
1537
1538 // And check if the remaining for overlap with other memory accesses.
1539 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1540 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1541 isl_set *AllAccs = isl_map_range(AllAccsRel);
1542
1543 for (MemoryAccess *MA : MemAccs) {
1544 if (MA == CandidatePair.first || MA == CandidatePair.second)
1545 continue;
1546
1547 isl_map *AccRel =
1548 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1549 isl_set *Accs = isl_map_range(AccRel);
1550
1551 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1552 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1553 Valid = Valid && isl_set_is_empty(OverlapAccs);
1554 isl_set_free(OverlapAccs);
1555 }
1556 }
1557
1558 isl_set_free(AllAccs);
1559 if (!Valid)
1560 continue;
1561
Johannes Doerfertf6183392014-07-01 20:52:51 +00001562 const LoadInst *Load =
1563 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1564 MemoryAccess::ReductionType RT =
1565 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1566
Johannes Doerferte58a0122014-06-27 20:31:28 +00001567 // If no overlapping access was found we mark the load and store as
1568 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001569 CandidatePair.first->markAsReductionLike(RT);
1570 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001571 }
Tobias Grosser75805372011-04-29 06:27:02 +00001572}
1573
Tobias Grosser74394f02013-01-14 22:40:23 +00001574std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001575
Tobias Grosser54839312015-04-21 11:37:25 +00001576std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001577 auto *S = getSchedule();
1578 auto Str = stringFromIslObj(S);
1579 isl_map_free(S);
1580 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001581}
1582
Johannes Doerferta3519512016-04-23 13:02:23 +00001583void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1584 isl_set_free(InvalidDomain);
1585 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001586}
1587
Michael Kruse375cb5f2016-02-24 22:08:24 +00001588BasicBlock *ScopStmt::getEntryBlock() const {
1589 if (isBlockStmt())
1590 return getBasicBlock();
1591 return getRegion()->getEntry();
1592}
1593
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001594unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001595
Tobias Grosser75805372011-04-29 06:27:02 +00001596const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1597
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001598Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001599 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001600}
1601
Tobias Grosser74394f02013-01-14 22:40:23 +00001602isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001603
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001604__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001605
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001606__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001607 return isl_set_get_space(Domain);
1608}
1609
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001610__isl_give isl_id *ScopStmt::getDomainId() const {
1611 return isl_set_get_tuple_id(Domain);
1612}
Tobias Grossercd95b772012-08-30 11:49:38 +00001613
Johannes Doerfert7c013572016-04-12 09:57:34 +00001614ScopStmt::~ScopStmt() {
1615 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001616 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001617}
Tobias Grosser75805372011-04-29 06:27:02 +00001618
1619void ScopStmt::print(raw_ostream &OS) const {
1620 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001621 OS.indent(12) << "Domain :=\n";
1622
1623 if (Domain) {
1624 OS.indent(16) << getDomainStr() << ";\n";
1625 } else
1626 OS.indent(16) << "n/a\n";
1627
Tobias Grosser54839312015-04-21 11:37:25 +00001628 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001629
1630 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001631 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001632 } else
1633 OS.indent(16) << "n/a\n";
1634
Tobias Grosser083d3d32014-06-28 08:59:45 +00001635 for (MemoryAccess *Access : MemAccs)
1636 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001637}
1638
1639void ScopStmt::dump() const { print(dbgs()); }
1640
Michael Kruse10071822016-05-23 14:45:58 +00001641void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
1642 // Remove the memory accesses from this statement
1643 // together with all scalar accesses that were caused by it.
Michael Krusead28e5a2016-01-26 13:33:15 +00001644 // MK_Value READs have no access instruction, hence would not be removed by
1645 // this function. However, it is only used for invariant LoadInst accesses,
1646 // its arguments are always affine, hence synthesizable, and therefore there
1647 // are no MK_Value READ accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001648 auto Predicate = [&](MemoryAccess *Acc) {
1649 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1650 };
1651 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1652 MemAccs.end());
1653 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001654}
1655
Tobias Grosser75805372011-04-29 06:27:02 +00001656//===----------------------------------------------------------------------===//
1657/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001658
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001659void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001660 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1661 isl_set_free(Context);
1662 Context = NewContext;
1663}
1664
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001665/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1666struct SCEVSensitiveParameterRewriter
1667 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1668 ValueToValueMap &VMap;
1669 ScalarEvolution &SE;
1670
1671public:
1672 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1673 : VMap(VMap), SE(SE) {}
1674
1675 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1676 ValueToValueMap &VMap) {
1677 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1678 return SSPR.visit(E);
1679 }
1680
1681 const SCEV *visit(const SCEV *E) {
1682 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1683 }
1684
1685 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1686
1687 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1688 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1689 }
1690
1691 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1692 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1693 }
1694
1695 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1696 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1697 }
1698
1699 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1700 SmallVector<const SCEV *, 4> Operands;
1701 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1702 Operands.push_back(visit(E->getOperand(i)));
1703 return SE.getAddExpr(Operands);
1704 }
1705
1706 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1707 SmallVector<const SCEV *, 4> Operands;
1708 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1709 Operands.push_back(visit(E->getOperand(i)));
1710 return SE.getMulExpr(Operands);
1711 }
1712
1713 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1714 SmallVector<const SCEV *, 4> Operands;
1715 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1716 Operands.push_back(visit(E->getOperand(i)));
1717 return SE.getSMaxExpr(Operands);
1718 }
1719
1720 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1721 SmallVector<const SCEV *, 4> Operands;
1722 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1723 Operands.push_back(visit(E->getOperand(i)));
1724 return SE.getUMaxExpr(Operands);
1725 }
1726
1727 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1728 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1729 }
1730
1731 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1732 auto *Start = visit(E->getStart());
1733 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1734 visit(E->getStepRecurrence(SE)),
1735 E->getLoop(), SCEV::FlagAnyWrap);
1736 return SE.getAddExpr(Start, AddRec);
1737 }
1738
1739 const SCEV *visitUnknown(const SCEVUnknown *E) {
1740 if (auto *NewValue = VMap.lookup(E->getValue()))
1741 return SE.getUnknown(NewValue);
1742 return E;
1743 }
1744};
1745
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001746const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001747 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001748}
1749
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001750void Scop::createParameterId(const SCEV *Parameter) {
1751 assert(Parameters.count(Parameter));
1752 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001753
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001754 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001755
Tobias Grosser8f99c162011-11-15 11:38:55 +00001756 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1757 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001758
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001759 // If this parameter references a specific Value and this value has a name
1760 // we use this name as it is likely to be unique and more useful than just
1761 // a number.
1762 if (Val->hasName())
1763 ParameterName = Val->getName();
1764 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001765 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001766 if (LoadOrigin->hasName()) {
1767 ParameterName += "_loaded_from_";
1768 ParameterName +=
1769 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1770 }
1771 }
1772 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001773
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001774 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1775 const_cast<void *>((const void *)Parameter));
1776 ParameterIds[Parameter] = Id;
1777}
1778
1779void Scop::addParams(const ParameterSetTy &NewParameters) {
1780 for (const SCEV *Parameter : NewParameters) {
1781 // Normalize the SCEV to get the representing element for an invariant load.
1782 Parameter = extractConstantFactor(Parameter, *SE).second;
1783 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1784
1785 if (Parameters.insert(Parameter))
1786 createParameterId(Parameter);
1787 }
1788}
1789
1790__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
1791 // Normalize the SCEV to get the representing element for an invariant load.
1792 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1793 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001794}
Tobias Grosser75805372011-04-29 06:27:02 +00001795
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001796__isl_give isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001797 isl_set *DomainContext = isl_union_set_params(getDomains());
1798 return isl_set_intersect_params(C, DomainContext);
1799}
1800
Johannes Doerferte0b08072016-05-23 12:43:44 +00001801bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
1802 return DT.dominates(BB, getEntry());
1803}
1804
Hongbin Zheng192f69a2016-02-13 15:12:54 +00001805void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
1806 LoopInfo &LI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001807 auto &F = getFunction();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001808 for (auto &Assumption : AC.assumptions()) {
1809 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1810 if (!CI || CI->getNumArgOperands() != 1)
1811 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001812
Johannes Doerfert952b5302016-05-23 12:40:48 +00001813 bool InScop = contains(CI);
Johannes Doerferte0b08072016-05-23 12:43:44 +00001814 if (!InScop && !isDominatedBy(DT, CI->getParent()))
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001815 continue;
1816
Michael Kruse09eb4452016-03-03 22:10:47 +00001817 auto *L = LI.getLoopFor(CI->getParent());
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001818 auto *Val = CI->getArgOperand(0);
Johannes Doerfertf560b3d2016-04-25 13:33:07 +00001819 ParameterSetTy DetectedParams;
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001820 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001821 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1822 CI->getDebugLoc(),
1823 "Non-affine user assumption ignored.");
1824 continue;
1825 }
1826
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001827 // Collect all newly introduced parameters.
1828 ParameterSetTy NewParams;
1829 for (auto *Param : DetectedParams) {
1830 Param = extractConstantFactor(Param, *SE).second;
1831 Param = getRepresentingInvariantLoadSCEV(Param);
1832 if (Parameters.count(Param))
1833 continue;
1834 NewParams.insert(Param);
1835 }
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001836
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001837 SmallVector<isl_set *, 2> ConditionSets;
Johannes Doerfert952b5302016-05-23 12:40:48 +00001838 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
1839 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
1840 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001841 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
1842 isl_set_free(Dom);
1843
1844 if (!Valid)
Johannes Doerfert297c7202016-05-10 13:06:42 +00001845 continue;
1846
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001847 isl_set *AssumptionCtx = nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00001848 if (InScop) {
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001849 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
1850 isl_set_free(ConditionSets[0]);
1851 } else {
1852 AssumptionCtx = isl_set_complement(ConditionSets[1]);
1853 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
1854 }
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001855
1856 // Project out newly introduced parameters as they are not otherwise useful.
1857 if (!NewParams.empty()) {
1858 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
1859 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
1860 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
1861 isl_id_free(Id);
1862
1863 if (!NewParams.count(Param))
1864 continue;
1865
1866 AssumptionCtx =
1867 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
1868 }
1869 }
1870
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001871 emitOptimizationRemarkAnalysis(
1872 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1873 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1874 Context = isl_set_intersect(Context, AssumptionCtx);
1875 }
1876}
1877
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001878void Scop::addUserContext() {
1879 if (UserContextStr.empty())
1880 return;
1881
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001882 isl_set *UserContext =
1883 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001884 isl_space *Space = getParamSpace();
1885 if (isl_space_dim(Space, isl_dim_param) !=
1886 isl_set_dim(UserContext, isl_dim_param)) {
1887 auto SpaceStr = isl_space_to_str(Space);
1888 errs() << "Error: the context provided in -polly-context has not the same "
1889 << "number of dimensions than the computed context. Due to this "
1890 << "mismatch, the -polly-context option is ignored. Please provide "
1891 << "the context in the parameter space: " << SpaceStr << ".\n";
1892 free(SpaceStr);
1893 isl_set_free(UserContext);
1894 isl_space_free(Space);
1895 return;
1896 }
1897
1898 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001899 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1900 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001901
1902 if (strcmp(NameContext, NameUserContext) != 0) {
1903 auto SpaceStr = isl_space_to_str(Space);
1904 errs() << "Error: the name of dimension " << i
1905 << " provided in -polly-context "
1906 << "is '" << NameUserContext << "', but the name in the computed "
1907 << "context is '" << NameContext
1908 << "'. Due to this name mismatch, "
1909 << "the -polly-context option is ignored. Please provide "
1910 << "the context in the parameter space: " << SpaceStr << ".\n";
1911 free(SpaceStr);
1912 isl_set_free(UserContext);
1913 isl_space_free(Space);
1914 return;
1915 }
1916
1917 UserContext =
1918 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1919 isl_space_get_dim_id(Space, isl_dim_param, i));
1920 }
1921
1922 Context = isl_set_intersect(Context, UserContext);
1923 isl_space_free(Space);
1924}
1925
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001926void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00001927 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001928
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001929 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001930 for (LoadInst *LInst : RIL) {
1931 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1932
Johannes Doerfert96e54712016-02-07 17:30:13 +00001933 Type *Ty = LInst->getType();
1934 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001935 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001936 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001937 continue;
1938 }
1939
1940 ClassRep = LInst;
Johannes Doerfert96e54712016-02-07 17:30:13 +00001941 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(), nullptr,
1942 Ty);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001943 }
1944}
1945
Tobias Grosser6be480c2011-11-08 15:41:13 +00001946void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001947 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001948 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001949 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00001950 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001951}
1952
Tobias Grosser18daaca2012-05-22 10:47:27 +00001953void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001954 unsigned PDim = 0;
1955 for (auto *Parameter : Parameters) {
1956 ConstantRange SRange = SE->getSignedRange(Parameter);
1957 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001958 }
1959}
1960
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001961void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001962 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001963 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001964
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001965 unsigned PDim = 0;
1966 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001967 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001968 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001969 }
1970
1971 // Align the parameters of all data structures to the model.
1972 Context = isl_set_align_params(Context, Space);
1973
Johannes Doerferta60ad842016-05-10 12:18:22 +00001974 // As all parameters are known add bounds to them.
1975 addParameterBounds();
1976
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001977 for (ScopStmt &Stmt : *this)
1978 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00001979
1980 // Simplify the schedule according to the context too.
1981 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001982}
1983
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001984static __isl_give isl_set *
1985simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1986 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001987 // If we modelt all blocks in the SCoP that have side effects we can simplify
1988 // the context with the constraints that are needed for anything to be
1989 // executed at all. However, if we have error blocks in the SCoP we already
1990 // assumed some parameter combinations cannot occure and removed them from the
1991 // domains, thus we cannot use the remaining domain to simplify the
1992 // assumptions.
1993 if (!S.hasErrorBlock()) {
1994 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1995 AssumptionContext =
1996 isl_set_gist_params(AssumptionContext, DomainParameters);
1997 }
1998
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001999 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2000 return AssumptionContext;
2001}
2002
2003void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002004 // The parameter constraints of the iteration domains give us a set of
2005 // constraints that need to hold for all cases where at least a single
2006 // statement iteration is executed in the whole scop. We now simplify the
2007 // assumed context under the assumption that such constraints hold and at
2008 // least a single statement iteration is executed. For cases where no
2009 // statement instances are executed, the assumptions we have taken about
2010 // the executed code do not matter and can be changed.
2011 //
2012 // WARNING: This only holds if the assumptions we have taken do not reduce
2013 // the set of statement instances that are executed. Otherwise we
2014 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002015 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002016 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002017 // performed. In such a case, modifying the run-time conditions and
2018 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002019 // to not be executed.
2020 //
2021 // Example:
2022 //
2023 // When delinearizing the following code:
2024 //
2025 // for (long i = 0; i < 100; i++)
2026 // for (long j = 0; j < m; j++)
2027 // A[i+p][j] = 1.0;
2028 //
2029 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002030 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002031 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002032 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002033 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002034}
2035
Johannes Doerfertb164c792014-09-18 11:17:17 +00002036/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002037static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002038 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
2039 isl_pw_multi_aff *MinPMA, *MaxPMA;
2040 isl_pw_aff *LastDimAff;
2041 isl_aff *OneAff;
2042 unsigned Pos;
2043
Johannes Doerfert6296d952016-04-22 11:38:19 +00002044 Set = isl_set_remove_divs(Set);
2045
Michael Krusebc150122016-05-02 12:25:18 +00002046 if (isl_set_n_basic_set(Set) >= MaxDisjunctionsInDomain) {
Johannes Doerfert6296d952016-04-22 11:38:19 +00002047 isl_set_free(Set);
2048 return isl_stat_error;
2049 }
2050
Johannes Doerfert9143d672014-09-27 11:02:39 +00002051 // Restrict the number of parameters involved in the access as the lexmin/
2052 // lexmax computation will take too long if this number is high.
2053 //
2054 // Experiments with a simple test case using an i7 4800MQ:
2055 //
2056 // #Parameters involved | Time (in sec)
2057 // 6 | 0.01
2058 // 7 | 0.04
2059 // 8 | 0.12
2060 // 9 | 0.40
2061 // 10 | 1.54
2062 // 11 | 6.78
2063 // 12 | 30.38
2064 //
2065 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2066 unsigned InvolvedParams = 0;
2067 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2068 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2069 InvolvedParams++;
2070
2071 if (InvolvedParams > RunTimeChecksMaxParameters) {
2072 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002073 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002074 }
2075 }
2076
Johannes Doerfertb164c792014-09-18 11:17:17 +00002077 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2078 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2079
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002080 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2081 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2082
Johannes Doerfertb164c792014-09-18 11:17:17 +00002083 // Adjust the last dimension of the maximal access by one as we want to
2084 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2085 // we test during code generation might now point after the end of the
2086 // allocated array but we will never dereference it anyway.
2087 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2088 "Assumed at least one output dimension");
2089 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2090 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2091 OneAff = isl_aff_zero_on_domain(
2092 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2093 OneAff = isl_aff_add_constant_si(OneAff, 1);
2094 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2095 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2096
2097 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2098
2099 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002100 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002101}
2102
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002103static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2104 isl_set *Domain = MA->getStatement()->getDomain();
2105 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2106 return isl_set_reset_tuple_id(Domain);
2107}
2108
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002109/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
2110static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00002111 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002112 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002113
2114 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2115 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002116 Locations = isl_union_set_coalesce(Locations);
2117 Locations = isl_union_set_detect_equalities(Locations);
2118 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002119 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002120 isl_union_set_free(Locations);
2121 return Valid;
2122}
2123
Johannes Doerfert96425c22015-08-30 21:13:53 +00002124/// @brief Helper to treat non-affine regions and basic blocks the same.
2125///
2126///{
2127
2128/// @brief Return the block that is the representing block for @p RN.
2129static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2130 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2131 : RN->getNodeAs<BasicBlock>();
2132}
2133
2134/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002135static inline BasicBlock *
2136getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002137 if (RN->isSubRegion()) {
2138 assert(idx == 0);
2139 return RN->getNodeAs<Region>()->getExit();
2140 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002141 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002142}
2143
2144/// @brief Return the smallest loop surrounding @p RN.
2145static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2146 if (!RN->isSubRegion())
2147 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2148
2149 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2150 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2151 while (L && NonAffineSubRegion->contains(L))
2152 L = L->getParentLoop();
2153 return L;
2154}
2155
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002156static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2157 if (!RN->isSubRegion())
2158 return 1;
2159
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002160 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002161 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002162}
2163
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002164static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2165 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002166 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002167 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002168 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002169 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002170 return true;
2171 return false;
2172}
2173
Johannes Doerfert96425c22015-08-30 21:13:53 +00002174///}
2175
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002176static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2177 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002178 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002179 isl_id *DimId =
2180 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2181 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2182}
2183
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002184__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002185 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002186}
2187
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002188__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002189 auto DIt = DomainMap.find(BB);
2190 if (DIt != DomainMap.end())
2191 return isl_set_copy(DIt->getSecond());
2192
2193 auto &RI = *R.getRegionInfo();
2194 auto *BBR = RI.getRegionFor(BB);
2195 while (BBR->getEntry() == BB)
2196 BBR = BBR->getParent();
2197 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002198}
2199
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002200bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002201
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002202 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002203 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002204 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2205 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002206 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002207
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002208 while (LD-- >= 0) {
2209 S = addDomainDimId(S, LD + 1, L);
2210 L = L->getParentLoop();
2211 }
2212
Johannes Doerferta3519512016-04-23 13:02:23 +00002213 // Initialize the invalid domain.
2214 auto *EntryStmt = getStmtFor(EntryBB);
2215 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2216
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002217 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002218
Johannes Doerfert432658d2016-01-26 11:01:41 +00002219 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002220 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002221
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002222 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002223 return false;
2224
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002225 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002226 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002227
2228 // Error blocks and blocks dominated by them have been assumed to never be
2229 // executed. Representing them in the Scop does not add any value. In fact,
2230 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002231 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002232 // will cause problems when building up a ScopStmt for them.
2233 // Furthermore, basic blocks dominated by error blocks may reference
2234 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002235 // can themselves not be constructed properly. To this end we will replace
2236 // the domains of error blocks and those only reachable via error blocks
2237 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002238 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002239 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002240 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002241 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002242
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002243 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002244}
2245
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002246static Loop *getFirstNonBoxedLoopFor(BasicBlock *BB, LoopInfo &LI,
2247 const BoxedLoopsSetTy &BoxedLoops) {
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002248 auto *L = LI.getLoopFor(BB);
2249 while (BoxedLoops.count(L))
2250 L = L->getParentLoop();
2251 return L;
2252}
2253
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002254/// @brief Adjust the dimensions of @p Dom that was constructed for @p OldL
2255/// to be compatible to domains constructed for loop @p NewL.
2256///
2257/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2258/// edge from @p OldL to @p NewL.
2259static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2260 __isl_take isl_set *Dom,
2261 Loop *OldL, Loop *NewL) {
2262
2263 // If the loops are the same there is nothing to do.
2264 if (NewL == OldL)
2265 return Dom;
2266
2267 int OldDepth = S.getRelativeLoopDepth(OldL);
2268 int NewDepth = S.getRelativeLoopDepth(NewL);
2269 // If both loops are non-affine loops there is nothing to do.
2270 if (OldDepth == -1 && NewDepth == -1)
2271 return Dom;
2272
2273 // Distinguish three cases:
2274 // 1) The depth is the same but the loops are not.
2275 // => One loop was left one was entered.
2276 // 2) The depth increased from OldL to NewL.
2277 // => One loop was entered, none was left.
2278 // 3) The depth decreased from OldL to NewL.
2279 // => Loops were left were difference of the depths defines how many.
2280 if (OldDepth == NewDepth) {
2281 assert(OldL->getParentLoop() == NewL->getParentLoop());
2282 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2283 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2284 Dom = addDomainDimId(Dom, NewDepth, NewL);
2285 } else if (OldDepth < NewDepth) {
2286 assert(OldDepth + 1 == NewDepth);
2287 auto &R = S.getRegion();
2288 (void)R;
2289 assert(NewL->getParentLoop() == OldL ||
2290 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2291 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2292 Dom = addDomainDimId(Dom, NewDepth, NewL);
2293 } else {
2294 assert(OldDepth > NewDepth);
2295 int Diff = OldDepth - NewDepth;
2296 int NumDim = isl_set_n_dim(Dom);
2297 assert(NumDim >= Diff);
2298 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2299 }
2300
2301 return Dom;
2302}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002303
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002304bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2305 LoopInfo &LI) {
2306 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002307
2308 ReversePostOrderTraversal<Region *> RTraversal(R);
2309 for (auto *RN : RTraversal) {
2310
2311 // Recurse for affine subregions but go on for basic blocks and non-affine
2312 // subregions.
2313 if (RN->isSubRegion()) {
2314 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002315 if (!isNonAffineSubRegion(SubRegion)) {
2316 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002317 continue;
2318 }
2319 }
2320
2321 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2322 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002323 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002324 isl_set *&Domain = DomainMap[BB];
2325 assert(Domain && "Cannot propagate a nullptr");
2326
Johannes Doerferta3519512016-04-23 13:02:23 +00002327 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002328 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002329 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002330
Johannes Doerferta3519512016-04-23 13:02:23 +00002331 if (!IsInvalidBlock) {
2332 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002333 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002334 isl_set_free(InvalidDomain);
2335 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002336 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2337 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2338 AS_RESTRICTION);
2339 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002340 }
2341
Johannes Doerferta3519512016-04-23 13:02:23 +00002342 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002343 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002344 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002345 }
2346
Johannes Doerferta3519512016-04-23 13:02:23 +00002347 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002348 auto *TI = BB->getTerminator();
2349 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2350 for (unsigned u = 0; u < NumSuccs; u++) {
2351 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002352 auto *SuccStmt = getStmtFor(SuccBB);
2353
2354 // Skip successors outside the SCoP.
2355 if (!SuccStmt)
2356 continue;
2357
Johannes Doerferte4459a22016-04-25 13:34:50 +00002358 // Skip backedges.
2359 if (DT.dominates(SuccBB, BB))
2360 continue;
2361
Johannes Doerferta3519512016-04-23 13:02:23 +00002362 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
2363 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2364 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2365 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2366 SuccInvalidDomain =
2367 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2368 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2369 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2370 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002371
Michael Krusebc150122016-05-02 12:25:18 +00002372 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002373 // In case this happens we will bail.
Michael Krusebc150122016-05-02 12:25:18 +00002374 if (NumConjucts < MaxDisjunctionsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002375 continue;
2376
Johannes Doerferta3519512016-04-23 13:02:23 +00002377 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002378 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002379 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002380 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002381
2382 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002383 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002384
2385 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002386}
2387
Johannes Doerfert642594a2016-04-04 07:57:39 +00002388void Scop::propagateDomainConstraintsToRegionExit(
2389 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002390 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002391
2392 // Check if the block @p BB is the entry of a region. If so we propagate it's
2393 // domain to the exit block of the region. Otherwise we are done.
2394 auto *RI = R.getRegionInfo();
2395 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2396 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002397 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002398 return;
2399
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002400 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002401 // Do not propagate the domain if there is a loop backedge inside the region
2402 // that would prevent the exit block from beeing executed.
2403 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002404 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002405 SmallVector<BasicBlock *, 4> LatchBBs;
2406 BBLoop->getLoopLatches(LatchBBs);
2407 for (auto *LatchBB : LatchBBs)
2408 if (BB != LatchBB && BBReg->contains(LatchBB))
2409 return;
2410 L = L->getParentLoop();
2411 }
2412
2413 auto *Domain = DomainMap[BB];
2414 assert(Domain && "Cannot propagate a nullptr");
2415
2416 auto *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, BoxedLoops);
2417
2418 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2419 // adjust the domain before we can propagate it.
2420 auto *AdjustedDomain =
2421 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2422 auto *&ExitDomain = DomainMap[ExitBB];
2423
2424 // If the exit domain is not yet created we set it otherwise we "add" the
2425 // current domain.
2426 ExitDomain =
2427 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2428
Johannes Doerferta3519512016-04-23 13:02:23 +00002429 // Initialize the invalid domain.
2430 auto *ExitStmt = getStmtFor(ExitBB);
2431 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2432
Johannes Doerfert642594a2016-04-04 07:57:39 +00002433 FinishedExitBlocks.insert(ExitBB);
2434}
2435
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002436bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2437 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002438 // To create the domain for each block in R we iterate over all blocks and
2439 // subregions in R and propagate the conditions under which the current region
2440 // element is executed. To this end we iterate in reverse post order over R as
2441 // it ensures that we first visit all predecessors of a region node (either a
2442 // basic block or a subregion) before we visit the region node itself.
2443 // Initially, only the domain for the SCoP region entry block is set and from
2444 // there we propagate the current domain to all successors, however we add the
2445 // condition that the successor is actually executed next.
2446 // As we are only interested in non-loop carried constraints here we can
2447 // simply skip loop back edges.
2448
Johannes Doerfert642594a2016-04-04 07:57:39 +00002449 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002450 ReversePostOrderTraversal<Region *> RTraversal(R);
2451 for (auto *RN : RTraversal) {
2452
2453 // Recurse for affine subregions but go on for basic blocks and non-affine
2454 // subregions.
2455 if (RN->isSubRegion()) {
2456 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002457 if (!isNonAffineSubRegion(SubRegion)) {
2458 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002459 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002460 continue;
2461 }
2462 }
2463
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002464 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002465 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002466
Johannes Doerfert96425c22015-08-30 21:13:53 +00002467 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002468 TerminatorInst *TI = BB->getTerminator();
2469
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002470 if (isa<UnreachableInst>(TI))
2471 continue;
2472
Johannes Doerfertf5673802015-10-01 23:48:18 +00002473 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002474 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002475 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002476 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002477
Johannes Doerfert642594a2016-04-04 07:57:39 +00002478 auto *BBLoop = getRegionNodeLoop(RN, LI);
2479 // Propagate the domain from BB directly to blocks that have a superset
2480 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002481 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002482
2483 // If all successors of BB have been set a domain through the propagation
2484 // above we do not need to build condition sets but can just skip this
2485 // block. However, it is important to note that this is a local property
2486 // with regards to the region @p R. To this end FinishedExitBlocks is a
2487 // local variable.
2488 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2489 return FinishedExitBlocks.count(SuccBB);
2490 };
2491 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2492 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002493
2494 // Build the condition sets for the successor nodes of the current region
2495 // node. If it is a non-affine subregion we will always execute the single
2496 // exit node, hence the single entry node domain is the condition set. For
2497 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002498 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002499 if (RN->isSubRegion())
2500 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002501 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2502 ConditionSets))
2503 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002504
2505 // Now iterate over the successors and set their initial domain based on
2506 // their condition set. We skip back edges here and have to be careful when
2507 // we leave a loop not to keep constraints over a dimension that doesn't
2508 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002509 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002510 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002511 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002512 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002513
Johannes Doerfert535de032016-04-19 14:49:05 +00002514 auto *SuccStmt = getStmtFor(SuccBB);
2515 // Skip blocks outside the region.
2516 if (!SuccStmt) {
2517 isl_set_free(CondSet);
2518 continue;
2519 }
2520
Johannes Doerfert642594a2016-04-04 07:57:39 +00002521 // If we propagate the domain of some block to "SuccBB" we do not have to
2522 // adjust the domain.
2523 if (FinishedExitBlocks.count(SuccBB)) {
2524 isl_set_free(CondSet);
2525 continue;
2526 }
2527
Johannes Doerfert96425c22015-08-30 21:13:53 +00002528 // Skip back edges.
2529 if (DT.dominates(SuccBB, BB)) {
2530 isl_set_free(CondSet);
2531 continue;
2532 }
2533
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002534 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002535 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002536 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002537
2538 // Set the domain for the successor or merge it with an existing domain in
2539 // case there are multiple paths (without loop back edges) to the
2540 // successor block.
2541 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002542
Johannes Doerferta3519512016-04-23 13:02:23 +00002543 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002544 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002545 } else {
2546 // Initialize the invalid domain.
2547 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2548 SuccDomain = CondSet;
2549 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002550
Michael Krusebc150122016-05-02 12:25:18 +00002551 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002552 // In case this happens we will clean up and bail.
Michael Krusebc150122016-05-02 12:25:18 +00002553 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctionsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002554 continue;
2555
2556 invalidate(COMPLEXITY, DebugLoc());
2557 while (++u < ConditionSets.size())
2558 isl_set_free(ConditionSets[u]);
2559 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002560 }
2561 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002562
2563 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002564}
2565
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00002566__isl_give isl_set *Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2567 isl_set *Domain,
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00002568 DominatorTree &DT,
2569 LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002570 // If @p BB is the ScopEntry we are done
2571 if (R.getEntry() == BB)
2572 return isl_set_universe(isl_set_get_space(Domain));
2573
2574 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002575 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002576
2577 // The region info of this function.
2578 auto &RI = *R.getRegionInfo();
2579
2580 auto *BBLoop = getFirstNonBoxedLoopFor(BB, LI, BoxedLoops);
2581
2582 // A domain to collect all predecessor domains, thus all conditions under
2583 // which the block is executed. To this end we start with the empty domain.
2584 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2585
2586 // Set of regions of which the entry block domain has been propagated to BB.
2587 // all predecessors inside any of the regions can be skipped.
2588 SmallSet<Region *, 8> PropagatedRegions;
2589
2590 for (auto *PredBB : predecessors(BB)) {
2591 // Skip backedges.
2592 if (DT.dominates(BB, PredBB))
2593 continue;
2594
2595 // If the predecessor is in a region we used for propagation we can skip it.
2596 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2597 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2598 PredBBInRegion)) {
2599 continue;
2600 }
2601
2602 // Check if there is a valid region we can use for propagation, thus look
2603 // for a region that contains the predecessor and has @p BB as exit block.
2604 auto *PredR = RI.getRegionFor(PredBB);
2605 while (PredR->getExit() != BB && !PredR->contains(BB))
2606 PredR->getParent();
2607
2608 // If a valid region for propagation was found use the entry of that region
2609 // for propagation, otherwise the PredBB directly.
2610 if (PredR->getExit() == BB) {
2611 PredBB = PredR->getEntry();
2612 PropagatedRegions.insert(PredR);
2613 }
2614
Johannes Doerfert41cda152016-04-08 10:32:26 +00002615 auto *PredBBDom = getDomainConditions(PredBB);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002616 auto *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, BoxedLoops);
2617 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2618
2619 PredDom = isl_set_union(PredDom, PredBBDom);
2620 }
2621
2622 return PredDom;
2623}
2624
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002625bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2626 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002627 // Iterate over the region R and propagate the domain constrains from the
2628 // predecessors to the current node. In contrast to the
2629 // buildDomainsWithBranchConstraints function, this one will pull the domain
2630 // information from the predecessors instead of pushing it to the successors.
2631 // Additionally, we assume the domains to be already present in the domain
2632 // map here. However, we iterate again in reverse post order so we know all
2633 // predecessors have been visited before a block or non-affine subregion is
2634 // visited.
2635
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002636 ReversePostOrderTraversal<Region *> RTraversal(R);
2637 for (auto *RN : RTraversal) {
2638
2639 // Recurse for affine subregions but go on for basic blocks and non-affine
2640 // subregions.
2641 if (RN->isSubRegion()) {
2642 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002643 if (!isNonAffineSubRegion(SubRegion)) {
2644 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002645 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002646 continue;
2647 }
2648 }
2649
2650 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002651 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002652 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002653
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002654 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002655 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002656 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002657 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002658
Johannes Doerfert642594a2016-04-04 07:57:39 +00002659 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002660 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002661 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
2662 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002663 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002664
2665 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002666}
2667
2668/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2669/// is incremented by one and all other dimensions are equal, e.g.,
2670/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2671/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2672static __isl_give isl_map *
2673createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2674 auto *MapSpace = isl_space_map_from_set(SetSpace);
2675 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2676 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2677 if (u != Dim)
2678 NextIterationMap =
2679 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2680 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2681 C = isl_constraint_set_constant_si(C, 1);
2682 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2683 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2684 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2685 return NextIterationMap;
2686}
2687
Johannes Doerfert297c7202016-05-10 13:06:42 +00002688bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002689 int LoopDepth = getRelativeLoopDepth(L);
2690 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002691
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002692 BasicBlock *HeaderBB = L->getHeader();
2693 assert(DomainMap.count(HeaderBB));
2694 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002695
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002696 isl_map *NextIterationMap =
2697 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002698
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002699 isl_set *UnionBackedgeCondition =
2700 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002701
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002702 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2703 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002704
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002705 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002706
2707 // If the latch is only reachable via error statements we skip it.
2708 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2709 if (!LatchBBDom)
2710 continue;
2711
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002712 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002713
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002714 TerminatorInst *TI = LatchBB->getTerminator();
2715 BranchInst *BI = dyn_cast<BranchInst>(TI);
2716 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002717 BackedgeCondition = isl_set_copy(LatchBBDom);
2718 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002719 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002720 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00002721 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
2722 ConditionSets))
2723 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002724
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002725 // Free the non back edge condition set as we do not need it.
2726 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002727
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002728 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002729 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002730
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002731 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2732 assert(LatchLoopDepth >= LoopDepth);
2733 BackedgeCondition =
2734 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2735 LatchLoopDepth - LoopDepth);
2736 UnionBackedgeCondition =
2737 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002738 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002739
2740 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2741 for (int i = 0; i < LoopDepth; i++)
2742 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2743
2744 isl_set *UnionBackedgeConditionComplement =
2745 isl_set_complement(UnionBackedgeCondition);
2746 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2747 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2748 UnionBackedgeConditionComplement =
2749 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2750 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2751 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2752
2753 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2754 HeaderBBDom = Parts.second;
2755
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002756 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2757 // the bounded assumptions to the context as they are already implied by the
2758 // <nsw> tag.
2759 if (Affinator.hasNSWAddRecForLoop(L)) {
2760 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002761 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002762 }
2763
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002764 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002765 recordAssumption(INFINITELOOP, UnboundedCtx,
2766 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002767 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002768}
2769
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002770MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
2771 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2772 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2773 if (!PointerBase)
2774 return nullptr;
2775
2776 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase->getValue());
2777 if (!PointerBaseInst)
2778 return nullptr;
2779
2780 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
2781 if (!BasePtrStmt)
2782 return nullptr;
2783
2784 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
2785}
2786
2787bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
2788 __isl_keep isl_union_map *Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00002789 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
2790 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
2791 bool Hoistable = NHCtx != nullptr;
2792 isl_set_free(NHCtx);
2793 return !Hoistable;
2794 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002795
2796 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2797 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2798 if (auto *BasePtrInst = dyn_cast<Instruction>(PointerBase->getValue()))
2799 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00002800 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002801
2802 return false;
2803}
2804
Johannes Doerfert5210da52016-06-02 11:06:54 +00002805bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002806 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00002807 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002808
2809 if (buildAliasGroups(AA))
Johannes Doerfert5210da52016-06-02 11:06:54 +00002810 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002811
2812 // If a problem occurs while building the alias groups we need to delete
2813 // this SCoP and pretend it wasn't valid in the first place. To this end
2814 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002815 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002816
2817 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2818 << " could not be created as the number of parameters involved "
2819 "is too high. The SCoP will be "
2820 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2821 "the maximal number of parameters but be advised that the "
2822 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00002823 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002824}
2825
Johannes Doerfert9143d672014-09-27 11:02:39 +00002826bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002827 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002828 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002829 // for all memory accesses inside the SCoP.
2830 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002831 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002832 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002833 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002834 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002835 // if their access domains intersect, otherwise they are in different
2836 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002837 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002838 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002839 // and maximal accesses to each array of a group in read only and non
2840 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002841 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2842
2843 AliasSetTracker AST(AA);
2844
2845 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002846 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002847 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002848
2849 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002850 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002851 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2852 isl_set_free(StmtDomain);
2853 if (StmtDomainEmpty)
2854 continue;
2855
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002856 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002857 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002858 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002859 if (!MA->isRead())
2860 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002861 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00002862 if (MA->isRead() && isa<MemTransferInst>(Acc))
2863 PtrToAcc[cast<MemTransferInst>(Acc)->getSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00002864 else
2865 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002866 AST.add(Acc);
2867 }
2868 }
2869
2870 SmallVector<AliasGroupTy, 4> AliasGroups;
2871 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002872 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002873 continue;
2874 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00002875 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00002876 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00002877 if (AG.size() < 2)
2878 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002879 AliasGroups.push_back(std::move(AG));
2880 }
2881
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002882 // Split the alias groups based on their domain.
2883 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2884 AliasGroupTy NewAG;
2885 AliasGroupTy &AG = AliasGroups[u];
2886 AliasGroupTy::iterator AGI = AG.begin();
2887 isl_set *AGDomain = getAccessDomain(*AGI);
2888 while (AGI != AG.end()) {
2889 MemoryAccess *MA = *AGI;
2890 isl_set *MADomain = getAccessDomain(MA);
2891 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2892 NewAG.push_back(MA);
2893 AGI = AG.erase(AGI);
2894 isl_set_free(MADomain);
2895 } else {
2896 AGDomain = isl_set_union(AGDomain, MADomain);
2897 AGI++;
2898 }
2899 }
2900 if (NewAG.size() > 1)
2901 AliasGroups.push_back(std::move(NewAG));
2902 isl_set_free(AGDomain);
2903 }
2904
Johannes Doerfert3f52e352016-05-23 12:38:05 +00002905 auto &F = getFunction();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002906 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002907 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2908 for (AliasGroupTy &AG : AliasGroups) {
2909 NonReadOnlyBaseValues.clear();
2910 ReadOnlyPairs.clear();
2911
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002912 if (AG.size() < 2) {
2913 AG.clear();
2914 continue;
2915 }
2916
Johannes Doerfert13771732014-10-01 12:40:46 +00002917 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002918 emitOptimizationRemarkAnalysis(
2919 F.getContext(), DEBUG_TYPE, F,
2920 (*II)->getAccessInstruction()->getDebugLoc(),
2921 "Possibly aliasing pointer, use restrict keyword.");
2922
Johannes Doerfert13771732014-10-01 12:40:46 +00002923 Value *BaseAddr = (*II)->getBaseAddr();
2924 if (HasWriteAccess.count(BaseAddr)) {
2925 NonReadOnlyBaseValues.insert(BaseAddr);
2926 II++;
2927 } else {
2928 ReadOnlyPairs[BaseAddr].insert(*II);
2929 II = AG.erase(II);
2930 }
2931 }
2932
2933 // If we don't have read only pointers check if there are at least two
2934 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002935 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002936 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002937 continue;
2938 }
2939
2940 // If we don't have non read only pointers clear the alias group.
2941 if (NonReadOnlyBaseValues.empty()) {
2942 AG.clear();
2943 continue;
2944 }
2945
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00002946 // Check if we have non-affine accesses left, if so bail out as we cannot
2947 // generate a good access range yet.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002948 for (auto *MA : AG) {
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00002949 if (!MA->isAffine()) {
2950 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
2951 return false;
2952 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002953 if (auto *BasePtrMA = lookupBasePtrAccess(MA))
2954 addRequiredInvariantLoad(
2955 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
2956 }
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00002957 for (auto &ReadOnlyPair : ReadOnlyPairs)
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002958 for (auto *MA : ReadOnlyPair.second) {
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00002959 if (!MA->isAffine()) {
2960 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
2961 return false;
2962 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002963 if (auto *BasePtrMA = lookupBasePtrAccess(MA))
2964 addRequiredInvariantLoad(
2965 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
2966 }
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00002967
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002968 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002969 MinMaxAliasGroups.emplace_back();
2970 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2971 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2972 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2973 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002974
2975 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002976
2977 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002978 for (MemoryAccess *MA : AG)
2979 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002980
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002981 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2982 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002983
2984 // Bail out if the number of values we need to compare is too large.
2985 // This is important as the number of comparisions grows quadratically with
2986 // the number of values we need to compare.
Johannes Doerfert5210da52016-06-02 11:06:54 +00002987 if (!Valid || (MinMaxAccessesNonReadOnly.size() + ReadOnlyPairs.size() >
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002988 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002989 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002990
2991 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002992 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002993 Accesses = isl_union_map_empty(getParamSpace());
2994
2995 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2996 for (MemoryAccess *MA : ReadOnlyPair.second)
2997 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2998
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002999 Valid =
3000 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00003001
3002 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003003 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003004 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003005
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003006 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003007}
3008
Johannes Doerfertef744432016-05-23 12:42:38 +00003009/// @brief Get the smallest loop that contains @p S but is not in @p S.
3010static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003011 // Start with the smallest loop containing the entry and expand that
3012 // loop until it contains all blocks in the region. If there is a loop
3013 // containing all blocks in the region check if it is itself contained
3014 // and if so take the parent loop as it will be the smallest containing
3015 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003016 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003017 while (L) {
3018 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003019 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003020 AllContained &= L->contains(BB);
3021 if (AllContained)
3022 break;
3023 L = L->getParentLoop();
3024 }
3025
Johannes Doerfertef744432016-05-23 12:42:38 +00003026 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003027}
3028
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003029Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003030 ScopDetection::DetectionContext &DC)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00003031 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003032 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003033 MaxLoopDepth(0), DC(DC), IslCtx(isl_ctx_alloc(), isl_ctx_free),
3034 Context(nullptr), Affinator(this, LI), AssumedContext(nullptr),
3035 InvalidContext(nullptr), Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003036 if (IslOnErrorAbort)
3037 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003038 buildContext();
3039}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003040
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003041void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, DominatorTree &DT,
3042 LoopInfo &LI) {
3043 buildInvariantEquivalenceClasses();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003044
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003045 if (!buildDomains(&R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003046 return;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003047
Johannes Doerfertff68f462016-04-19 14:49:42 +00003048 addUserAssumptions(AC, DT, LI);
3049
Johannes Doerfert26404542016-05-10 12:19:47 +00003050 // Remove empty statements.
Michael Kruseafe06702015-10-02 16:33:27 +00003051 // Exit early in case there are no executable statements left in this scop.
Johannes Doerfert26404542016-05-10 12:19:47 +00003052 simplifySCoP(false, DT, LI);
Michael Kruseafe06702015-10-02 16:33:27 +00003053 if (Stmts.empty())
3054 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003055
Michael Krusecac948e2015-10-02 13:53:07 +00003056 // The ScopStmts now have enough information to initialize themselves.
3057 for (ScopStmt &Stmt : Stmts)
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003058 Stmt.init(LI);
Michael Krusecac948e2015-10-02 13:53:07 +00003059
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003060 // Check early for profitability. Afterwards it cannot change anymore,
3061 // only the runtime context could become infeasible.
3062 if (!isProfitable()) {
3063 invalidate(PROFITABLE, DebugLoc());
Tobias Grosser8286b832015-11-02 11:29:32 +00003064 return;
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003065 }
3066
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003067 buildSchedule(LI);
Tobias Grosser8286b832015-11-02 11:29:32 +00003068
3069 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00003070 realignParams();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00003071 addUserContext();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003072
3073 // After the context was fully constructed, thus all our knowledge about
3074 // the parameters is in there, we add all recorded assumptions to the
3075 // assumed/invalid context.
3076 addRecordedAssumptions();
3077
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003078 simplifyContexts();
Johannes Doerfert5210da52016-06-02 11:06:54 +00003079 if (!buildAliasChecks(AA))
3080 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003081
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003082 hoistInvariantLoads();
3083 verifyInvariantLoads();
Johannes Doerfert26404542016-05-10 12:19:47 +00003084 simplifySCoP(true, DT, LI);
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003085
3086 // Check late for a feasible runtime context because profitability did not
3087 // change.
3088 if (!hasFeasibleRuntimeContext()) {
3089 invalidate(PROFITABLE, DebugLoc());
3090 return;
3091 }
Tobias Grosser75805372011-04-29 06:27:02 +00003092}
3093
3094Scop::~Scop() {
3095 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003096 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003097 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003098 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003099
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003100 for (auto &It : ParameterIds)
3101 isl_id_free(It.second);
3102
Johannes Doerfert96425c22015-08-30 21:13:53 +00003103 for (auto It : DomainMap)
3104 isl_set_free(It.second);
3105
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003106 for (auto &AS : RecordedAssumptions)
3107 isl_set_free(AS.Set);
3108
Johannes Doerfertb164c792014-09-18 11:17:17 +00003109 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003110 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003111 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003112 isl_pw_multi_aff_free(MMA.first);
3113 isl_pw_multi_aff_free(MMA.second);
3114 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003115 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003116 isl_pw_multi_aff_free(MMA.first);
3117 isl_pw_multi_aff_free(MMA.second);
3118 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003119 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003120
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003121 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003122 isl_set_free(std::get<2>(IAClass));
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003123
3124 // Explicitly release all Scop objects and the underlying isl objects before
3125 // we relase the isl context.
3126 Stmts.clear();
3127 ScopArrayInfoMap.clear();
3128 AccFuncMap.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003129}
3130
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003131void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003132 // Check all array accesses for each base pointer and find a (virtual) element
3133 // size for the base pointer that divides all access functions.
3134 for (auto &Stmt : *this)
3135 for (auto *Access : Stmt) {
3136 if (!Access->isArrayKind())
3137 continue;
3138 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(),
3139 ScopArrayInfo::MK_Array)];
3140 if (SAI->getNumberOfDimensions() != 1)
3141 continue;
3142 unsigned DivisibleSize = SAI->getElemSizeInBytes();
3143 auto *Subscript = Access->getSubscript(0);
3144 while (!isDivisible(Subscript, DivisibleSize, *SE))
3145 DivisibleSize /= 2;
3146 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
3147 SAI->updateElementType(Ty);
3148 }
3149
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003150 for (auto &Stmt : *this)
3151 for (auto &Access : Stmt)
3152 Access->updateDimensionality();
3153}
3154
Johannes Doerfert26404542016-05-10 12:19:47 +00003155void Scop::simplifySCoP(bool AfterHoisting, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003156 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3157 ScopStmt &Stmt = *StmtIt;
3158
Johannes Doerfert26404542016-05-10 12:19:47 +00003159 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003160 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003161 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003162
Johannes Doerferteca9e892015-11-03 16:54:49 +00003163 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003164 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003165 bool OnlyRead = true;
3166 for (MemoryAccess *MA : Stmt) {
3167 if (MA->isRead())
3168 continue;
3169
3170 OnlyRead = false;
3171 break;
3172 }
3173
3174 RemoveStmt = OnlyRead;
3175 }
3176
Johannes Doerfert26404542016-05-10 12:19:47 +00003177 if (!RemoveStmt) {
3178 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003179 continue;
3180 }
3181
Johannes Doerfert26404542016-05-10 12:19:47 +00003182 // Remove the statement because it is unnecessary.
3183 if (Stmt.isRegionStmt())
3184 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3185 StmtMap.erase(BB);
3186 else
3187 StmtMap.erase(Stmt.getBasicBlock());
3188
3189 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003190 }
3191}
3192
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003193InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003194 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3195 if (!LInst)
3196 return nullptr;
3197
3198 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3199 LInst = cast<LoadInst>(Rep);
3200
Johannes Doerfert96e54712016-02-07 17:30:13 +00003201 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003202 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003203 for (auto &IAClass : InvariantEquivClasses) {
3204 if (PointerSCEV != std::get<0>(IAClass) || Ty != std::get<3>(IAClass))
3205 continue;
3206
3207 auto &MAs = std::get<1>(IAClass);
3208 for (auto *MA : MAs)
3209 if (MA->getAccessInstruction() == Val)
3210 return &IAClass;
3211 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003212
3213 return nullptr;
3214}
3215
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003216/// @brief Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003217static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003218 bool MAInvalidCtxIsEmpty,
3219 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003220 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3221 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3222 // TODO: We can provide more information for better but more expensive
3223 // results.
3224 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3225 LInst->getAlignment(), DL))
3226 return false;
3227
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003228 // If the location might be overwritten we do not hoist it unconditionally.
3229 //
3230 // TODO: This is probably to conservative.
3231 if (!NonHoistableCtxIsEmpty)
3232 return false;
3233
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003234 // If a dereferencable load is in a statement that is modeled precisely we can
3235 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003236 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003237 return true;
3238
3239 // Even if the statement is not modeled precisely we can hoist the load if it
3240 // does not involve any parameters that might have been specilized by the
3241 // statement domain.
3242 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3243 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3244 return false;
3245 return true;
3246}
3247
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003248void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003249
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003250 if (InvMAs.empty())
3251 return;
3252
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003253 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003254 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003255
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003256 // Get the context under which the statement is executed but remove the error
3257 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003258 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003259 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003260
Michael Krusebc150122016-05-02 12:25:18 +00003261 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctionsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003262 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003263 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3264 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003265 for (auto &InvMA : InvMAs)
3266 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003267 return;
3268 }
3269
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003270 // Project out all parameters that relate to loads in the statement. Otherwise
3271 // we could have cyclic dependences on the constraints under which the
3272 // hoisted loads are executed and we could not determine an order in which to
3273 // pre-load them. This happens because not only lower bounds are part of the
3274 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003275 for (auto &InvMA : InvMAs) {
3276 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003277 Instruction *AccInst = MA->getAccessInstruction();
3278 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003279 SetVector<Value *> Values;
3280 for (const SCEV *Parameter : Parameters) {
3281 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003282 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003283 if (!Values.count(AccInst))
3284 continue;
3285
3286 if (isl_id *ParamId = getIdForParam(Parameter)) {
3287 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
3288 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
3289 isl_id_free(ParamId);
3290 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003291 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003292 }
3293 }
3294
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003295 for (auto &InvMA : InvMAs) {
3296 auto *MA = InvMA.MA;
3297 auto *NHCtx = InvMA.NonHoistableCtx;
3298
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003299 // Check for another invariant access that accesses the same location as
3300 // MA and if found consolidate them. Otherwise create a new equivalence
3301 // class at the end of InvariantEquivClasses.
3302 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003303 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003304 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3305
Johannes Doerfert85676e32016-04-23 14:32:34 +00003306 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003307 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003308 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3309
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003310 isl_set *MACtx;
3311 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003312 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3313 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003314 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003315 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003316 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003317 } else {
3318 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003319 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003320 MACtx = isl_set_gist_params(MACtx, getContext());
3321 }
3322
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003323 bool Consolidated = false;
3324 for (auto &IAClass : InvariantEquivClasses) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00003325 if (PointerSCEV != std::get<0>(IAClass) || Ty != std::get<3>(IAClass))
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003326 continue;
3327
Johannes Doerfertdf880232016-03-03 12:26:58 +00003328 // If the pointer and the type is equal check if the access function wrt.
3329 // to the domain is equal too. It can happen that the domain fixes
3330 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003331 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003332 // create a new invariant load equivalence class.
3333 auto &MAs = std::get<1>(IAClass);
3334 if (!MAs.empty()) {
3335 auto *LastMA = MAs.front();
3336
3337 auto *AR = isl_map_range(MA->getAccessRelation());
3338 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3339 bool SameAR = isl_set_is_equal(AR, LastAR);
3340 isl_set_free(AR);
3341 isl_set_free(LastAR);
3342
3343 if (!SameAR)
3344 continue;
3345 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003346
3347 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003348 MAs.push_front(MA);
3349
Johannes Doerfertdf880232016-03-03 12:26:58 +00003350 Consolidated = true;
3351
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003352 // Unify the execution context of the class and this statement.
3353 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003354 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003355 IAClassDomainCtx =
3356 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003357 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003358 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003359 break;
3360 }
3361
3362 if (Consolidated)
3363 continue;
3364
3365 // If we did not consolidate MA, thus did not find an equivalence class
3366 // for it, we create a new one.
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003367 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA}, MACtx,
3368 Ty);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003369 }
3370
3371 isl_set_free(DomainCtx);
3372}
3373
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003374__isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3375 __isl_keep isl_union_map *Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003376 // TODO: Loads that are not loop carried, hence are in a statement with
3377 // zero iterators, are by construction invariant, though we
3378 // currently "hoist" them anyway. This is necessary because we allow
3379 // them to be treated as parameters (e.g., in conditions) and our code
3380 // generation would otherwise use the old value.
3381
3382 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003383 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003384
3385 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003386 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003387
3388 // Skip accesses that have an invariant base pointer which is defined but
3389 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3390 // returns a pointer that is used as a base address. However, as we want
3391 // to hoist indirect pointers, we allow the base pointer to be defined in
3392 // the region if it is also a memory access. Each ScopArrayInfo object
3393 // that has a base pointer origin has a base pointer that is loaded and
3394 // that it is invariant, thus it will be hoisted too. However, if there is
3395 // no base pointer origin we check that the base pointer is defined
3396 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003397 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003398 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003399 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003400
3401 // Skip accesses in non-affine subregions as they might not be executed
3402 // under the same condition as the entry of the non-affine subregion.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003403 if (BB != LI->getParent())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003404 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003405
3406 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003407 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003408
3409 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3410 Stmt.getNumIterators())) {
3411 isl_map_free(AccessRelation);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003412 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003413 }
3414
3415 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3416 isl_set *AccessRange = isl_map_range(AccessRelation);
3417
3418 isl_union_map *Written = isl_union_map_intersect_range(
3419 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003420 auto *WrittenCtx = isl_union_map_params(Written);
3421 bool IsWritten = !isl_set_is_empty(WrittenCtx);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003422
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003423 if (!IsWritten)
3424 return WrittenCtx;
3425
3426 WrittenCtx = isl_set_remove_divs(WrittenCtx);
3427 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctionsInDomain;
3428 if (TooComplex || !isRequiredInvariantLoad(LI)) {
3429 isl_set_free(WrittenCtx);
3430 return nullptr;
3431 }
3432
3433 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3434 AS_RESTRICTION);
3435 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003436}
3437
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003438void Scop::verifyInvariantLoads() {
3439 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003440 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003441 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003442 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003443 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003444 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3445 return;
3446 }
3447 }
3448}
3449
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003450void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003451 if (!PollyInvariantLoadHoisting)
3452 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003453
Tobias Grosser0865e7752016-02-29 07:29:42 +00003454 isl_union_map *Writes = getWrites();
3455 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003456 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003457
Tobias Grosser0865e7752016-02-29 07:29:42 +00003458 for (MemoryAccess *Access : Stmt)
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003459 if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3460 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003461
3462 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003463 for (auto InvMA : InvariantAccesses)
3464 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003465 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003466 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003467 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003468}
3469
Johannes Doerfert80ef1102014-11-07 08:31:31 +00003470const ScopArrayInfo *
Tobias Grossercc779502016-02-02 13:22:54 +00003471Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003472 ArrayRef<const SCEV *> Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00003473 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003474 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003475 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003476 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003477 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003478 DL, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003479 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003480 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003481 // In case of mismatching array sizes, we bail out by setting the run-time
3482 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003483 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003484 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003485 }
Tobias Grosserab671442015-05-23 05:58:27 +00003486 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003487}
3488
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003489const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00003490 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003491 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003492 assert(SAI && "No ScopArrayInfo available for this base pointer");
3493 return SAI;
3494}
3495
Tobias Grosser74394f02013-01-14 22:40:23 +00003496std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003497
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003498std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003499 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003500 return stringFromIslObj(AssumedContext);
3501}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003502
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003503std::string Scop::getInvalidContextStr() const {
3504 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003505}
Tobias Grosser75805372011-04-29 06:27:02 +00003506
3507std::string Scop::getNameStr() const {
3508 std::string ExitName, EntryName;
3509 raw_string_ostream ExitStr(ExitName);
3510 raw_string_ostream EntryStr(EntryName);
3511
Tobias Grosserf240b482014-01-09 10:42:15 +00003512 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003513 EntryStr.str();
3514
3515 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003516 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003517 ExitStr.str();
3518 } else
3519 ExitName = "FunctionExit";
3520
3521 return EntryName + "---" + ExitName;
3522}
3523
Tobias Grosser74394f02013-01-14 22:40:23 +00003524__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003525__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003526 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003527}
3528
Tobias Grossere86109f2013-10-29 21:05:49 +00003529__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003530 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003531 return isl_set_copy(AssumedContext);
3532}
3533
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003534bool Scop::isProfitable() const {
3535 if (PollyProcessUnprofitable)
3536 return true;
3537
3538 if (!hasFeasibleRuntimeContext())
3539 return false;
3540
3541 if (isEmpty())
3542 return false;
3543
3544 unsigned OptimizableStmtsOrLoops = 0;
3545 for (auto &Stmt : *this) {
3546 if (Stmt.getNumIterators() == 0)
3547 continue;
3548
3549 bool ContainsArrayAccs = false;
3550 bool ContainsScalarAccs = false;
3551 for (auto *MA : Stmt) {
3552 if (MA->isRead())
3553 continue;
3554 ContainsArrayAccs |= MA->isArrayKind();
3555 ContainsScalarAccs |= MA->isScalarKind();
3556 }
3557
3558 if (ContainsArrayAccs && !ContainsScalarAccs)
3559 OptimizableStmtsOrLoops += Stmt.getNumIterators();
3560 }
3561
3562 return OptimizableStmtsOrLoops > 1;
3563}
3564
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003565bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003566 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003567 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00003568 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3569 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
3570 isl_set_is_subset(PositiveContext, NegativeContext));
3571 isl_set_free(PositiveContext);
3572 if (!IsFeasible) {
3573 isl_set_free(NegativeContext);
3574 return false;
3575 }
3576
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003577 auto *DomainContext = isl_union_set_params(getDomains());
3578 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00003579 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003580 isl_set_free(NegativeContext);
3581 isl_set_free(DomainContext);
3582
Johannes Doerfert43788c52015-08-20 05:58:56 +00003583 return IsFeasible;
3584}
3585
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003586static std::string toString(AssumptionKind Kind) {
3587 switch (Kind) {
3588 case ALIASING:
3589 return "No-aliasing";
3590 case INBOUNDS:
3591 return "Inbounds";
3592 case WRAPPING:
3593 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00003594 case UNSIGNED:
3595 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003596 case COMPLEXITY:
3597 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003598 case PROFITABLE:
3599 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003600 case ERRORBLOCK:
3601 return "No-error";
3602 case INFINITELOOP:
3603 return "Finite loop";
3604 case INVARIANTLOAD:
3605 return "Invariant load";
3606 case DELINEARIZATION:
3607 return "Delinearization";
3608 }
3609 llvm_unreachable("Unknown AssumptionKind!");
3610}
3611
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003612bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
3613 if (Sign == AS_ASSUMPTION) {
3614 if (isl_set_is_subset(Context, Set))
3615 return false;
3616
3617 if (isl_set_is_subset(AssumedContext, Set))
3618 return false;
3619 } else {
3620 if (isl_set_is_disjoint(Set, Context))
3621 return false;
3622
3623 if (isl_set_is_subset(Set, InvalidContext))
3624 return false;
3625 }
3626 return true;
3627}
3628
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003629bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3630 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003631 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
3632 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003633
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003634 auto &F = getFunction();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003635 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
3636 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003637 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003638 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003639}
3640
3641void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003642 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003643 // Simplify the assumptions/restrictions first.
3644 Set = isl_set_gist_params(Set, getContext());
3645
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003646 if (!trackAssumption(Kind, Set, Loc, Sign)) {
3647 isl_set_free(Set);
3648 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003649 }
3650
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003651 if (Sign == AS_ASSUMPTION) {
3652 AssumedContext = isl_set_intersect(AssumedContext, Set);
3653 AssumedContext = isl_set_coalesce(AssumedContext);
3654 } else {
3655 InvalidContext = isl_set_union(InvalidContext, Set);
3656 InvalidContext = isl_set_coalesce(InvalidContext);
3657 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003658}
3659
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003660void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003661 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
3662 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003663}
3664
3665void Scop::addRecordedAssumptions() {
3666 while (!RecordedAssumptions.empty()) {
3667 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003668
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003669 if (!AS.BB) {
3670 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
3671 continue;
3672 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003673
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003674 // If the domain was deleted the assumptions are void.
3675 isl_set *Dom = getDomainConditions(AS.BB);
3676 if (!Dom) {
3677 isl_set_free(AS.Set);
3678 continue;
3679 }
3680
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003681 // If a basic block was given use its domain to simplify the assumption.
3682 // In case of restrictions we know they only have to hold on the domain,
3683 // thus we can intersect them with the domain of the block. However, for
3684 // assumptions the domain has to imply them, thus:
3685 // _ _____
3686 // Dom => S <==> A v B <==> A - B
3687 //
3688 // To avoid the complement we will register A - B as a restricton not an
3689 // assumption.
3690 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003691 if (AS.Sign == AS_RESTRICTION)
3692 S = isl_set_params(isl_set_intersect(S, Dom));
3693 else /* (AS.Sign == AS_ASSUMPTION) */
3694 S = isl_set_params(isl_set_subtract(Dom, S));
3695
3696 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003697 }
3698}
3699
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003700void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003701 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003702}
3703
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003704__isl_give isl_set *Scop::getInvalidContext() const {
3705 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003706}
3707
Tobias Grosser75805372011-04-29 06:27:02 +00003708void Scop::printContext(raw_ostream &OS) const {
3709 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003710 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003711
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003712 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003713 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003714
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003715 OS.indent(4) << "Invalid Context:\n";
3716 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003717
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003718 unsigned Dim = 0;
3719 for (const SCEV *Parameter : Parameters)
3720 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003721}
3722
Johannes Doerfertb164c792014-09-18 11:17:17 +00003723void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003724 int noOfGroups = 0;
3725 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003726 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003727 noOfGroups += 1;
3728 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003729 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003730 }
3731
Tobias Grosserbb853c22015-07-25 12:31:03 +00003732 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003733 if (MinMaxAliasGroups.empty()) {
3734 OS.indent(8) << "n/a\n";
3735 return;
3736 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003737
Tobias Grosserbb853c22015-07-25 12:31:03 +00003738 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003739
3740 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003741 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003742 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003743 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003744 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3745 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003746 }
3747 OS << " ]]\n";
3748 }
3749
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003750 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003751 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003752 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003753 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003754 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3755 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003756 }
3757 OS << " ]]\n";
3758 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003759 }
3760}
3761
Tobias Grosser75805372011-04-29 06:27:02 +00003762void Scop::printStatements(raw_ostream &OS) const {
3763 OS << "Statements {\n";
3764
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003765 for (const ScopStmt &Stmt : *this)
3766 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003767
3768 OS.indent(4) << "}\n";
3769}
3770
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003771void Scop::printArrayInfo(raw_ostream &OS) const {
3772 OS << "Arrays {\n";
3773
Tobias Grosserab671442015-05-23 05:58:27 +00003774 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003775 Array.second->print(OS);
3776
3777 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003778
3779 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3780
3781 for (auto &Array : arrays())
3782 Array.second->print(OS, /* SizeAsPwAff */ true);
3783
3784 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003785}
3786
Tobias Grosser75805372011-04-29 06:27:02 +00003787void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003788 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003789 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003790 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003791 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003792 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003793 const auto &MAs = std::get<1>(IAClass);
3794 if (MAs.empty()) {
3795 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003796 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003797 MAs.front()->print(OS);
3798 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003799 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003800 }
3801 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003802 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003803 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003804 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003805 printStatements(OS.indent(4));
3806}
3807
3808void Scop::dump() const { print(dbgs()); }
3809
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003810isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00003811
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003812__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
3813 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003814 // First try to use the SCEVAffinator to generate a piecewise defined
3815 // affine function from @p E in the context of @p BB. If that tasks becomes to
3816 // complex the affinator might return a nullptr. In such a case we invalidate
3817 // the SCoP and return a dummy value. This way we do not need to add error
3818 // handling cdoe to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003819 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003820 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00003821 // TODO: We could use a heuristic and either use:
3822 // SCEVAffinator::takeNonNegativeAssumption
3823 // or
3824 // SCEVAffinator::interpretAsUnsigned
3825 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003826 if (NonNegative)
3827 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003828 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003829 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003830
3831 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
3832 invalidate(COMPLEXITY, DL);
3833 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003834}
3835
Tobias Grosser808cd692015-07-14 09:33:13 +00003836__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003837 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003838
Tobias Grosser808cd692015-07-14 09:33:13 +00003839 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003840 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003841
3842 return Domain;
3843}
3844
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003845__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
3846 PWACtx PWAC = getPwAff(E, BB);
3847 isl_set_free(PWAC.second);
3848 return PWAC.first;
3849}
3850
Tobias Grossere5a35142015-11-12 14:07:09 +00003851__isl_give isl_union_map *
3852Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3853 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003854
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003855 for (ScopStmt &Stmt : *this) {
3856 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003857 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003858 continue;
3859
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003860 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003861 isl_map *AccessDomain = MA->getAccessRelation();
3862 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003863 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003864 }
3865 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003866 return isl_union_map_coalesce(Accesses);
3867}
3868
3869__isl_give isl_union_map *Scop::getMustWrites() {
3870 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003871}
3872
3873__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003874 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003875}
3876
Tobias Grosser37eb4222014-02-20 21:43:54 +00003877__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003878 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003879}
3880
3881__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003882 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003883}
3884
Tobias Grosser2ac23382015-11-12 14:07:13 +00003885__isl_give isl_union_map *Scop::getAccesses() {
3886 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3887}
3888
Tobias Grosser808cd692015-07-14 09:33:13 +00003889__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00003890 auto *Tree = getScheduleTree();
3891 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00003892 isl_schedule_free(Tree);
3893 return S;
3894}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003895
Tobias Grosser808cd692015-07-14 09:33:13 +00003896__isl_give isl_schedule *Scop::getScheduleTree() const {
3897 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3898 getDomains());
3899}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003900
Tobias Grosser808cd692015-07-14 09:33:13 +00003901void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3902 auto *S = isl_schedule_from_domain(getDomains());
3903 S = isl_schedule_insert_partial_schedule(
3904 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3905 isl_schedule_free(Schedule);
3906 Schedule = S;
3907}
3908
3909void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3910 isl_schedule_free(Schedule);
3911 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003912}
3913
3914bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3915 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003916 for (ScopStmt &Stmt : *this) {
3917 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003918 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3919 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3920
3921 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3922 isl_union_set_free(StmtDomain);
3923 isl_union_set_free(NewStmtDomain);
3924 continue;
3925 }
3926
3927 Changed = true;
3928
3929 isl_union_set_free(StmtDomain);
3930 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3931
3932 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003933 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003934 isl_union_set_free(NewStmtDomain);
3935 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003936 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003937 }
3938 isl_union_set_free(Domain);
3939 return Changed;
3940}
3941
Tobias Grosser75805372011-04-29 06:27:02 +00003942ScalarEvolution *Scop::getSE() const { return SE; }
3943
Tobias Grosser808cd692015-07-14 09:33:13 +00003944struct MapToDimensionDataTy {
3945 int N;
3946 isl_union_pw_multi_aff *Res;
3947};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003948
Tobias Grosser808cd692015-07-14 09:33:13 +00003949// @brief Create a function that maps the elements of 'Set' to its N-th
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003950// dimension and add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00003951//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003952// @param Set The input set.
3953// @param User->N The dimension to map to.
3954// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00003955//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003956// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00003957static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3958 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3959 int Dim;
3960 isl_space *Space;
3961 isl_pw_multi_aff *PMA;
3962
3963 Dim = isl_set_dim(Set, isl_dim_set);
3964 Space = isl_set_get_space(Set);
3965 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3966 Dim - Data->N);
3967 if (Data->N > 1)
3968 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3969 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3970
3971 isl_set_free(Set);
3972
3973 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003974}
3975
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003976// @brief Create an isl_multi_union_aff that defines an identity mapping
3977// from the elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003978//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003979// # Example:
3980//
3981// Domain: { A[i,j]; B[i,j,k] }
3982// N: 1
3983//
3984// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
3985//
3986// @param USet A union set describing the elements for which to generate a
3987// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00003988// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003989// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003990static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003991mapToDimension(__isl_take isl_union_set *USet, int N) {
3992 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00003993 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003994 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003995
Tobias Grosser808cd692015-07-14 09:33:13 +00003996 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00003997
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003998 auto *Space = isl_union_set_get_space(USet);
3999 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00004000
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004001 Data = {N, PwAff};
4002
4003 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004004 (void)Res;
4005
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004006 assert(Res == isl_stat_ok);
4007
4008 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00004009 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4010}
4011
Tobias Grosser316b5b22015-11-11 19:28:14 +00004012void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00004013 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00004014 Stmts.emplace_back(*this, *BB);
Johannes Doerferta90943d2016-02-21 16:37:25 +00004015 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00004016 StmtMap[BB] = Stmt;
4017 } else {
4018 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00004019 Stmts.emplace_back(*this, *R);
Johannes Doerferta90943d2016-02-21 16:37:25 +00004020 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00004021 for (BasicBlock *BB : R->blocks())
4022 StmtMap[BB] = Stmt;
4023 }
Tobias Grosser808cd692015-07-14 09:33:13 +00004024}
4025
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004026void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004027 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004028 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004029 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004030 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4031 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004032}
4033
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004034/// To generate a schedule for the elements in a Region we traverse the Region
4035/// in reverse-post-order and add the contained RegionNodes in traversal order
4036/// to the schedule of the loop that is currently at the top of the LoopStack.
4037/// For loop-free codes, this results in a correct sequential ordering.
4038///
4039/// Example:
4040/// bb1(0)
4041/// / \.
4042/// bb2(1) bb3(2)
4043/// \ / \.
4044/// bb4(3) bb5(4)
4045/// \ /
4046/// bb6(5)
4047///
4048/// Including loops requires additional processing. Whenever a loop header is
4049/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4050/// from an empty schedule, we first process all RegionNodes that are within
4051/// this loop and complete the sequential schedule at this loop-level before
4052/// processing about any other nodes. To implement this
4053/// loop-nodes-first-processing, the reverse post-order traversal is
4054/// insufficient. Hence, we additionally check if the traversal yields
4055/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4056/// These region-nodes are then queue and only traverse after the all nodes
4057/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004058void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004059 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004060
4061 ReversePostOrderTraversal<Region *> RTraversal(R);
4062 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4063 std::deque<RegionNode *> DelayList;
4064 bool LastRNWaiting = false;
4065
4066 // Iterate over the region @p R in reverse post-order but queue
4067 // sub-regions/blocks iff they are not part of the last encountered but not
4068 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4069 // that we queued the last sub-region/block from the reverse post-order
4070 // iterator. If it is set we have to explore the next sub-region/block from
4071 // the iterator (if any) to guarantee progress. If it is not set we first try
4072 // the next queued sub-region/blocks.
4073 while (!WorkList.empty() || !DelayList.empty()) {
4074 RegionNode *RN;
4075
4076 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4077 RN = WorkList.front();
4078 WorkList.pop_front();
4079 LastRNWaiting = false;
4080 } else {
4081 RN = DelayList.front();
4082 DelayList.pop_front();
4083 }
4084
4085 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004086 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004087 L = OuterScopLoop;
4088
Tobias Grosser151ae322016-04-03 19:36:52 +00004089 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004090 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004091 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004092 LastRNWaiting = true;
4093 DelayList.push_back(RN);
4094 continue;
4095 }
4096 LoopStack.push_back({L, nullptr, 0});
4097 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004098 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004099 }
4100
4101 return;
4102}
4103
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004104void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004105
Tobias Grosser8362c262016-01-06 15:30:06 +00004106 if (RN->isSubRegion()) {
4107 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004108 if (!isNonAffineSubRegion(LocalRegion)) {
4109 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004110 return;
4111 }
4112 }
Michael Kruse046dde42015-08-10 13:01:57 +00004113
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004114 auto &LoopData = LoopStack.back();
4115 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004116
Michael Kruse6f7721f2016-02-24 22:08:19 +00004117 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004118 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4119 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004120 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004121 }
4122
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004123 // Check if we just processed the last node in this loop. If we did, finalize
4124 // the loop by:
4125 //
4126 // - adding new schedule dimensions
4127 // - folding the resulting schedule into the parent loop schedule
4128 // - dropping the loop schedule from the LoopStack.
4129 //
4130 // Then continue to check surrounding loops, which might also have been
4131 // completed by this node.
4132 while (LoopData.L &&
4133 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004134 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004135 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004136
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004137 LoopStack.pop_back();
4138 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004139
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004140 if (Schedule) {
4141 auto *Domain = isl_schedule_get_domain(Schedule);
4142 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4143 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4144 NextLoopData.Schedule =
4145 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004146 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004147
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004148 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4149 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004150 }
Tobias Grosser75805372011-04-29 06:27:02 +00004151}
4152
Michael Kruse6f7721f2016-02-24 22:08:19 +00004153ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004154 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004155 if (StmtMapIt == StmtMap.end())
4156 return nullptr;
4157 return StmtMapIt->second;
4158}
4159
Michael Kruse6f7721f2016-02-24 22:08:19 +00004160ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4161 if (RN->isSubRegion())
4162 return getStmtFor(RN->getNodeAs<Region>());
4163 return getStmtFor(RN->getNodeAs<BasicBlock>());
4164}
4165
4166ScopStmt *Scop::getStmtFor(Region *R) const {
4167 ScopStmt *Stmt = getStmtFor(R->getEntry());
4168 assert(!Stmt || Stmt->getRegion() == R);
4169 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004170}
4171
Johannes Doerfert96425c22015-08-30 21:13:53 +00004172int Scop::getRelativeLoopDepth(const Loop *L) const {
4173 Loop *OuterLoop =
4174 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4175 if (!OuterLoop)
4176 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004177 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4178}
4179
Johannes Doerfert99191c72016-05-31 09:41:04 +00004180//===----------------------------------------------------------------------===//
4181void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4182 AU.addRequired<LoopInfoWrapperPass>();
4183 AU.addRequired<RegionInfoPass>();
4184 AU.addRequired<DominatorTreeWrapperPass>();
4185 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4186 AU.addRequiredTransitive<ScopDetection>();
4187 AU.addRequired<AAResultsWrapperPass>();
4188 AU.addRequired<AssumptionCacheTracker>();
4189 AU.setPreservesAll();
4190}
4191
4192bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
4193 auto &SD = getAnalysis<ScopDetection>();
4194
4195 if (!SD.isMaxRegionInScop(*R))
4196 return false;
4197
4198 Function *F = R->getEntry()->getParent();
4199 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4200 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4201 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4202 auto const &DL = F->getParent()->getDataLayout();
4203 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4204 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
4205
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004206 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
4207 S = SB.getScop(); // take ownership of scop object
Tobias Grosser75805372011-04-29 06:27:02 +00004208 return false;
4209}
4210
Johannes Doerfert99191c72016-05-31 09:41:04 +00004211void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004212 if (S)
4213 S->print(OS);
4214 else
4215 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00004216}
Tobias Grosser75805372011-04-29 06:27:02 +00004217
Johannes Doerfert99191c72016-05-31 09:41:04 +00004218char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004219
Johannes Doerfert99191c72016-05-31 09:41:04 +00004220Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4221
4222INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004223 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004224 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004225INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004226INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004227INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004228INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004229INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004230INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004231INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004232INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004233 "Polly - Create polyhedral description of Scops", false,
4234 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004235
4236//===----------------------------------------------------------------------===//
4237void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
4238 AU.addRequired<LoopInfoWrapperPass>();
4239 AU.addRequired<RegionInfoPass>();
4240 AU.addRequired<DominatorTreeWrapperPass>();
4241 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4242 AU.addRequiredTransitive<ScopDetection>();
4243 AU.addRequired<AAResultsWrapperPass>();
4244 AU.addRequired<AssumptionCacheTracker>();
4245 AU.setPreservesAll();
4246}
4247
4248bool ScopInfoWrapperPass::runOnFunction(Function &F) {
4249 auto &SD = getAnalysis<ScopDetection>();
4250
4251 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4252 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4253 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4254 auto const &DL = F.getParent()->getDataLayout();
4255 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4256 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
4257
4258 /// Create polyhedral descripton of scops for all the valid regions of a
4259 /// function.
4260 for (auto &It : SD) {
4261 Region *R = const_cast<Region *>(It);
4262 if (!SD.isMaxRegionInScop(*R))
4263 continue;
4264
4265 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
4266 bool Inserted =
4267 RegionToScopMap.insert(std::make_pair(R, SB.getScop())).second;
4268 assert(Inserted && "Building Scop for the same region twice!");
4269 (void)Inserted;
4270 }
4271 return false;
4272}
4273
4274void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
4275 for (auto &It : RegionToScopMap) {
4276 if (It.second)
4277 It.second->print(OS);
4278 else
4279 OS << "Invalid Scop!\n";
4280 }
4281}
4282
4283char ScopInfoWrapperPass::ID = 0;
4284
4285Pass *polly::createScopInfoWrapperPassPass() {
4286 return new ScopInfoWrapperPass();
4287}
4288
4289INITIALIZE_PASS_BEGIN(
4290 ScopInfoWrapperPass, "polly-function-scops",
4291 "Polly - Create polyhedral description of all Scops of a function", false,
4292 false);
4293INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
4294INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
4295INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
4296INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
4297INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
4298INITIALIZE_PASS_DEPENDENCY(ScopDetection);
4299INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
4300INITIALIZE_PASS_END(
4301 ScopInfoWrapperPass, "polly-function-scops",
4302 "Polly - Create polyhedral description of all Scops of a function", false,
4303 false)