blob: 37f6a7a3e20f7aa31beef9e44ff5dc841d788077 [file] [log] [blame]
Johannes Doerfert58a7c752015-09-28 09:48:53 +00001//===--------- ScopInfo.cpp - Create Scops from LLVM IR ------------------===//
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 Grosser74394f02013-01-14 22:40:23 +000063STATISTIC(ScopFound, "Number of valid Scops");
64STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000065
Tobias Grosser75dc40c2015-12-20 13:31:48 +000066// The maximal number of basic sets we allow during domain construction to
67// be created. More complex scops will result in very high compile time and
68// are also unlikely to result in good code
69static int const MaxConjunctsInDomain = 20;
70
Johannes Doerfert2f705842016-04-12 16:09:44 +000071static cl::opt<bool> PollyRemarksMinimal(
72 "polly-remarks-minimal",
73 cl::desc("Do not emit remarks about assumptions that are known"),
74 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
75
Michael Kruse7bf39442015-09-10 12:46:52 +000076static cl::opt<bool> ModelReadOnlyScalars(
77 "polly-analyze-read-only-scalars",
78 cl::desc("Model read-only scalar values in the scop description"),
79 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
80
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000081// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000082// operations can overflow easily. Additive reductions and bit operations
83// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000084static cl::opt<bool> DisableMultiplicativeReductions(
85 "polly-disable-multiplicative-reductions",
86 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
87 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000088
Johannes Doerfert9143d672014-09-27 11:02:39 +000089static cl::opt<unsigned> RunTimeChecksMaxParameters(
90 "polly-rtc-max-parameters",
91 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
92 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
93
Tobias Grosser71500722015-03-28 15:11:14 +000094static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
95 "polly-rtc-max-arrays-per-group",
96 cl::desc("The maximal number of arrays to compare in each alias group."),
97 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000098static cl::opt<std::string> UserContextStr(
99 "polly-context", cl::value_desc("isl parameter set"),
100 cl::desc("Provide additional constraints on the context parameters"),
101 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +0000102
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000103static cl::opt<bool> DetectReductions("polly-detect-reductions",
104 cl::desc("Detect and exploit reductions"),
105 cl::Hidden, cl::ZeroOrMore,
106 cl::init(true), cl::cat(PollyCategory));
107
Tobias Grosser2937b592016-04-29 11:43:20 +0000108static cl::opt<bool>
109 IslOnErrorAbort("polly-on-isl-error-abort",
110 cl::desc("Abort if an isl error is encountered"),
111 cl::init(true), cl::cat(PollyCategory));
112
Michael Kruse7bf39442015-09-10 12:46:52 +0000113//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000114
Michael Kruse046dde42015-08-10 13:01:57 +0000115// Create a sequence of two schedules. Either argument may be null and is
116// interpreted as the empty schedule. Can also return null if both schedules are
117// empty.
118static __isl_give isl_schedule *
119combineInSequence(__isl_take isl_schedule *Prev,
120 __isl_take isl_schedule *Succ) {
121 if (!Prev)
122 return Succ;
123 if (!Succ)
124 return Prev;
125
126 return isl_schedule_sequence(Prev, Succ);
127}
128
Johannes Doerferte7044942015-02-24 11:58:30 +0000129static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
130 const ConstantRange &Range,
131 int dim,
132 enum isl_dim_type type) {
133 isl_val *V;
134 isl_ctx *ctx = isl_set_get_ctx(S);
135
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000136 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
137 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000138 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000139 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
140
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000141 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000142 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000143 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000144 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000145 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
146
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000147 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000148 return isl_set_union(SLB, SUB);
149 else
150 return isl_set_intersect(SLB, SUB);
151}
152
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000153static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
154 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
155 if (!BasePtrLI)
156 return nullptr;
157
158 if (!S->getRegion().contains(BasePtrLI))
159 return nullptr;
160
161 ScalarEvolution &SE = *S->getSE();
162
163 auto *OriginBaseSCEV =
164 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
165 if (!OriginBaseSCEV)
166 return nullptr;
167
168 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
169 if (!OriginBaseSCEVUnknown)
170 return nullptr;
171
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000172 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grossera535dff2015-12-13 19:59:01 +0000173 ScopArrayInfo::MK_Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000174}
175
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000176ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grossera535dff2015-12-13 19:59:01 +0000177 ArrayRef<const SCEV *> Sizes, enum MemoryKind Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000178 const DataLayout &DL, Scop *S)
179 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000180 std::string BasePtrName =
Tobias Grossera535dff2015-12-13 19:59:01 +0000181 getIslCompatibleName("MemRef_", BasePtr, Kind == MK_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000182 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000183
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000184 updateSizes(Sizes);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000185 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
186 if (BasePtrOriginSAI)
187 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000188}
189
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000190__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000191 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000192 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
193 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
194 return Space;
195}
196
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000197void ScopArrayInfo::updateElementType(Type *NewElementType) {
198 if (NewElementType == ElementType)
199 return;
200
Tobias Grosserd840fc72016-02-04 13:18:42 +0000201 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
202 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
203
Johannes Doerferta7920982016-02-25 14:08:48 +0000204 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000205 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000206
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000207 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
208 ElementType = NewElementType;
209 } else {
210 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
211 ElementType = IntegerType::get(ElementType->getContext(), GCD);
212 }
213}
214
215bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000216 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
217 int ExtraDimsNew = NewSizes.size() - SharedDims;
218 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Tobias Grosser8286b832015-11-02 11:29:32 +0000219 for (int i = 0; i < SharedDims; i++)
220 if (NewSizes[i + ExtraDimsNew] != DimensionSizes[i + ExtraDimsOld])
221 return false;
222
223 if (DimensionSizes.size() >= NewSizes.size())
224 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000225
226 DimensionSizes.clear();
227 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
228 NewSizes.end());
229 for (isl_pw_aff *Size : DimensionSizesPw)
230 isl_pw_aff_free(Size);
231 DimensionSizesPw.clear();
232 for (const SCEV *Expr : DimensionSizes) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000233 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000234 DimensionSizesPw.push_back(Size);
235 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000236 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000237}
238
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000239ScopArrayInfo::~ScopArrayInfo() {
240 isl_id_free(Id);
241 for (isl_pw_aff *Size : DimensionSizesPw)
242 isl_pw_aff_free(Size);
243}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000244
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000245std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
246
247int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000248 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000249}
250
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000251__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
252 return isl_id_copy(Id);
253}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000254
255void ScopArrayInfo::dump() const { print(errs()); }
256
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000257void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000258 OS.indent(8) << *getElementType() << " " << getName();
259 if (getNumberOfDimensions() > 0)
260 OS << "[*]";
Tobias Grosser26253842015-11-10 14:24:21 +0000261 for (unsigned u = 1; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000262 OS << "[";
263
Tobias Grosser26253842015-11-10 14:24:21 +0000264 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000265 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000266 OS << " " << Size << " ";
267 isl_pw_aff_free(Size);
268 } else {
269 OS << *getDimensionSize(u);
270 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000271
272 OS << "]";
273 }
274
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000275 OS << ";";
276
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000277 if (BasePtrOriginSAI)
278 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
279
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000280 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000281}
282
283const ScopArrayInfo *
284ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
285 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
286 assert(Id && "Output dimension didn't have an ID");
287 return getFromId(Id);
288}
289
290const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
291 void *User = isl_id_get_user(Id);
292 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
293 isl_id_free(Id);
294 return SAI;
295}
296
Michael Kruse3b425ff2016-04-11 14:34:08 +0000297void MemoryAccess::wrapConstantDimensions() {
298 auto *SAI = getScopArrayInfo();
299 auto *ArraySpace = SAI->getSpace();
300 auto *Ctx = isl_space_get_ctx(ArraySpace);
301 unsigned DimsArray = SAI->getNumberOfDimensions();
302
303 auto *DivModAff = isl_multi_aff_identity(isl_space_map_from_domain_and_range(
304 isl_space_copy(ArraySpace), isl_space_copy(ArraySpace)));
305 auto *LArraySpace = isl_local_space_from_space(ArraySpace);
306
307 // Begin with last dimension, to iteratively carry into higher dimensions.
308 for (int i = DimsArray - 1; i > 0; i--) {
309 auto *DimSize = SAI->getDimensionSize(i);
310 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
311
312 // This transformation is not applicable to dimensions with dynamic size.
313 if (!DimSizeCst)
314 continue;
315
316 auto *DimSizeVal = isl_valFromAPInt(Ctx, DimSizeCst->getAPInt(), false);
317 auto *Var = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
318 isl_dim_set, i);
319 auto *PrevVar = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
320 isl_dim_set, i - 1);
321
322 // Compute: index % size
323 // Modulo must apply in the divide of the previous iteration, if any.
324 auto *Modulo = isl_aff_copy(Var);
325 Modulo = isl_aff_mod_val(Modulo, isl_val_copy(DimSizeVal));
326 Modulo = isl_aff_pullback_multi_aff(Modulo, isl_multi_aff_copy(DivModAff));
327
328 // Compute: floor(index / size)
329 auto *Divide = Var;
330 Divide = isl_aff_div(
331 Divide,
332 isl_aff_val_on_domain(isl_local_space_copy(LArraySpace), DimSizeVal));
333 Divide = isl_aff_floor(Divide);
334 Divide = isl_aff_add(Divide, PrevVar);
335 Divide = isl_aff_pullback_multi_aff(Divide, isl_multi_aff_copy(DivModAff));
336
337 // Apply Modulo and Divide.
338 DivModAff = isl_multi_aff_set_aff(DivModAff, i, Modulo);
339 DivModAff = isl_multi_aff_set_aff(DivModAff, i - 1, Divide);
340 }
341
342 // Apply all modulo/divides on the accesses.
343 AccessRelation =
344 isl_map_apply_range(AccessRelation, isl_map_from_multi_aff(DivModAff));
345 AccessRelation = isl_map_detect_equalities(AccessRelation);
346 isl_local_space_free(LArraySpace);
347}
348
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000349void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000350 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000351 auto *ArraySpace = SAI->getSpace();
352 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000353 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000354
355 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
356 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
357 auto DimsMissing = DimsArray - DimsAccess;
358
Michael Kruse375cb5f2016-02-24 22:08:24 +0000359 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000360 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000361 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000362 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000363
Johannes Doerferta90943d2016-02-21 16:37:25 +0000364 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000365 isl_set_universe(AccessSpace),
366 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000367
368 for (unsigned i = 0; i < DimsMissing; i++)
369 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
370
371 for (unsigned i = DimsMissing; i < DimsArray; i++)
372 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
373
374 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000375
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000376 // For the non delinearized arrays, divide the access function of the last
377 // subscript by the size of the elements in the array.
378 //
379 // A stride one array access in C expressed as A[i] is expressed in
380 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
381 // two subsequent values of 'i' index two values that are stored next to
382 // each other in memory. By this division we make this characteristic
383 // obvious again. If the base pointer was accessed with offsets not divisible
384 // by the accesses element size, we will have choosen a smaller ArrayElemSize
385 // that divides the offsets of all accesses to this base pointer.
386 if (DimsAccess == 1) {
387 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
388 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
389 }
390
Michael Kruse3b425ff2016-04-11 14:34:08 +0000391 // We currently do this only if we added at least one dimension, which means
392 // some dimension's indices have not been specified, an indicator that some
393 // index values have been added together.
394 // TODO: Investigate general usefulness; Effect on unit tests is to make index
395 // expressions more complicated.
396 if (DimsMissing)
397 wrapConstantDimensions();
398
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000399 if (!isAffine())
400 computeBoundsOnAccessRelation(ArrayElemSize);
401
Tobias Grosserd840fc72016-02-04 13:18:42 +0000402 // Introduce multi-element accesses in case the type loaded by this memory
403 // access is larger than the canonical element type of the array.
404 //
405 // An access ((float *)A)[i] to an array char *A is modeled as
406 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000407 if (ElemBytes > ArrayElemSize) {
408 assert(ElemBytes % ArrayElemSize == 0 &&
409 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000410 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000411 isl_set_universe(isl_space_copy(ArraySpace)),
412 isl_set_universe(isl_space_copy(ArraySpace)));
413 for (unsigned i = 0; i < DimsArray - 1; i++)
414 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
415
Tobias Grosserd840fc72016-02-04 13:18:42 +0000416 isl_constraint *C;
417 isl_local_space *LS;
418
419 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000420 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
421
422 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
423 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000424 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000425 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
426 Map = isl_map_add_constraint(Map, C);
427
428 C = isl_constraint_alloc_inequality(LS);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000429 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000430 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
431 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
432 Map = isl_map_add_constraint(Map, C);
433 AccessRelation = isl_map_apply_range(AccessRelation, Map);
434 }
435
436 isl_space_free(ArraySpace);
437
Roman Gareev10595a12016-01-08 14:01:59 +0000438 assumeNoOutOfBound();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000439}
440
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000441const std::string
442MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
443 switch (RT) {
444 case MemoryAccess::RT_NONE:
445 llvm_unreachable("Requested a reduction operator string for a memory "
446 "access which isn't a reduction");
447 case MemoryAccess::RT_ADD:
448 return "+";
449 case MemoryAccess::RT_MUL:
450 return "*";
451 case MemoryAccess::RT_BOR:
452 return "|";
453 case MemoryAccess::RT_BXOR:
454 return "^";
455 case MemoryAccess::RT_BAND:
456 return "&";
457 }
458 llvm_unreachable("Unknown reduction type");
459 return "";
460}
461
Johannes Doerfertf6183392014-07-01 20:52:51 +0000462/// @brief Return the reduction type for a given binary operator
463static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
464 const Instruction *Load) {
465 if (!BinOp)
466 return MemoryAccess::RT_NONE;
467 switch (BinOp->getOpcode()) {
468 case Instruction::FAdd:
469 if (!BinOp->hasUnsafeAlgebra())
470 return MemoryAccess::RT_NONE;
471 // Fall through
472 case Instruction::Add:
473 return MemoryAccess::RT_ADD;
474 case Instruction::Or:
475 return MemoryAccess::RT_BOR;
476 case Instruction::Xor:
477 return MemoryAccess::RT_BXOR;
478 case Instruction::And:
479 return MemoryAccess::RT_BAND;
480 case Instruction::FMul:
481 if (!BinOp->hasUnsafeAlgebra())
482 return MemoryAccess::RT_NONE;
483 // Fall through
484 case Instruction::Mul:
485 if (DisableMultiplicativeReductions)
486 return MemoryAccess::RT_NONE;
487 return MemoryAccess::RT_MUL;
488 default:
489 return MemoryAccess::RT_NONE;
490 }
491}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000492
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000493/// @brief Derive the individual index expressions from a GEP instruction
494///
495/// This function optimistically assumes the GEP references into a fixed size
496/// array. If this is actually true, this function returns a list of array
497/// subscript expressions as SCEV as well as a list of integers describing
498/// the size of the individual array dimensions. Both lists have either equal
499/// length of the size list is one element shorter in case there is no known
500/// size available for the outermost array dimension.
501///
502/// @param GEP The GetElementPtr instruction to analyze.
503///
504/// @return A tuple with the subscript expressions and the dimension sizes.
505static std::tuple<std::vector<const SCEV *>, std::vector<int>>
506getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
507 std::vector<const SCEV *> Subscripts;
508 std::vector<int> Sizes;
509
510 Type *Ty = GEP->getPointerOperandType();
511
512 bool DroppedFirstDim = false;
513
Michael Kruse26ed65e2015-09-24 17:32:49 +0000514 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000515
516 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
517
518 if (i == 1) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000519 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000520 Ty = PtrTy->getElementType();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000521 } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000522 Ty = ArrayTy->getElementType();
523 } else {
524 Subscripts.clear();
525 Sizes.clear();
526 break;
527 }
Johannes Doerferta90943d2016-02-21 16:37:25 +0000528 if (auto *Const = dyn_cast<SCEVConstant>(Expr))
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000529 if (Const->getValue()->isZero()) {
530 DroppedFirstDim = true;
531 continue;
532 }
533 Subscripts.push_back(Expr);
534 continue;
535 }
536
Johannes Doerferta90943d2016-02-21 16:37:25 +0000537 auto *ArrayTy = dyn_cast<ArrayType>(Ty);
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000538 if (!ArrayTy) {
539 Subscripts.clear();
540 Sizes.clear();
541 break;
542 }
543
544 Subscripts.push_back(Expr);
545 if (!(DroppedFirstDim && i == 2))
546 Sizes.push_back(ArrayTy->getNumElements());
547
548 Ty = ArrayTy->getElementType();
549 }
550
551 return std::make_tuple(Subscripts, Sizes);
552}
553
Tobias Grosser75805372011-04-29 06:27:02 +0000554MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000555 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000556 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000557 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000558 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000559}
560
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000561const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
562 isl_id *ArrayId = getArrayId();
563 void *User = isl_id_get_user(ArrayId);
564 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
565 isl_id_free(ArrayId);
566 return SAI;
567}
568
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000569__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000570 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
571}
572
Tobias Grosserd840fc72016-02-04 13:18:42 +0000573__isl_give isl_map *MemoryAccess::getAddressFunction() const {
574 return isl_map_lexmin(getAccessRelation());
575}
576
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000577__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
578 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000579 isl_map *Schedule, *ScheduledAccRel;
580 isl_union_set *UDomain;
581
582 UDomain = isl_union_set_from_set(getStatement()->getDomain());
583 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
584 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000585 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000586 return isl_pw_multi_aff_from_map(ScheduledAccRel);
587}
588
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000589__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000590 return isl_map_copy(AccessRelation);
591}
592
Johannes Doerferta99130f2014-10-13 12:58:03 +0000593std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000594 return stringFromIslObj(AccessRelation);
595}
596
Johannes Doerferta99130f2014-10-13 12:58:03 +0000597__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000598 return isl_map_get_space(AccessRelation);
599}
600
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000601__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000602 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000603}
604
Tobias Grosser6f730082015-09-05 07:46:47 +0000605std::string MemoryAccess::getNewAccessRelationStr() const {
606 return stringFromIslObj(NewAccessRelation);
607}
608
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000609__isl_give isl_basic_map *
610MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000611 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000612 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000613
Tobias Grosser084d8f72012-05-29 09:29:44 +0000614 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000615 isl_basic_set_universe(Statement->getDomainSpace()),
616 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000617}
618
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000619// Formalize no out-of-bound access assumption
620//
621// When delinearizing array accesses we optimistically assume that the
622// delinearized accesses do not access out of bound locations (the subscript
623// expression of each array evaluates for each statement instance that is
624// executed to a value that is larger than zero and strictly smaller than the
625// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000626// dimension for which we do not need to assume any upper bound. At this point
627// we formalize this assumption to ensure that at code generation time the
628// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000629//
630// To find the set of constraints necessary to avoid out of bound accesses, we
631// first build the set of data locations that are not within array bounds. We
632// then apply the reverse access relation to obtain the set of iterations that
633// may contain invalid accesses and reduce this set of iterations to the ones
634// that are actually executed by intersecting them with the domain of the
635// statement. If we now project out all loop dimensions, we obtain a set of
636// parameters that may cause statement instances to be executed that may
637// possibly yield out of bound memory accesses. The complement of these
638// constraints is the set of constraints that needs to be assumed to ensure such
639// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000640void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000641 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000642 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000643 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000644 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000645 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
646 isl_pw_aff *Var =
647 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
648 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
649
650 isl_set *DimOutside;
651
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000652 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000653 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000654 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
655 isl_space_dim(Space, isl_dim_set));
656 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
657 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000658
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000659 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000660
661 Outside = isl_set_union(Outside, DimOutside);
662 }
663
664 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
665 Outside = isl_set_intersect(Outside, Statement->getDomain());
666 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000667
668 // Remove divs to avoid the construction of overly complicated assumptions.
669 // Doing so increases the set of parameter combinations that are assumed to
670 // not appear. This is always save, but may make the resulting run-time check
671 // bail out more often than strictly necessary.
672 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000673 Outside = isl_set_complement(Outside);
Michael Kruse7071e8b2016-04-11 13:24:29 +0000674 const auto &Loc = getAccessInstruction()
675 ? getAccessInstruction()->getDebugLoc()
676 : DebugLoc();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000677 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
678 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000679 isl_space_free(Space);
680}
681
Johannes Doerfertcea61932016-02-21 19:13:19 +0000682void MemoryAccess::buildMemIntrinsicAccessRelation() {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000683 assert(isa<MemIntrinsic>(getAccessInstruction()));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000684 assert(Subscripts.size() == 2 && Sizes.size() == 0);
685
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000686 auto *SubscriptPWA = getPwAff(Subscripts[0]);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000687 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000688
689 isl_map *LengthMap;
690 if (Subscripts[1] == nullptr) {
691 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
692 } else {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000693 auto *LengthPWA = getPwAff(Subscripts[1]);
Johannes Doerferta7920982016-02-25 14:08:48 +0000694 LengthMap = isl_map_from_pw_aff(LengthPWA);
695 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
696 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
697 }
698 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
699 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000700 SubscriptMap =
701 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000702 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
703 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
704 getStatement()->getDomainId());
705}
706
Johannes Doerferte7044942015-02-24 11:58:30 +0000707void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
708 ScalarEvolution *SE = Statement->getParent()->getSE();
709
Johannes Doerfertcea61932016-02-21 19:13:19 +0000710 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000711 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000712 return;
713
714 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000715 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
716 return;
717
718 auto *PtrSCEV = SE->getSCEV(Ptr);
719 if (isa<SCEVCouldNotCompute>(PtrSCEV))
720 return;
721
722 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
723 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
724 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
725
726 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
727 if (Range.isFullSet())
728 return;
729
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000730 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000731 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000732 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000733 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000734 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000735
736 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000737 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000738
739 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
740 AccessRange =
741 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
742 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
743}
744
Michael Krusee2bccbb2015-09-18 19:59:43 +0000745__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000746 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000747 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000748
749 for (int i = Size - 2; i >= 0; --i) {
750 isl_space *Space;
751 isl_map *MapOne, *MapTwo;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000752 isl_pw_aff *DimSize = getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000753
754 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
755 isl_pw_aff_free(DimSize);
756 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
757
758 Space = isl_map_get_space(AccessRelation);
759 Space = isl_space_map_from_set(isl_space_range(Space));
760 Space = isl_space_align_params(Space, SpaceSize);
761
762 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
763 isl_id_free(ParamId);
764
765 MapOne = isl_map_universe(isl_space_copy(Space));
766 for (int j = 0; j < Size; ++j)
767 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
768 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
769
770 MapTwo = isl_map_universe(isl_space_copy(Space));
771 for (int j = 0; j < Size; ++j)
772 if (j < i || j > i + 1)
773 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
774
775 isl_local_space *LS = isl_local_space_from_space(Space);
776 isl_constraint *C;
777 C = isl_equality_alloc(isl_local_space_copy(LS));
778 C = isl_constraint_set_constant_si(C, -1);
779 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
780 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
781 MapTwo = isl_map_add_constraint(MapTwo, C);
782 C = isl_equality_alloc(LS);
783 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
784 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
785 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
786 MapTwo = isl_map_add_constraint(MapTwo, C);
787 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
788
789 MapOne = isl_map_union(MapOne, MapTwo);
790 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
791 }
792 return AccessRelation;
793}
794
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000795/// @brief Check if @p Expr is divisible by @p Size.
796static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000797 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000798 if (Size == 1)
799 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000800
801 // Only one factor needs to be divisible.
802 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
803 for (auto *FactorExpr : MulExpr->operands())
804 if (isDivisible(FactorExpr, Size, SE))
805 return true;
806 return false;
807 }
808
809 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
810 // to be divisble.
811 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
812 for (auto *OpExpr : NAryExpr->operands())
813 if (!isDivisible(OpExpr, Size, SE))
814 return false;
815 return true;
816 }
817
818 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
819 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
820 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
821 return MulSCEV == Expr;
822}
823
Michael Krusee2bccbb2015-09-18 19:59:43 +0000824void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
825 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000826
Johannes Doerfert85676e32016-04-23 14:32:34 +0000827 // Initialize the invalid domain which describes all iterations for which the
828 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000829 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
830 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
831 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000832
Michael Krusee2bccbb2015-09-18 19:59:43 +0000833 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000834 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000835
Michael Krusee2bccbb2015-09-18 19:59:43 +0000836 if (!isAffine()) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000837 if (isa<MemIntrinsic>(getAccessInstruction()))
838 buildMemIntrinsicAccessRelation();
839
Tobias Grosser4f967492013-06-23 05:21:18 +0000840 // We overapproximate non-affine accesses with a possible access to the
841 // whole array. For read accesses it does not make a difference, if an
842 // access must or may happen. However, for write accesses it is important to
843 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000844 if (!AccessRelation)
845 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
846
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000847 AccessRelation =
848 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000849 return;
850 }
851
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000852 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000853 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000854
Michael Krusee2bccbb2015-09-18 19:59:43 +0000855 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000856 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000857 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000858 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000859 }
860
Tobias Grosser5d51afe2016-02-02 16:46:45 +0000861 if (Sizes.size() >= 1 && !isa<SCEVConstant>(Sizes[0]))
Michael Krusee2bccbb2015-09-18 19:59:43 +0000862 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000863
Tobias Grosser79baa212014-04-10 08:38:02 +0000864 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000865 AccessRelation = isl_map_set_tuple_id(
866 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000867 AccessRelation =
868 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
869
Tobias Grosseraa660a92015-03-30 00:07:50 +0000870 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000871 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000872}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000873
Michael Krusecac948e2015-10-02 13:53:07 +0000874MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000875 AccessType AccType, Value *BaseAddress,
876 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000877 ArrayRef<const SCEV *> Subscripts,
878 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000879 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000880 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Johannes Doerfert85676e32016-04-23 14:32:34 +0000881 InvalidDomain(nullptr), BaseAddr(BaseAddress), BaseName(BaseName),
882 ElementType(ElementType), Sizes(Sizes.begin(), Sizes.end()),
883 AccessInstruction(AccessInst), AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000884 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000885 NewAccessRelation(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000886 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Johannes Doerfertcea61932016-02-21 19:13:19 +0000887 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000888
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000889 std::string IdName =
890 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000891 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
892}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000893
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000894void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000895 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Johannes Doerfert85676e32016-04-23 14:32:34 +0000896 InvalidDomain =
897 isl_set_align_params(InvalidDomain, isl_space_copy(ParamSpace));
Tobias Grosser37487052011-10-06 00:03:42 +0000898 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000899}
900
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000901const std::string MemoryAccess::getReductionOperatorStr() const {
902 return MemoryAccess::getReductionOperatorStr(getReductionType());
903}
904
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000905__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
906
Johannes Doerfertf6183392014-07-01 20:52:51 +0000907raw_ostream &polly::operator<<(raw_ostream &OS,
908 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000909 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000910 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000911 else
912 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000913 return OS;
914}
915
Tobias Grosser75805372011-04-29 06:27:02 +0000916void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000917 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000918 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000919 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000920 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000921 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000922 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000923 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000924 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000925 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000926 break;
927 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000928 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000929 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000930 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000931 if (hasNewAccessRelation())
932 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000933}
934
Tobias Grosser74394f02013-01-14 22:40:23 +0000935void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000936
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000937__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
938 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +0000939 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
940 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
941 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000942}
943
Tobias Grosser75805372011-04-29 06:27:02 +0000944// Create a map in the size of the provided set domain, that maps from the
945// one element of the provided set domain to another element of the provided
946// set domain.
947// The mapping is limited to all points that are equal in all but the last
948// dimension and for which the last dimension of the input is strict smaller
949// than the last dimension of the output.
950//
951// getEqualAndLarger(set[i0, i1, ..., iX]):
952//
953// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
954// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
955//
Tobias Grosserf5338802011-10-06 00:03:35 +0000956static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000957 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000958 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000959 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000960
961 // Set all but the last dimension to be equal for the input and output
962 //
963 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
964 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000965 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000966 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000967
968 // Set the last dimension of the input to be strict smaller than the
969 // last dimension of the output.
970 //
971 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000972 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
973 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000974 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000975}
976
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000977__isl_give isl_set *
978MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000979 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000980 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000981 isl_space *Space = isl_space_range(isl_map_get_space(S));
982 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000983
Sebastian Popa00a0292012-12-18 07:46:06 +0000984 S = isl_map_reverse(S);
985 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000986
Sebastian Popa00a0292012-12-18 07:46:06 +0000987 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
988 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
989 NextScatt = isl_map_apply_domain(NextScatt, S);
990 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000991
Sebastian Popa00a0292012-12-18 07:46:06 +0000992 isl_set *Deltas = isl_map_deltas(NextScatt);
993 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000994}
995
Sebastian Popa00a0292012-12-18 07:46:06 +0000996bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000997 int StrideWidth) const {
998 isl_set *Stride, *StrideX;
999 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001000
Sebastian Popa00a0292012-12-18 07:46:06 +00001001 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +00001002 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +00001003 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1004 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1005 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1006 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001007 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001008
Tobias Grosser28dd4862012-01-24 16:42:16 +00001009 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001010 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001011
Tobias Grosser28dd4862012-01-24 16:42:16 +00001012 return IsStrideX;
1013}
1014
Sebastian Popa00a0292012-12-18 07:46:06 +00001015bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
1016 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001017}
1018
Sebastian Popa00a0292012-12-18 07:46:06 +00001019bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
1020 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001021}
1022
Tobias Grosser166c4222015-09-05 07:46:40 +00001023void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
1024 isl_map_free(NewAccessRelation);
1025 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001026}
Tobias Grosser75805372011-04-29 06:27:02 +00001027
1028//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001029
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001030__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001031 isl_set *Domain = getDomain();
1032 if (isl_set_is_empty(Domain)) {
1033 isl_set_free(Domain);
1034 return isl_map_from_aff(
1035 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1036 }
1037 auto *Schedule = getParent()->getSchedule();
1038 Schedule = isl_union_map_intersect_domain(
1039 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1040 if (isl_union_map_is_empty(Schedule)) {
1041 isl_set_free(Domain);
1042 isl_union_map_free(Schedule);
1043 return isl_map_from_aff(
1044 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1045 }
1046 auto *M = isl_map_from_union_map(Schedule);
1047 M = isl_map_coalesce(M);
1048 M = isl_map_gist_domain(M, Domain);
1049 M = isl_map_coalesce(M);
1050 return M;
1051}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001052
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001053__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
1054 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00001055 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1056 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +00001057}
1058
Tobias Grosser37eb4222014-02-20 21:43:54 +00001059void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1060 assert(isl_set_is_subset(NewDomain, Domain) &&
1061 "New domain is not a subset of old domain!");
1062 isl_set_free(Domain);
1063 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001064}
1065
Michael Krusecac948e2015-10-02 13:53:07 +00001066void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001067 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001068 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001069 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001070
Tobias Grossera535dff2015-12-13 19:59:01 +00001071 ScopArrayInfo::MemoryKind Ty;
1072 if (Access->isPHIKind())
1073 Ty = ScopArrayInfo::MK_PHI;
1074 else if (Access->isExitPHIKind())
1075 Ty = ScopArrayInfo::MK_ExitPHI;
1076 else if (Access->isValueKind())
1077 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001078 else
Tobias Grossera535dff2015-12-13 19:59:01 +00001079 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001080
Johannes Doerfertadeab372016-02-07 13:57:32 +00001081 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
1082 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001083 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001084 }
1085}
1086
Michael Krusecac948e2015-10-02 13:53:07 +00001087void ScopStmt::addAccess(MemoryAccess *Access) {
1088 Instruction *AccessInst = Access->getAccessInstruction();
1089
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001090 if (Access->isArrayKind()) {
1091 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1092 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001093 } else if (Access->isValueKind() && Access->isWrite()) {
1094 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001095 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001096 assert(!ValueWrites.lookup(AccessVal));
1097
1098 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001099 } else if (Access->isValueKind() && Access->isRead()) {
1100 Value *AccessVal = Access->getAccessValue();
1101 assert(!ValueReads.lookup(AccessVal));
1102
1103 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001104 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1105 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
1106 assert(!PHIWrites.lookup(PHI));
1107
1108 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001109 }
1110
1111 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001112}
1113
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001114void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001115 for (MemoryAccess *MA : *this)
1116 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001117
Johannes Doerferta3519512016-04-23 13:02:23 +00001118 InvalidDomain = isl_set_align_params(InvalidDomain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001119 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001120}
1121
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001122/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
1123static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1124 void *User) {
1125 isl_set **BoundedParts = static_cast<isl_set **>(User);
1126 if (isl_basic_set_is_bounded(BSet))
1127 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1128 else
1129 isl_basic_set_free(BSet);
1130 return isl_stat_ok;
1131}
1132
1133/// @brief Return the bounded parts of @p S.
1134static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1135 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1136 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1137 isl_set_free(S);
1138 return BoundedParts;
1139}
1140
1141/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
1142///
1143/// @returns A separation of @p S into first an unbounded then a bounded subset,
1144/// both with regards to the dimension @p Dim.
1145static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1146partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1147
1148 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001149 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001150
1151 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001152 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001153
1154 // Remove dimensions that are greater than Dim as they are not interesting.
1155 assert(NumDimsS >= Dim + 1);
1156 OnlyDimS =
1157 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1158
1159 // Create artificial parametric upper bounds for dimensions smaller than Dim
1160 // as we are not interested in them.
1161 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1162 for (unsigned u = 0; u < Dim; u++) {
1163 isl_constraint *C = isl_inequality_alloc(
1164 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1165 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1166 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1167 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1168 }
1169
1170 // Collect all bounded parts of OnlyDimS.
1171 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1172
1173 // Create the dimensions greater than Dim again.
1174 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1175 NumDimsS - Dim - 1);
1176
1177 // Remove the artificial upper bound parameters again.
1178 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1179
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001180 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001181 return std::make_pair(UnboundedParts, BoundedParts);
1182}
1183
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001184/// @brief Set the dimension Ids from @p From in @p To.
1185static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1186 __isl_take isl_set *To) {
1187 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1188 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1189 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1190 }
1191 return To;
1192}
1193
1194/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001195static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001196 __isl_take isl_pw_aff *L,
1197 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001198 switch (Pred) {
1199 case ICmpInst::ICMP_EQ:
1200 return isl_pw_aff_eq_set(L, R);
1201 case ICmpInst::ICMP_NE:
1202 return isl_pw_aff_ne_set(L, R);
1203 case ICmpInst::ICMP_SLT:
1204 return isl_pw_aff_lt_set(L, R);
1205 case ICmpInst::ICMP_SLE:
1206 return isl_pw_aff_le_set(L, R);
1207 case ICmpInst::ICMP_SGT:
1208 return isl_pw_aff_gt_set(L, R);
1209 case ICmpInst::ICMP_SGE:
1210 return isl_pw_aff_ge_set(L, R);
1211 case ICmpInst::ICMP_ULT:
1212 return isl_pw_aff_lt_set(L, R);
1213 case ICmpInst::ICMP_UGT:
1214 return isl_pw_aff_gt_set(L, R);
1215 case ICmpInst::ICMP_ULE:
1216 return isl_pw_aff_le_set(L, R);
1217 case ICmpInst::ICMP_UGE:
1218 return isl_pw_aff_ge_set(L, R);
1219 default:
1220 llvm_unreachable("Non integer predicate not supported");
1221 }
1222}
1223
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001224/// @brief Create the conditions under which @p L @p Pred @p R is true.
1225///
1226/// Helper function that will make sure the dimensions of the result have the
1227/// same isl_id's as the @p Domain.
1228static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1229 __isl_take isl_pw_aff *L,
1230 __isl_take isl_pw_aff *R,
1231 __isl_keep isl_set *Domain) {
1232 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1233 return setDimensionIds(Domain, ConsequenceCondSet);
1234}
1235
1236/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001237///
1238/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001239/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1240/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001241static void
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001242buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1243 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001244 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1245
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001246 Value *Condition = getConditionFromTerminator(SI);
1247 assert(Condition && "No condition for switch");
1248
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001249 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001250 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001251 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001252 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001253
1254 unsigned NumSuccessors = SI->getNumSuccessors();
1255 ConditionSets.resize(NumSuccessors);
1256 for (auto &Case : SI->cases()) {
1257 unsigned Idx = Case.getSuccessorIndex();
1258 ConstantInt *CaseValue = Case.getCaseValue();
1259
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001260 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001261 isl_set *CaseConditionSet =
1262 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1263 ConditionSets[Idx] = isl_set_coalesce(
1264 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1265 }
1266
1267 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1268 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1269 for (unsigned u = 2; u < NumSuccessors; u++)
1270 ConditionSetUnion =
1271 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1272 ConditionSets[0] = setDimensionIds(
1273 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1274
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001275 isl_pw_aff_free(LHS);
1276}
1277
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001278/// @brief Build the conditions sets for the branch condition @p Condition in
1279/// the @p Domain.
1280///
1281/// This will fill @p ConditionSets with the conditions under which control
1282/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001283/// have as many elements as @p TI has successors. If @p TI is nullptr the
1284/// context under which @p Condition is true/false will be returned as the
1285/// new elements of @p ConditionSets.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001286static void
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001287buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1288 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001289 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1290
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001291 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001292 isl_set *ConsequenceCondSet = nullptr;
1293 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1294 if (CCond->isZero())
1295 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1296 else
1297 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1298 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1299 auto Opcode = BinOp->getOpcode();
1300 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1301
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001302 buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1303 ConditionSets);
1304 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1305 ConditionSets);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001306
1307 isl_set_free(ConditionSets.pop_back_val());
1308 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1309 isl_set_free(ConditionSets.pop_back_val());
1310 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1311
1312 if (Opcode == Instruction::And)
1313 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1314 else
1315 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1316 } else {
1317 auto *ICond = dyn_cast<ICmpInst>(Condition);
1318 assert(ICond &&
1319 "Condition of exiting branch was neither constant nor ICmp!");
1320
1321 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001322 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001323 // For unsigned comparisons we assumed the signed bit of neither operand
1324 // to be set. The comparison is equal to a signed comparison under this
1325 // assumption.
1326 bool NonNeg = ICond->isUnsigned();
1327 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1328 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001329 ConsequenceCondSet =
1330 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1331 }
1332
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001333 // If no terminator was given we are only looking for parameter constraints
1334 // under which @p Condition is true/false.
1335 if (!TI)
1336 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001337 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001338 ConsequenceCondSet = isl_set_coalesce(
1339 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001340
Johannes Doerfertb2885792016-04-26 09:20:41 +00001341 isl_set *AlternativeCondSet = nullptr;
1342 bool ToComplex =
1343 isl_set_n_basic_set(ConsequenceCondSet) >= MaxConjunctsInDomain;
1344
1345 if (!ToComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001346 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1347 isl_set_copy(ConsequenceCondSet));
Johannes Doerfertb2885792016-04-26 09:20:41 +00001348 ToComplex = isl_set_n_basic_set(AlternativeCondSet) >= MaxConjunctsInDomain;
1349 }
1350
1351 if (ToComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001352 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001353 isl_set_free(AlternativeCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001354 AlternativeCondSet = isl_set_empty(isl_set_get_space(ConsequenceCondSet));
Johannes Doerfertb2885792016-04-26 09:20:41 +00001355 isl_set_free(ConsequenceCondSet);
1356 ConsequenceCondSet = isl_set_empty(isl_set_get_space(AlternativeCondSet));
Johannes Doerfert15194912016-04-04 07:59:41 +00001357 }
1358
1359 ConditionSets.push_back(ConsequenceCondSet);
1360 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001361}
1362
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001363/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1364///
1365/// This will fill @p ConditionSets with the conditions under which control
1366/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1367/// have as many elements as @p TI has successors.
1368static void
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001369buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001370 __isl_keep isl_set *Domain,
1371 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1372
1373 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001374 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001375
1376 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1377
1378 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001379 ConditionSets.push_back(isl_set_copy(Domain));
1380 return;
1381 }
1382
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001383 Value *Condition = getConditionFromTerminator(TI);
1384 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001385
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001386 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001387}
1388
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001389void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001390 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001391
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001392 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001393 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001394}
1395
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001396void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP,
1397 ScopDetection &SD) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001398 isl_ctx *Ctx = Parent.getIslCtx();
1399 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1400 Type *Ty = GEP->getPointerOperandType();
1401 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001402
1403 // The set of loads that are required to be invariant.
1404 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001405
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001406 std::vector<const SCEV *> Subscripts;
1407 std::vector<int> Sizes;
1408
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001409 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001410
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001411 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001412 Ty = PtrTy->getElementType();
1413 }
1414
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001415 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001416
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001417 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001418
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001419 auto *NotExecuted = isl_set_complement(isl_set_params(getDomain()));
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001420 for (size_t i = 0; i < Sizes.size(); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001421 auto *Expr = Subscripts[i + IndexOffset];
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001422 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001423
Michael Kruse09eb4452016-03-03 22:10:47 +00001424 auto *Scope = SD.getLI()->getLoopFor(getEntryBlock());
Johannes Doerfert09e36972015-10-07 20:17:36 +00001425 InvariantLoadsSetTy AccessILS;
Johannes Doerfertec8a2172016-04-25 13:32:36 +00001426 if (!isAffineExpr(&Parent.getRegion(), Scope, Expr, SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +00001427 continue;
1428
1429 bool NonAffine = false;
1430 for (LoadInst *LInst : AccessILS)
1431 if (!ScopRIL.count(LInst))
1432 NonAffine = true;
1433
1434 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001435 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001436
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001437 isl_pw_aff *AccessOffset = getPwAff(Expr);
1438 AccessOffset =
1439 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001440
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001441 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1442 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001443
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001444 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1445 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1446 OutOfBound = isl_set_params(OutOfBound);
1447 isl_set *InBound = isl_set_complement(OutOfBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001448
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001449 // A => B == !A or B
1450 isl_set *InBoundIfExecuted =
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001451 isl_set_union(isl_set_copy(NotExecuted), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001452
Roman Gareev10595a12016-01-08 14:01:59 +00001453 InBoundIfExecuted = isl_set_coalesce(InBoundIfExecuted);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00001454 Parent.recordAssumption(INBOUNDS, InBoundIfExecuted, GEP->getDebugLoc(),
1455 AS_ASSUMPTION);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001456 }
1457
1458 isl_local_space_free(LSpace);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001459 isl_set_free(NotExecuted);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001460}
1461
Johannes Doerfertd5c369f2016-04-25 18:55:15 +00001462void ScopStmt::deriveAssumptions(ScopDetection &SD) {
1463 for (auto *MA : *this) {
1464 if (!MA->isArrayKind())
1465 continue;
1466
1467 MemAccInst Acc(MA->getAccessInstruction());
1468 auto *GEP = dyn_cast_or_null<GetElementPtrInst>(Acc.getPointerOperand());
1469
1470 if (GEP)
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001471 deriveAssumptionsFromGEP(GEP, SD);
Johannes Doerfertd5c369f2016-04-25 18:55:15 +00001472 }
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001473}
1474
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001475void ScopStmt::collectSurroundingLoops() {
1476 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1477 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1478 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1479 isl_id_free(DimId);
1480 }
1481}
1482
Michael Kruse9d080092015-09-11 21:41:48 +00001483ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerferta3519512016-04-23 13:02:23 +00001484 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
1485 R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001486
Tobias Grosser16c44032015-07-09 07:31:45 +00001487 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001488}
1489
Michael Kruse9d080092015-09-11 21:41:48 +00001490ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerferta3519512016-04-23 13:02:23 +00001491 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
1492 R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001493
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001494 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001495}
1496
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001497void ScopStmt::init(ScopDetection &SD) {
Michael Krusecac948e2015-10-02 13:53:07 +00001498 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001499
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001500 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001501 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001502 buildAccessRelations();
1503
Johannes Doerfertd5c369f2016-04-25 18:55:15 +00001504 deriveAssumptions(SD);
Michael Krusecac948e2015-10-02 13:53:07 +00001505
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001506 if (DetectReductions)
1507 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001508}
1509
Johannes Doerferte58a0122014-06-27 20:31:28 +00001510/// @brief Collect loads which might form a reduction chain with @p StoreMA
1511///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001512/// Check if the stored value for @p StoreMA is a binary operator with one or
1513/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001514/// used only once (by @p StoreMA) and its load operands are also used only
1515/// once, we have found a possible reduction chain. It starts at an operand
1516/// load and includes the binary operator and @p StoreMA.
1517///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001518/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001519/// escape this block or into any other store except @p StoreMA.
1520void ScopStmt::collectCandiateReductionLoads(
1521 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1522 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1523 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001524 return;
1525
1526 // Skip if there is not one binary operator between the load and the store
1527 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001528 if (!BinOp)
1529 return;
1530
1531 // Skip if the binary operators has multiple uses
1532 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001533 return;
1534
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001535 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001536 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1537 return;
1538
Johannes Doerfert9890a052014-07-01 00:32:29 +00001539 // Skip if the binary operator is outside the current SCoP
1540 if (BinOp->getParent() != Store->getParent())
1541 return;
1542
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001543 // Skip if it is a multiplicative reduction and we disabled them
1544 if (DisableMultiplicativeReductions &&
1545 (BinOp->getOpcode() == Instruction::Mul ||
1546 BinOp->getOpcode() == Instruction::FMul))
1547 return;
1548
Johannes Doerferte58a0122014-06-27 20:31:28 +00001549 // Check the binary operator operands for a candidate load
1550 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1551 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1552 if (!PossibleLoad0 && !PossibleLoad1)
1553 return;
1554
1555 // A load is only a candidate if it cannot escape (thus has only this use)
1556 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001557 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001558 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001559 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001560 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001561 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001562}
1563
1564/// @brief Check for reductions in this ScopStmt
1565///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001566/// Iterate over all store memory accesses and check for valid binary reduction
1567/// like chains. For all candidates we check if they have the same base address
1568/// and there are no other accesses which overlap with them. The base address
1569/// check rules out impossible reductions candidates early. The overlap check,
1570/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001571/// guarantees that none of the intermediate results will escape during
1572/// execution of the loop nest. We basically check here that no other memory
1573/// access can access the same memory as the potential reduction.
1574void ScopStmt::checkForReductions() {
1575 SmallVector<MemoryAccess *, 2> Loads;
1576 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1577
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001578 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001579 // stores and collecting possible reduction loads.
1580 for (MemoryAccess *StoreMA : MemAccs) {
1581 if (StoreMA->isRead())
1582 continue;
1583
1584 Loads.clear();
1585 collectCandiateReductionLoads(StoreMA, Loads);
1586 for (MemoryAccess *LoadMA : Loads)
1587 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1588 }
1589
1590 // Then check each possible candidate pair.
1591 for (const auto &CandidatePair : Candidates) {
1592 bool Valid = true;
1593 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1594 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1595
1596 // Skip those with obviously unequal base addresses.
1597 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1598 isl_map_free(LoadAccs);
1599 isl_map_free(StoreAccs);
1600 continue;
1601 }
1602
1603 // And check if the remaining for overlap with other memory accesses.
1604 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1605 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1606 isl_set *AllAccs = isl_map_range(AllAccsRel);
1607
1608 for (MemoryAccess *MA : MemAccs) {
1609 if (MA == CandidatePair.first || MA == CandidatePair.second)
1610 continue;
1611
1612 isl_map *AccRel =
1613 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1614 isl_set *Accs = isl_map_range(AccRel);
1615
1616 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1617 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1618 Valid = Valid && isl_set_is_empty(OverlapAccs);
1619 isl_set_free(OverlapAccs);
1620 }
1621 }
1622
1623 isl_set_free(AllAccs);
1624 if (!Valid)
1625 continue;
1626
Johannes Doerfertf6183392014-07-01 20:52:51 +00001627 const LoadInst *Load =
1628 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1629 MemoryAccess::ReductionType RT =
1630 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1631
Johannes Doerferte58a0122014-06-27 20:31:28 +00001632 // If no overlapping access was found we mark the load and store as
1633 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001634 CandidatePair.first->markAsReductionLike(RT);
1635 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001636 }
Tobias Grosser75805372011-04-29 06:27:02 +00001637}
1638
Tobias Grosser74394f02013-01-14 22:40:23 +00001639std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001640
Tobias Grosser54839312015-04-21 11:37:25 +00001641std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001642 auto *S = getSchedule();
1643 auto Str = stringFromIslObj(S);
1644 isl_map_free(S);
1645 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001646}
1647
Johannes Doerferta3519512016-04-23 13:02:23 +00001648void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1649 isl_set_free(InvalidDomain);
1650 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001651}
1652
Michael Kruse375cb5f2016-02-24 22:08:24 +00001653BasicBlock *ScopStmt::getEntryBlock() const {
1654 if (isBlockStmt())
1655 return getBasicBlock();
1656 return getRegion()->getEntry();
1657}
1658
Michael Kruse7b5caa42016-02-24 22:08:28 +00001659RegionNode *ScopStmt::getRegionNode() const {
1660 if (isRegionStmt())
1661 return getRegion()->getNode();
1662 return getParent()->getRegion().getBBNode(getBasicBlock());
1663}
1664
Tobias Grosser74394f02013-01-14 22:40:23 +00001665unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001666
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001667unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001668
Tobias Grosser75805372011-04-29 06:27:02 +00001669const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1670
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001671const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001672 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001673}
1674
Tobias Grosser74394f02013-01-14 22:40:23 +00001675isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001676
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001677__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001678
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001679__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001680 return isl_set_get_space(Domain);
1681}
1682
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001683__isl_give isl_id *ScopStmt::getDomainId() const {
1684 return isl_set_get_tuple_id(Domain);
1685}
Tobias Grossercd95b772012-08-30 11:49:38 +00001686
Johannes Doerfert7c013572016-04-12 09:57:34 +00001687ScopStmt::~ScopStmt() {
1688 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001689 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001690}
Tobias Grosser75805372011-04-29 06:27:02 +00001691
1692void ScopStmt::print(raw_ostream &OS) const {
1693 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001694 OS.indent(12) << "Domain :=\n";
1695
1696 if (Domain) {
1697 OS.indent(16) << getDomainStr() << ";\n";
1698 } else
1699 OS.indent(16) << "n/a\n";
1700
Tobias Grosser54839312015-04-21 11:37:25 +00001701 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001702
1703 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001704 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001705 } else
1706 OS.indent(16) << "n/a\n";
1707
Tobias Grosser083d3d32014-06-28 08:59:45 +00001708 for (MemoryAccess *Access : MemAccs)
1709 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001710}
1711
1712void ScopStmt::dump() const { print(dbgs()); }
1713
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001714void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001715 // Remove all memory accesses in @p InvMAs from this statement
1716 // together with all scalar accesses that were caused by them.
Michael Krusead28e5a2016-01-26 13:33:15 +00001717 // MK_Value READs have no access instruction, hence would not be removed by
1718 // this function. However, it is only used for invariant LoadInst accesses,
1719 // its arguments are always affine, hence synthesizable, and therefore there
1720 // are no MK_Value READ accesses to be removed.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001721 for (MemoryAccess *MA : InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001722 auto Predicate = [&](MemoryAccess *Acc) {
Tobias Grosser3a6ac9f2015-11-30 21:13:43 +00001723 return Acc->getAccessInstruction() == MA->getAccessInstruction();
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001724 };
1725 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1726 MemAccs.end());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001727 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001728 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001729}
1730
Tobias Grosser75805372011-04-29 06:27:02 +00001731//===----------------------------------------------------------------------===//
1732/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001733
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001734void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001735 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1736 isl_set_free(Context);
1737 Context = NewContext;
1738}
1739
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001740/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1741struct SCEVSensitiveParameterRewriter
1742 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1743 ValueToValueMap &VMap;
1744 ScalarEvolution &SE;
1745
1746public:
1747 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1748 : VMap(VMap), SE(SE) {}
1749
1750 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1751 ValueToValueMap &VMap) {
1752 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1753 return SSPR.visit(E);
1754 }
1755
1756 const SCEV *visit(const SCEV *E) {
1757 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1758 }
1759
1760 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1761
1762 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1763 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1764 }
1765
1766 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1767 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1768 }
1769
1770 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1771 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1772 }
1773
1774 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1775 SmallVector<const SCEV *, 4> Operands;
1776 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1777 Operands.push_back(visit(E->getOperand(i)));
1778 return SE.getAddExpr(Operands);
1779 }
1780
1781 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1782 SmallVector<const SCEV *, 4> Operands;
1783 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1784 Operands.push_back(visit(E->getOperand(i)));
1785 return SE.getMulExpr(Operands);
1786 }
1787
1788 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1789 SmallVector<const SCEV *, 4> Operands;
1790 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1791 Operands.push_back(visit(E->getOperand(i)));
1792 return SE.getSMaxExpr(Operands);
1793 }
1794
1795 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1796 SmallVector<const SCEV *, 4> Operands;
1797 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1798 Operands.push_back(visit(E->getOperand(i)));
1799 return SE.getUMaxExpr(Operands);
1800 }
1801
1802 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1803 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1804 }
1805
1806 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1807 auto *Start = visit(E->getStart());
1808 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1809 visit(E->getStepRecurrence(SE)),
1810 E->getLoop(), SCEV::FlagAnyWrap);
1811 return SE.getAddExpr(Start, AddRec);
1812 }
1813
1814 const SCEV *visitUnknown(const SCEVUnknown *E) {
1815 if (auto *NewValue = VMap.lookup(E->getValue()))
1816 return SE.getUnknown(NewValue);
1817 return E;
1818 }
1819};
1820
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001821const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001822 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001823}
1824
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001825void Scop::createParameterId(const SCEV *Parameter) {
1826 assert(Parameters.count(Parameter));
1827 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001828
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001829 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001830
Tobias Grosser8f99c162011-11-15 11:38:55 +00001831 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1832 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001833
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001834 // If this parameter references a specific Value and this value has a name
1835 // we use this name as it is likely to be unique and more useful than just
1836 // a number.
1837 if (Val->hasName())
1838 ParameterName = Val->getName();
1839 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001840 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001841 if (LoadOrigin->hasName()) {
1842 ParameterName += "_loaded_from_";
1843 ParameterName +=
1844 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1845 }
1846 }
1847 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001848
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001849 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1850 const_cast<void *>((const void *)Parameter));
1851 ParameterIds[Parameter] = Id;
1852}
1853
1854void Scop::addParams(const ParameterSetTy &NewParameters) {
1855 for (const SCEV *Parameter : NewParameters) {
1856 // Normalize the SCEV to get the representing element for an invariant load.
1857 Parameter = extractConstantFactor(Parameter, *SE).second;
1858 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1859
1860 if (Parameters.insert(Parameter))
1861 createParameterId(Parameter);
1862 }
1863}
1864
1865__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
1866 // Normalize the SCEV to get the representing element for an invariant load.
1867 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1868 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001869}
Tobias Grosser75805372011-04-29 06:27:02 +00001870
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001871__isl_give isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001872 isl_set *DomainContext = isl_union_set_params(getDomains());
1873 return isl_set_intersect_params(C, DomainContext);
1874}
1875
Hongbin Zheng192f69a2016-02-13 15:12:54 +00001876void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
1877 LoopInfo &LI) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001878 auto *R = &getRegion();
1879 auto &F = *R->getEntry()->getParent();
1880 for (auto &Assumption : AC.assumptions()) {
1881 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1882 if (!CI || CI->getNumArgOperands() != 1)
1883 continue;
1884 if (!DT.dominates(CI->getParent(), R->getEntry()))
1885 continue;
1886
Michael Kruse09eb4452016-03-03 22:10:47 +00001887 auto *L = LI.getLoopFor(CI->getParent());
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001888 auto *Val = CI->getArgOperand(0);
Johannes Doerfertf560b3d2016-04-25 13:33:07 +00001889 ParameterSetTy DetectedParams;
1890 if (!isAffineParamConstraint(Val, R, L, *SE, DetectedParams)) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001891 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1892 CI->getDebugLoc(),
1893 "Non-affine user assumption ignored.");
1894 continue;
1895 }
1896
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001897 // Collect all newly introduced parameters.
1898 ParameterSetTy NewParams;
1899 for (auto *Param : DetectedParams) {
1900 Param = extractConstantFactor(Param, *SE).second;
1901 Param = getRepresentingInvariantLoadSCEV(Param);
1902 if (Parameters.count(Param))
1903 continue;
1904 NewParams.insert(Param);
1905 }
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001906
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001907 SmallVector<isl_set *, 2> ConditionSets;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001908 buildConditionSets(*Stmts.begin(), Val, nullptr, L, Context, ConditionSets);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001909 assert(ConditionSets.size() == 2);
1910 isl_set_free(ConditionSets[1]);
1911
1912 auto *AssumptionCtx = ConditionSets[0];
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001913
1914 // Project out newly introduced parameters as they are not otherwise useful.
1915 if (!NewParams.empty()) {
1916 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
1917 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
1918 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
1919 isl_id_free(Id);
1920
1921 if (!NewParams.count(Param))
1922 continue;
1923
1924 AssumptionCtx =
1925 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
1926 }
1927 }
1928
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001929 emitOptimizationRemarkAnalysis(
1930 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1931 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1932 Context = isl_set_intersect(Context, AssumptionCtx);
1933 }
1934}
1935
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001936void Scop::addUserContext() {
1937 if (UserContextStr.empty())
1938 return;
1939
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001940 isl_set *UserContext =
1941 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001942 isl_space *Space = getParamSpace();
1943 if (isl_space_dim(Space, isl_dim_param) !=
1944 isl_set_dim(UserContext, isl_dim_param)) {
1945 auto SpaceStr = isl_space_to_str(Space);
1946 errs() << "Error: the context provided in -polly-context has not the same "
1947 << "number of dimensions than the computed context. Due to this "
1948 << "mismatch, the -polly-context option is ignored. Please provide "
1949 << "the context in the parameter space: " << SpaceStr << ".\n";
1950 free(SpaceStr);
1951 isl_set_free(UserContext);
1952 isl_space_free(Space);
1953 return;
1954 }
1955
1956 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001957 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1958 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001959
1960 if (strcmp(NameContext, NameUserContext) != 0) {
1961 auto SpaceStr = isl_space_to_str(Space);
1962 errs() << "Error: the name of dimension " << i
1963 << " provided in -polly-context "
1964 << "is '" << NameUserContext << "', but the name in the computed "
1965 << "context is '" << NameContext
1966 << "'. Due to this name mismatch, "
1967 << "the -polly-context option is ignored. Please provide "
1968 << "the context in the parameter space: " << SpaceStr << ".\n";
1969 free(SpaceStr);
1970 isl_set_free(UserContext);
1971 isl_space_free(Space);
1972 return;
1973 }
1974
1975 UserContext =
1976 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1977 isl_space_get_dim_id(Space, isl_dim_param, i));
1978 }
1979
1980 Context = isl_set_intersect(Context, UserContext);
1981 isl_space_free(Space);
1982}
1983
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001984void Scop::buildInvariantEquivalenceClasses(ScopDetection &SD) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00001985 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001986
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001987 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001988 for (LoadInst *LInst : RIL) {
1989 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1990
Johannes Doerfert96e54712016-02-07 17:30:13 +00001991 Type *Ty = LInst->getType();
1992 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001993 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001994 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001995 continue;
1996 }
1997
1998 ClassRep = LInst;
Johannes Doerfert96e54712016-02-07 17:30:13 +00001999 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(), nullptr,
2000 Ty);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002001 }
2002}
2003
Tobias Grosser6be480c2011-11-08 15:41:13 +00002004void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002005 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00002006 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002007 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00002008 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00002009}
2010
Tobias Grosser18daaca2012-05-22 10:47:27 +00002011void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002012 unsigned PDim = 0;
2013 for (auto *Parameter : Parameters) {
2014 ConstantRange SRange = SE->getSignedRange(Parameter);
2015 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00002016 }
2017}
2018
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002019void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002020 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002021 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00002022
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002023 unsigned PDim = 0;
2024 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002025 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002026 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00002027 }
2028
2029 // Align the parameters of all data structures to the model.
2030 Context = isl_set_align_params(Context, Space);
2031
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002032 for (ScopStmt &Stmt : *this)
2033 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002034}
2035
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002036static __isl_give isl_set *
2037simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2038 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002039 // If we modelt all blocks in the SCoP that have side effects we can simplify
2040 // the context with the constraints that are needed for anything to be
2041 // executed at all. However, if we have error blocks in the SCoP we already
2042 // assumed some parameter combinations cannot occure and removed them from the
2043 // domains, thus we cannot use the remaining domain to simplify the
2044 // assumptions.
2045 if (!S.hasErrorBlock()) {
2046 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2047 AssumptionContext =
2048 isl_set_gist_params(AssumptionContext, DomainParameters);
2049 }
2050
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002051 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2052 return AssumptionContext;
2053}
2054
2055void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002056 // The parameter constraints of the iteration domains give us a set of
2057 // constraints that need to hold for all cases where at least a single
2058 // statement iteration is executed in the whole scop. We now simplify the
2059 // assumed context under the assumption that such constraints hold and at
2060 // least a single statement iteration is executed. For cases where no
2061 // statement instances are executed, the assumptions we have taken about
2062 // the executed code do not matter and can be changed.
2063 //
2064 // WARNING: This only holds if the assumptions we have taken do not reduce
2065 // the set of statement instances that are executed. Otherwise we
2066 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002067 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002068 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002069 // performed. In such a case, modifying the run-time conditions and
2070 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002071 // to not be executed.
2072 //
2073 // Example:
2074 //
2075 // When delinearizing the following code:
2076 //
2077 // for (long i = 0; i < 100; i++)
2078 // for (long j = 0; j < m; j++)
2079 // A[i+p][j] = 1.0;
2080 //
2081 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002082 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002083 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002084 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002085 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002086}
2087
Johannes Doerfertb164c792014-09-18 11:17:17 +00002088/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002089static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002090 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
2091 isl_pw_multi_aff *MinPMA, *MaxPMA;
2092 isl_pw_aff *LastDimAff;
2093 isl_aff *OneAff;
2094 unsigned Pos;
2095
Johannes Doerfert6296d952016-04-22 11:38:19 +00002096 Set = isl_set_remove_divs(Set);
2097
2098 if (isl_set_n_basic_set(Set) >= MaxConjunctsInDomain) {
2099 isl_set_free(Set);
2100 return isl_stat_error;
2101 }
2102
Johannes Doerfert9143d672014-09-27 11:02:39 +00002103 // Restrict the number of parameters involved in the access as the lexmin/
2104 // lexmax computation will take too long if this number is high.
2105 //
2106 // Experiments with a simple test case using an i7 4800MQ:
2107 //
2108 // #Parameters involved | Time (in sec)
2109 // 6 | 0.01
2110 // 7 | 0.04
2111 // 8 | 0.12
2112 // 9 | 0.40
2113 // 10 | 1.54
2114 // 11 | 6.78
2115 // 12 | 30.38
2116 //
2117 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2118 unsigned InvolvedParams = 0;
2119 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2120 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2121 InvolvedParams++;
2122
2123 if (InvolvedParams > RunTimeChecksMaxParameters) {
2124 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002125 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002126 }
2127 }
2128
Johannes Doerfertb164c792014-09-18 11:17:17 +00002129 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2130 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2131
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002132 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2133 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2134
Johannes Doerfertb164c792014-09-18 11:17:17 +00002135 // Adjust the last dimension of the maximal access by one as we want to
2136 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2137 // we test during code generation might now point after the end of the
2138 // allocated array but we will never dereference it anyway.
2139 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2140 "Assumed at least one output dimension");
2141 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2142 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2143 OneAff = isl_aff_zero_on_domain(
2144 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2145 OneAff = isl_aff_add_constant_si(OneAff, 1);
2146 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2147 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2148
2149 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2150
2151 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002152 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002153}
2154
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002155static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2156 isl_set *Domain = MA->getStatement()->getDomain();
2157 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2158 return isl_set_reset_tuple_id(Domain);
2159}
2160
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002161/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
2162static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00002163 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002164 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002165
2166 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2167 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002168 Locations = isl_union_set_coalesce(Locations);
2169 Locations = isl_union_set_detect_equalities(Locations);
2170 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002171 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002172 isl_union_set_free(Locations);
2173 return Valid;
2174}
2175
Johannes Doerfert96425c22015-08-30 21:13:53 +00002176/// @brief Helper to treat non-affine regions and basic blocks the same.
2177///
2178///{
2179
2180/// @brief Return the block that is the representing block for @p RN.
2181static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2182 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2183 : RN->getNodeAs<BasicBlock>();
2184}
2185
2186/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002187static inline BasicBlock *
2188getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002189 if (RN->isSubRegion()) {
2190 assert(idx == 0);
2191 return RN->getNodeAs<Region>()->getExit();
2192 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002193 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002194}
2195
2196/// @brief Return the smallest loop surrounding @p RN.
2197static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2198 if (!RN->isSubRegion())
2199 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2200
2201 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2202 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2203 while (L && NonAffineSubRegion->contains(L))
2204 L = L->getParentLoop();
2205 return L;
2206}
2207
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002208static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2209 if (!RN->isSubRegion())
2210 return 1;
2211
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002212 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002213 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002214}
2215
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002216static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2217 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002218 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002219 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002220 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002221 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002222 return true;
2223 return false;
2224}
2225
Johannes Doerfert96425c22015-08-30 21:13:53 +00002226///}
2227
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002228static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2229 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002230 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002231 isl_id *DimId =
2232 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2233 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2234}
2235
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002236__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002237 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002238}
2239
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002240__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002241 auto DIt = DomainMap.find(BB);
2242 if (DIt != DomainMap.end())
2243 return isl_set_copy(DIt->getSecond());
2244
2245 auto &RI = *R.getRegionInfo();
2246 auto *BBR = RI.getRegionFor(BB);
2247 while (BBR->getEntry() == BB)
2248 BBR = BBR->getParent();
2249 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002250}
2251
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002252bool Scop::buildDomains(Region *R, ScopDetection &SD, DominatorTree &DT,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002253 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002254
Johannes Doerfert432658d2016-01-26 11:01:41 +00002255 bool IsOnlyNonAffineRegion = SD.isNonAffineSubRegion(R, R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002256 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002257 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2258 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002259 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002260
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002261 while (LD-- >= 0) {
2262 S = addDomainDimId(S, LD + 1, L);
2263 L = L->getParentLoop();
2264 }
2265
Johannes Doerferta3519512016-04-23 13:02:23 +00002266 // Initialize the invalid domain.
2267 auto *EntryStmt = getStmtFor(EntryBB);
2268 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2269
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002270 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002271
Johannes Doerfert432658d2016-01-26 11:01:41 +00002272 if (IsOnlyNonAffineRegion)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002273 return true;
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002274
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002275 if (!buildDomainsWithBranchConstraints(R, SD, DT, LI))
2276 return false;
2277
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002278 propagateDomainConstraints(R, SD, DT, LI);
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002279
2280 // Error blocks and blocks dominated by them have been assumed to never be
2281 // executed. Representing them in the Scop does not add any value. In fact,
2282 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002283 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002284 // will cause problems when building up a ScopStmt for them.
2285 // Furthermore, basic blocks dominated by error blocks may reference
2286 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002287 // can themselves not be constructed properly. To this end we will replace
2288 // the domains of error blocks and those only reachable via error blocks
2289 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002290 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002291 // InvalidDomain. This information is needed during load hoisting.
2292 propagateInvalidStmtDomains(R, SD, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002293
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002294 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002295}
2296
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002297static Loop *
2298getFirstNonBoxedLoopFor(BasicBlock *BB, LoopInfo &LI,
2299 const ScopDetection::BoxedLoopsSetTy &BoxedLoops) {
2300 auto *L = LI.getLoopFor(BB);
2301 while (BoxedLoops.count(L))
2302 L = L->getParentLoop();
2303 return L;
2304}
2305
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002306/// @brief Adjust the dimensions of @p Dom that was constructed for @p OldL
2307/// to be compatible to domains constructed for loop @p NewL.
2308///
2309/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2310/// edge from @p OldL to @p NewL.
2311static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2312 __isl_take isl_set *Dom,
2313 Loop *OldL, Loop *NewL) {
2314
2315 // If the loops are the same there is nothing to do.
2316 if (NewL == OldL)
2317 return Dom;
2318
2319 int OldDepth = S.getRelativeLoopDepth(OldL);
2320 int NewDepth = S.getRelativeLoopDepth(NewL);
2321 // If both loops are non-affine loops there is nothing to do.
2322 if (OldDepth == -1 && NewDepth == -1)
2323 return Dom;
2324
2325 // Distinguish three cases:
2326 // 1) The depth is the same but the loops are not.
2327 // => One loop was left one was entered.
2328 // 2) The depth increased from OldL to NewL.
2329 // => One loop was entered, none was left.
2330 // 3) The depth decreased from OldL to NewL.
2331 // => Loops were left were difference of the depths defines how many.
2332 if (OldDepth == NewDepth) {
2333 assert(OldL->getParentLoop() == NewL->getParentLoop());
2334 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2335 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2336 Dom = addDomainDimId(Dom, NewDepth, NewL);
2337 } else if (OldDepth < NewDepth) {
2338 assert(OldDepth + 1 == NewDepth);
2339 auto &R = S.getRegion();
2340 (void)R;
2341 assert(NewL->getParentLoop() == OldL ||
2342 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2343 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2344 Dom = addDomainDimId(Dom, NewDepth, NewL);
2345 } else {
2346 assert(OldDepth > NewDepth);
2347 int Diff = OldDepth - NewDepth;
2348 int NumDim = isl_set_n_dim(Dom);
2349 assert(NumDim >= Diff);
2350 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2351 }
2352
2353 return Dom;
2354}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002355
Johannes Doerferta3519512016-04-23 13:02:23 +00002356void Scop::propagateInvalidStmtDomains(Region *R, ScopDetection &SD,
2357 DominatorTree &DT, LoopInfo &LI) {
2358 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002359
2360 ReversePostOrderTraversal<Region *> RTraversal(R);
2361 for (auto *RN : RTraversal) {
2362
2363 // Recurse for affine subregions but go on for basic blocks and non-affine
2364 // subregions.
2365 if (RN->isSubRegion()) {
2366 Region *SubRegion = RN->getNodeAs<Region>();
2367 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerferta3519512016-04-23 13:02:23 +00002368 propagateInvalidStmtDomains(SubRegion, SD, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002369 continue;
2370 }
2371 }
2372
2373 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2374 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002375 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002376 isl_set *&Domain = DomainMap[BB];
2377 assert(Domain && "Cannot propagate a nullptr");
2378
Johannes Doerferta3519512016-04-23 13:02:23 +00002379 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002380 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002381 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002382
Johannes Doerferta3519512016-04-23 13:02:23 +00002383 if (!IsInvalidBlock) {
2384 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002385 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002386 isl_set_free(InvalidDomain);
2387 InvalidDomain = Domain;
2388 auto *EmptyDom = isl_set_empty(isl_set_get_space(InvalidDomain));
2389 Domain = EmptyDom;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002390 }
2391
Johannes Doerferta3519512016-04-23 13:02:23 +00002392 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002393 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002394 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002395 }
2396
Johannes Doerferta3519512016-04-23 13:02:23 +00002397 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002398 auto *TI = BB->getTerminator();
2399 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2400 for (unsigned u = 0; u < NumSuccs; u++) {
2401 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002402 auto *SuccStmt = getStmtFor(SuccBB);
2403
2404 // Skip successors outside the SCoP.
2405 if (!SuccStmt)
2406 continue;
2407
Johannes Doerferte4459a22016-04-25 13:34:50 +00002408 // Skip backedges.
2409 if (DT.dominates(SuccBB, BB))
2410 continue;
2411
Johannes Doerferta3519512016-04-23 13:02:23 +00002412 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
2413 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2414 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2415 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2416 SuccInvalidDomain =
2417 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2418 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2419 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2420 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002421
2422 // Check if the maximal number of domain conjuncts was reached.
2423 // In case this happens we will bail.
Johannes Doerfert7c013572016-04-12 09:57:34 +00002424 if (NumConjucts < MaxConjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002425 continue;
2426
Johannes Doerferta3519512016-04-23 13:02:23 +00002427 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002428 invalidate(COMPLEXITY, TI->getDebugLoc());
2429 return;
2430 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002431
2432 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002433 }
2434}
2435
Johannes Doerfert642594a2016-04-04 07:57:39 +00002436void Scop::propagateDomainConstraintsToRegionExit(
2437 BasicBlock *BB, Loop *BBLoop,
2438 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, ScopDetection &SD,
2439 LoopInfo &LI) {
2440
2441 // Check if the block @p BB is the entry of a region. If so we propagate it's
2442 // domain to the exit block of the region. Otherwise we are done.
2443 auto *RI = R.getRegionInfo();
2444 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2445 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
2446 if (!BBReg || BBReg->getEntry() != BB || !R.contains(ExitBB))
2447 return;
2448
2449 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2450 // Do not propagate the domain if there is a loop backedge inside the region
2451 // that would prevent the exit block from beeing executed.
2452 auto *L = BBLoop;
2453 while (L && R.contains(L)) {
2454 SmallVector<BasicBlock *, 4> LatchBBs;
2455 BBLoop->getLoopLatches(LatchBBs);
2456 for (auto *LatchBB : LatchBBs)
2457 if (BB != LatchBB && BBReg->contains(LatchBB))
2458 return;
2459 L = L->getParentLoop();
2460 }
2461
2462 auto *Domain = DomainMap[BB];
2463 assert(Domain && "Cannot propagate a nullptr");
2464
2465 auto *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, BoxedLoops);
2466
2467 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2468 // adjust the domain before we can propagate it.
2469 auto *AdjustedDomain =
2470 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2471 auto *&ExitDomain = DomainMap[ExitBB];
2472
2473 // If the exit domain is not yet created we set it otherwise we "add" the
2474 // current domain.
2475 ExitDomain =
2476 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2477
Johannes Doerferta3519512016-04-23 13:02:23 +00002478 // Initialize the invalid domain.
2479 auto *ExitStmt = getStmtFor(ExitBB);
2480 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2481
Johannes Doerfert642594a2016-04-04 07:57:39 +00002482 FinishedExitBlocks.insert(ExitBB);
2483}
2484
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002485bool Scop::buildDomainsWithBranchConstraints(Region *R, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002486 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert6f50c292016-01-26 11:03:25 +00002487 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002488
2489 // To create the domain for each block in R we iterate over all blocks and
2490 // subregions in R and propagate the conditions under which the current region
2491 // element is executed. To this end we iterate in reverse post order over R as
2492 // it ensures that we first visit all predecessors of a region node (either a
2493 // basic block or a subregion) before we visit the region node itself.
2494 // Initially, only the domain for the SCoP region entry block is set and from
2495 // there we propagate the current domain to all successors, however we add the
2496 // condition that the successor is actually executed next.
2497 // As we are only interested in non-loop carried constraints here we can
2498 // simply skip loop back edges.
2499
Johannes Doerfert642594a2016-04-04 07:57:39 +00002500 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002501 ReversePostOrderTraversal<Region *> RTraversal(R);
2502 for (auto *RN : RTraversal) {
2503
2504 // Recurse for affine subregions but go on for basic blocks and non-affine
2505 // subregions.
2506 if (RN->isSubRegion()) {
2507 Region *SubRegion = RN->getNodeAs<Region>();
2508 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002509 if (!buildDomainsWithBranchConstraints(SubRegion, SD, DT, LI))
2510 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002511 continue;
2512 }
2513 }
2514
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002515 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002516 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002517
Johannes Doerfert96425c22015-08-30 21:13:53 +00002518 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002519 TerminatorInst *TI = BB->getTerminator();
2520
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002521 if (isa<UnreachableInst>(TI))
2522 continue;
2523
Johannes Doerfertf5673802015-10-01 23:48:18 +00002524 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002525 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002526 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002527
Johannes Doerfert642594a2016-04-04 07:57:39 +00002528 auto *BBLoop = getRegionNodeLoop(RN, LI);
2529 // Propagate the domain from BB directly to blocks that have a superset
2530 // domain, at the moment only region exit nodes of regions that start in BB.
2531 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, SD,
2532 LI);
2533
2534 // If all successors of BB have been set a domain through the propagation
2535 // above we do not need to build condition sets but can just skip this
2536 // block. However, it is important to note that this is a local property
2537 // with regards to the region @p R. To this end FinishedExitBlocks is a
2538 // local variable.
2539 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2540 return FinishedExitBlocks.count(SuccBB);
2541 };
2542 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2543 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002544
2545 // Build the condition sets for the successor nodes of the current region
2546 // node. If it is a non-affine subregion we will always execute the single
2547 // exit node, hence the single entry node domain is the condition set. For
2548 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002549 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002550 if (RN->isSubRegion())
2551 ConditionSets.push_back(isl_set_copy(Domain));
2552 else
Johannes Doerfert171b92f2016-04-19 14:53:13 +00002553 buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002554
2555 // Now iterate over the successors and set their initial domain based on
2556 // their condition set. We skip back edges here and have to be careful when
2557 // we leave a loop not to keep constraints over a dimension that doesn't
2558 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002559 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002560 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002561 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002562 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002563
Johannes Doerfert535de032016-04-19 14:49:05 +00002564 auto *SuccStmt = getStmtFor(SuccBB);
2565 // Skip blocks outside the region.
2566 if (!SuccStmt) {
2567 isl_set_free(CondSet);
2568 continue;
2569 }
2570
Johannes Doerfert642594a2016-04-04 07:57:39 +00002571 // If we propagate the domain of some block to "SuccBB" we do not have to
2572 // adjust the domain.
2573 if (FinishedExitBlocks.count(SuccBB)) {
2574 isl_set_free(CondSet);
2575 continue;
2576 }
2577
Johannes Doerfert96425c22015-08-30 21:13:53 +00002578 // Skip back edges.
2579 if (DT.dominates(SuccBB, BB)) {
2580 isl_set_free(CondSet);
2581 continue;
2582 }
2583
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002584 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002585 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002586
2587 // Set the domain for the successor or merge it with an existing domain in
2588 // case there are multiple paths (without loop back edges) to the
2589 // successor block.
2590 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002591
Johannes Doerferta3519512016-04-23 13:02:23 +00002592 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002593 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002594 } else {
2595 // Initialize the invalid domain.
2596 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2597 SuccDomain = CondSet;
2598 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002599
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002600 // Check if the maximal number of domain conjuncts was reached.
2601 // In case this happens we will clean up and bail.
Johannes Doerfert15194912016-04-04 07:59:41 +00002602 if (isl_set_n_basic_set(SuccDomain) < MaxConjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002603 continue;
2604
2605 invalidate(COMPLEXITY, DebugLoc());
2606 while (++u < ConditionSets.size())
2607 isl_set_free(ConditionSets[u]);
2608 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002609 }
2610 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002611
2612 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002613}
2614
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00002615__isl_give isl_set *Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2616 isl_set *Domain,
2617 ScopDetection &SD,
2618 DominatorTree &DT,
2619 LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002620 // If @p BB is the ScopEntry we are done
2621 if (R.getEntry() == BB)
2622 return isl_set_universe(isl_set_get_space(Domain));
2623
2624 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2625 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2626
2627 // The region info of this function.
2628 auto &RI = *R.getRegionInfo();
2629
2630 auto *BBLoop = getFirstNonBoxedLoopFor(BB, LI, BoxedLoops);
2631
2632 // A domain to collect all predecessor domains, thus all conditions under
2633 // which the block is executed. To this end we start with the empty domain.
2634 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2635
2636 // Set of regions of which the entry block domain has been propagated to BB.
2637 // all predecessors inside any of the regions can be skipped.
2638 SmallSet<Region *, 8> PropagatedRegions;
2639
2640 for (auto *PredBB : predecessors(BB)) {
2641 // Skip backedges.
2642 if (DT.dominates(BB, PredBB))
2643 continue;
2644
2645 // If the predecessor is in a region we used for propagation we can skip it.
2646 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2647 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2648 PredBBInRegion)) {
2649 continue;
2650 }
2651
2652 // Check if there is a valid region we can use for propagation, thus look
2653 // for a region that contains the predecessor and has @p BB as exit block.
2654 auto *PredR = RI.getRegionFor(PredBB);
2655 while (PredR->getExit() != BB && !PredR->contains(BB))
2656 PredR->getParent();
2657
2658 // If a valid region for propagation was found use the entry of that region
2659 // for propagation, otherwise the PredBB directly.
2660 if (PredR->getExit() == BB) {
2661 PredBB = PredR->getEntry();
2662 PropagatedRegions.insert(PredR);
2663 }
2664
Johannes Doerfert41cda152016-04-08 10:32:26 +00002665 auto *PredBBDom = getDomainConditions(PredBB);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002666 auto *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, BoxedLoops);
2667 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2668
2669 PredDom = isl_set_union(PredDom, PredBBDom);
2670 }
2671
2672 return PredDom;
2673}
2674
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002675void Scop::propagateDomainConstraints(Region *R, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002676 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002677 // Iterate over the region R and propagate the domain constrains from the
2678 // predecessors to the current node. In contrast to the
2679 // buildDomainsWithBranchConstraints function, this one will pull the domain
2680 // information from the predecessors instead of pushing it to the successors.
2681 // Additionally, we assume the domains to be already present in the domain
2682 // map here. However, we iterate again in reverse post order so we know all
2683 // predecessors have been visited before a block or non-affine subregion is
2684 // visited.
2685
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002686 ReversePostOrderTraversal<Region *> RTraversal(R);
2687 for (auto *RN : RTraversal) {
2688
2689 // Recurse for affine subregions but go on for basic blocks and non-affine
2690 // subregions.
2691 if (RN->isSubRegion()) {
2692 Region *SubRegion = RN->getNodeAs<Region>();
2693 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002694 propagateDomainConstraints(SubRegion, SD, DT, LI);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002695 continue;
2696 }
2697 }
2698
2699 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002700 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002701 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002702
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002703 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002704 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, SD, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002705 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002706 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002707
Johannes Doerfert642594a2016-04-04 07:57:39 +00002708 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002709 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002710 addLoopBoundsToHeaderDomain(BBLoop, LI);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002711
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002712 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002713 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002714 IsOptimized = true;
2715 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002716 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2717 AS_RESTRICTION);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002718 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002719 }
2720}
2721
2722/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2723/// is incremented by one and all other dimensions are equal, e.g.,
2724/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2725/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2726static __isl_give isl_map *
2727createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2728 auto *MapSpace = isl_space_map_from_set(SetSpace);
2729 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2730 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2731 if (u != Dim)
2732 NextIterationMap =
2733 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2734 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2735 C = isl_constraint_set_constant_si(C, 1);
2736 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2737 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2738 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2739 return NextIterationMap;
2740}
2741
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002742void Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002743 int LoopDepth = getRelativeLoopDepth(L);
2744 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002745
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002746 BasicBlock *HeaderBB = L->getHeader();
2747 assert(DomainMap.count(HeaderBB));
2748 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002749
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002750 isl_map *NextIterationMap =
2751 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002752
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002753 isl_set *UnionBackedgeCondition =
2754 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002755
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002756 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2757 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002758
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002759 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002760
2761 // If the latch is only reachable via error statements we skip it.
2762 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2763 if (!LatchBBDom)
2764 continue;
2765
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002766 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002767
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002768 TerminatorInst *TI = LatchBB->getTerminator();
2769 BranchInst *BI = dyn_cast<BranchInst>(TI);
2770 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002771 BackedgeCondition = isl_set_copy(LatchBBDom);
2772 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002773 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002774 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00002775 buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
2776 ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002777
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002778 // Free the non back edge condition set as we do not need it.
2779 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002780
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002781 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002782 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002783
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002784 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2785 assert(LatchLoopDepth >= LoopDepth);
2786 BackedgeCondition =
2787 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2788 LatchLoopDepth - LoopDepth);
2789 UnionBackedgeCondition =
2790 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002791 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002792
2793 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2794 for (int i = 0; i < LoopDepth; i++)
2795 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2796
2797 isl_set *UnionBackedgeConditionComplement =
2798 isl_set_complement(UnionBackedgeCondition);
2799 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2800 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2801 UnionBackedgeConditionComplement =
2802 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2803 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2804 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2805
2806 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2807 HeaderBBDom = Parts.second;
2808
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002809 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2810 // the bounded assumptions to the context as they are already implied by the
2811 // <nsw> tag.
2812 if (Affinator.hasNSWAddRecForLoop(L)) {
2813 isl_set_free(Parts.first);
2814 return;
2815 }
2816
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002817 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002818 recordAssumption(INFINITELOOP, UnboundedCtx,
2819 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002820}
2821
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002822void Scop::buildAliasChecks(AliasAnalysis &AA) {
2823 if (!PollyUseRuntimeAliasChecks)
2824 return;
2825
2826 if (buildAliasGroups(AA))
2827 return;
2828
2829 // If a problem occurs while building the alias groups we need to delete
2830 // this SCoP and pretend it wasn't valid in the first place. To this end
2831 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002832 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002833
2834 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2835 << " could not be created as the number of parameters involved "
2836 "is too high. The SCoP will be "
2837 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2838 "the maximal number of parameters but be advised that the "
2839 "compile time might increase exponentially.\n\n");
2840}
2841
Johannes Doerfert9143d672014-09-27 11:02:39 +00002842bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002843 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002844 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002845 // for all memory accesses inside the SCoP.
2846 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002847 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002848 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002849 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002850 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002851 // if their access domains intersect, otherwise they are in different
2852 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002853 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002854 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002855 // and maximal accesses to each array of a group in read only and non
2856 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002857 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2858
2859 AliasSetTracker AST(AA);
2860
2861 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002862 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002863 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002864
2865 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002866 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002867 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2868 isl_set_free(StmtDomain);
2869 if (StmtDomainEmpty)
2870 continue;
2871
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002872 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002873 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002874 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002875 if (!MA->isRead())
2876 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002877 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00002878 if (MA->isRead() && isa<MemTransferInst>(Acc))
2879 PtrToAcc[cast<MemTransferInst>(Acc)->getSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00002880 else
2881 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002882 AST.add(Acc);
2883 }
2884 }
2885
2886 SmallVector<AliasGroupTy, 4> AliasGroups;
2887 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002888 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002889 continue;
2890 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00002891 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00002892 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00002893 if (AG.size() < 2)
2894 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002895 AliasGroups.push_back(std::move(AG));
2896 }
2897
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002898 // Split the alias groups based on their domain.
2899 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2900 AliasGroupTy NewAG;
2901 AliasGroupTy &AG = AliasGroups[u];
2902 AliasGroupTy::iterator AGI = AG.begin();
2903 isl_set *AGDomain = getAccessDomain(*AGI);
2904 while (AGI != AG.end()) {
2905 MemoryAccess *MA = *AGI;
2906 isl_set *MADomain = getAccessDomain(MA);
2907 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2908 NewAG.push_back(MA);
2909 AGI = AG.erase(AGI);
2910 isl_set_free(MADomain);
2911 } else {
2912 AGDomain = isl_set_union(AGDomain, MADomain);
2913 AGI++;
2914 }
2915 }
2916 if (NewAG.size() > 1)
2917 AliasGroups.push_back(std::move(NewAG));
2918 isl_set_free(AGDomain);
2919 }
2920
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002921 auto &F = *getRegion().getEntry()->getParent();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002922 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002923 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2924 for (AliasGroupTy &AG : AliasGroups) {
2925 NonReadOnlyBaseValues.clear();
2926 ReadOnlyPairs.clear();
2927
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002928 if (AG.size() < 2) {
2929 AG.clear();
2930 continue;
2931 }
2932
Johannes Doerfert13771732014-10-01 12:40:46 +00002933 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002934 emitOptimizationRemarkAnalysis(
2935 F.getContext(), DEBUG_TYPE, F,
2936 (*II)->getAccessInstruction()->getDebugLoc(),
2937 "Possibly aliasing pointer, use restrict keyword.");
2938
Johannes Doerfert13771732014-10-01 12:40:46 +00002939 Value *BaseAddr = (*II)->getBaseAddr();
2940 if (HasWriteAccess.count(BaseAddr)) {
2941 NonReadOnlyBaseValues.insert(BaseAddr);
2942 II++;
2943 } else {
2944 ReadOnlyPairs[BaseAddr].insert(*II);
2945 II = AG.erase(II);
2946 }
2947 }
2948
2949 // If we don't have read only pointers check if there are at least two
2950 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002951 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002952 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002953 continue;
2954 }
2955
2956 // If we don't have non read only pointers clear the alias group.
2957 if (NonReadOnlyBaseValues.empty()) {
2958 AG.clear();
2959 continue;
2960 }
2961
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00002962 // Check if we have non-affine accesses left, if so bail out as we cannot
2963 // generate a good access range yet.
2964 for (auto *MA : AG)
2965 if (!MA->isAffine()) {
2966 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
2967 return false;
2968 }
2969 for (auto &ReadOnlyPair : ReadOnlyPairs)
2970 for (auto *MA : ReadOnlyPair.second)
2971 if (!MA->isAffine()) {
2972 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
2973 return false;
2974 }
2975
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002976 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002977 MinMaxAliasGroups.emplace_back();
2978 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2979 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2980 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2981 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002982
2983 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002984
2985 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002986 for (MemoryAccess *MA : AG)
2987 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002988
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002989 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2990 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002991
2992 // Bail out if the number of values we need to compare is too large.
2993 // This is important as the number of comparisions grows quadratically with
2994 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002995 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2996 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002997 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002998
2999 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003000 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003001 Accesses = isl_union_map_empty(getParamSpace());
3002
3003 for (const auto &ReadOnlyPair : ReadOnlyPairs)
3004 for (MemoryAccess *MA : ReadOnlyPair.second)
3005 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
3006
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00003007 Valid =
3008 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00003009
3010 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003011 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003012 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003013
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003014 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003015}
3016
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003017/// @brief Get the smallest loop that contains @p R but is not in @p R.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003018static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003019 // Start with the smallest loop containing the entry and expand that
3020 // loop until it contains all blocks in the region. If there is a loop
3021 // containing all blocks in the region check if it is itself contained
3022 // and if so take the parent loop as it will be the smallest containing
3023 // the region but not contained by it.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003024 Loop *L = LI.getLoopFor(R.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003025 while (L) {
3026 bool AllContained = true;
3027 for (auto *BB : R.blocks())
3028 AllContained &= L->contains(BB);
3029 if (AllContained)
3030 break;
3031 L = L->getParentLoop();
3032 }
3033
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003034 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
3035}
3036
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00003037static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
3038 ScopDetection &SD) {
3039
3040 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
3041
Johannes Doerferte3da05a2014-11-01 00:12:13 +00003042 unsigned MinLD = INT_MAX, MaxLD = 0;
3043 for (BasicBlock *BB : R.blocks()) {
3044 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00003045 if (!R.contains(L))
3046 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00003047 if (BoxedLoops && BoxedLoops->count(L))
3048 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00003049 unsigned LD = L->getLoopDepth();
3050 MinLD = std::min(MinLD, LD);
3051 MaxLD = std::max(MaxLD, LD);
3052 }
3053 }
3054
3055 // Handle the case that there is no loop in the SCoP first.
3056 if (MaxLD == 0)
3057 return 1;
3058
3059 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
3060 assert(MaxLD >= MinLD &&
3061 "Maximal loop depth was smaller than mininaml loop depth?");
3062 return MaxLD - MinLD + 1;
3063}
3064
Michael Kruse09eb4452016-03-03 22:10:47 +00003065Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
3066 unsigned MaxLoopDepth)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00003067 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003068 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003069 MaxLoopDepth(MaxLoopDepth), IslCtx(isl_ctx_alloc(), isl_ctx_free),
3070 Context(nullptr), Affinator(this, LI), AssumedContext(nullptr),
3071 InvalidContext(nullptr), Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003072 if (IslOnErrorAbort)
3073 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003074 buildContext();
3075}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003076
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00003077void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003078 DominatorTree &DT, LoopInfo &LI) {
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003079 buildInvariantEquivalenceClasses(SD);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003080
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003081 if (!buildDomains(&R, SD, DT, LI))
3082 return;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003083
Johannes Doerfertff68f462016-04-19 14:49:42 +00003084 addUserAssumptions(AC, DT, LI);
3085
Michael Krusecac948e2015-10-02 13:53:07 +00003086 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00003087 // Exit early in case there are no executable statements left in this scop.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003088 simplifySCoP(true, DT, LI);
Michael Kruseafe06702015-10-02 16:33:27 +00003089 if (Stmts.empty())
3090 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003091
Michael Krusecac948e2015-10-02 13:53:07 +00003092 // The ScopStmts now have enough information to initialize themselves.
3093 for (ScopStmt &Stmt : Stmts)
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003094 Stmt.init(SD);
Michael Krusecac948e2015-10-02 13:53:07 +00003095
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003096 buildSchedule(SD, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00003097
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003098 if (!hasFeasibleRuntimeContext())
Tobias Grosser8286b832015-11-02 11:29:32 +00003099 return;
3100
3101 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00003102 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00003103 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00003104 addUserContext();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003105
3106 // After the context was fully constructed, thus all our knowledge about
3107 // the parameters is in there, we add all recorded assumptions to the
3108 // assumed/invalid context.
3109 addRecordedAssumptions();
3110
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003111 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003112 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003113
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003114 hoistInvariantLoads(SD);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003115 verifyInvariantLoads(SD);
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003116 simplifySCoP(false, DT, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00003117}
3118
3119Scop::~Scop() {
3120 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003121 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003122 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003123 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003124
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003125 for (auto &It : ParameterIds)
3126 isl_id_free(It.second);
3127
Johannes Doerfert96425c22015-08-30 21:13:53 +00003128 for (auto It : DomainMap)
3129 isl_set_free(It.second);
3130
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003131 for (auto &AS : RecordedAssumptions)
3132 isl_set_free(AS.Set);
3133
Johannes Doerfertb164c792014-09-18 11:17:17 +00003134 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003135 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003136 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003137 isl_pw_multi_aff_free(MMA.first);
3138 isl_pw_multi_aff_free(MMA.second);
3139 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003140 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003141 isl_pw_multi_aff_free(MMA.first);
3142 isl_pw_multi_aff_free(MMA.second);
3143 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003144 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003145
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003146 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003147 isl_set_free(std::get<2>(IAClass));
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003148
3149 // Explicitly release all Scop objects and the underlying isl objects before
3150 // we relase the isl context.
3151 Stmts.clear();
3152 ScopArrayInfoMap.clear();
3153 AccFuncMap.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003154}
3155
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003156void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003157 // Check all array accesses for each base pointer and find a (virtual) element
3158 // size for the base pointer that divides all access functions.
3159 for (auto &Stmt : *this)
3160 for (auto *Access : Stmt) {
3161 if (!Access->isArrayKind())
3162 continue;
3163 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(),
3164 ScopArrayInfo::MK_Array)];
3165 if (SAI->getNumberOfDimensions() != 1)
3166 continue;
3167 unsigned DivisibleSize = SAI->getElemSizeInBytes();
3168 auto *Subscript = Access->getSubscript(0);
3169 while (!isDivisible(Subscript, DivisibleSize, *SE))
3170 DivisibleSize /= 2;
3171 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
3172 SAI->updateElementType(Ty);
3173 }
3174
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003175 for (auto &Stmt : *this)
3176 for (auto &Access : Stmt)
3177 Access->updateDimensionality();
3178}
3179
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003180void Scop::simplifySCoP(bool RemoveIgnoredStmts, DominatorTree &DT,
3181 LoopInfo &LI) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003182 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3183 ScopStmt &Stmt = *StmtIt;
Michael Kruse7b5caa42016-02-24 22:08:28 +00003184 RegionNode *RN = Stmt.getRegionNode();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003185
Johannes Doerferteca9e892015-11-03 16:54:49 +00003186 bool RemoveStmt = StmtIt->isEmpty();
3187 if (!RemoveStmt)
Michael Kruse375cb5f2016-02-24 22:08:24 +00003188 RemoveStmt = isl_set_is_empty(DomainMap[Stmt.getEntryBlock()]);
Johannes Doerferteca9e892015-11-03 16:54:49 +00003189 if (!RemoveStmt)
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003190 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN, DT, LI));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003191
Johannes Doerferteca9e892015-11-03 16:54:49 +00003192 // Remove read only statements only after invariant loop hoisting.
3193 if (!RemoveStmt && !RemoveIgnoredStmts) {
3194 bool OnlyRead = true;
3195 for (MemoryAccess *MA : Stmt) {
3196 if (MA->isRead())
3197 continue;
3198
3199 OnlyRead = false;
3200 break;
3201 }
3202
3203 RemoveStmt = OnlyRead;
3204 }
3205
3206 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00003207 // Remove the statement because it is unnecessary.
3208 if (Stmt.isRegionStmt())
3209 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3210 StmtMap.erase(BB);
3211 else
3212 StmtMap.erase(Stmt.getBasicBlock());
3213
3214 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003215 continue;
3216 }
3217
Michael Krusecac948e2015-10-02 13:53:07 +00003218 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003219 }
3220}
3221
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003222InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003223 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3224 if (!LInst)
3225 return nullptr;
3226
3227 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3228 LInst = cast<LoadInst>(Rep);
3229
Johannes Doerfert96e54712016-02-07 17:30:13 +00003230 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003231 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003232 for (auto &IAClass : InvariantEquivClasses) {
3233 if (PointerSCEV != std::get<0>(IAClass) || Ty != std::get<3>(IAClass))
3234 continue;
3235
3236 auto &MAs = std::get<1>(IAClass);
3237 for (auto *MA : MAs)
3238 if (MA->getAccessInstruction() == Val)
3239 return &IAClass;
3240 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003241
3242 return nullptr;
3243}
3244
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003245/// @brief Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003246static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
3247 bool MAInvalidCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003248 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3249 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3250 // TODO: We can provide more information for better but more expensive
3251 // results.
3252 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3253 LInst->getAlignment(), DL))
3254 return false;
3255
3256 // If a dereferencable load is in a statement that is modeled precisely we can
3257 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003258 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003259 return true;
3260
3261 // Even if the statement is not modeled precisely we can hoist the load if it
3262 // does not involve any parameters that might have been specilized by the
3263 // statement domain.
3264 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3265 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3266 return false;
3267 return true;
3268}
3269
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003270void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
3271
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003272 if (InvMAs.empty())
3273 return;
3274
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003275 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003276 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003277
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003278 // Get the context under which the statement is executed but remove the error
3279 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003280 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003281 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003282
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003283 if (isl_set_n_basic_set(DomainCtx) >= MaxConjunctsInDomain) {
3284 auto *AccInst = InvMAs.front()->getAccessInstruction();
3285 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3286 isl_set_free(DomainCtx);
3287 return;
3288 }
3289
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003290 // Project out all parameters that relate to loads in the statement. Otherwise
3291 // we could have cyclic dependences on the constraints under which the
3292 // hoisted loads are executed and we could not determine an order in which to
3293 // pre-load them. This happens because not only lower bounds are part of the
3294 // domain but also upper bounds.
3295 for (MemoryAccess *MA : InvMAs) {
3296 Instruction *AccInst = MA->getAccessInstruction();
3297 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003298 SetVector<Value *> Values;
3299 for (const SCEV *Parameter : Parameters) {
3300 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003301 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003302 if (!Values.count(AccInst))
3303 continue;
3304
3305 if (isl_id *ParamId = getIdForParam(Parameter)) {
3306 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
3307 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
3308 isl_id_free(ParamId);
3309 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003310 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003311 }
3312 }
3313
3314 for (MemoryAccess *MA : InvMAs) {
3315 // Check for another invariant access that accesses the same location as
3316 // MA and if found consolidate them. Otherwise create a new equivalence
3317 // class at the end of InvariantEquivClasses.
3318 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003319 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003320 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3321
Johannes Doerfert85676e32016-04-23 14:32:34 +00003322 auto *MAInvalidCtx = MA->getInvalidContext();
3323 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3324
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003325 isl_set *MACtx;
3326 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003327 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003328 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003329 isl_set_free(MAInvalidCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003330 } else {
3331 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003332 MACtx = isl_set_subtract(MACtx, MAInvalidCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003333 MACtx = isl_set_gist_params(MACtx, getContext());
3334 }
3335
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003336 bool Consolidated = false;
3337 for (auto &IAClass : InvariantEquivClasses) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00003338 if (PointerSCEV != std::get<0>(IAClass) || Ty != std::get<3>(IAClass))
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003339 continue;
3340
Johannes Doerfertdf880232016-03-03 12:26:58 +00003341 // If the pointer and the type is equal check if the access function wrt.
3342 // to the domain is equal too. It can happen that the domain fixes
3343 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003344 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003345 // create a new invariant load equivalence class.
3346 auto &MAs = std::get<1>(IAClass);
3347 if (!MAs.empty()) {
3348 auto *LastMA = MAs.front();
3349
3350 auto *AR = isl_map_range(MA->getAccessRelation());
3351 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3352 bool SameAR = isl_set_is_equal(AR, LastAR);
3353 isl_set_free(AR);
3354 isl_set_free(LastAR);
3355
3356 if (!SameAR)
3357 continue;
3358 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003359
3360 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003361 MAs.push_front(MA);
3362
Johannes Doerfertdf880232016-03-03 12:26:58 +00003363 Consolidated = true;
3364
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003365 // Unify the execution context of the class and this statement.
3366 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003367 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003368 IAClassDomainCtx =
3369 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003370 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003371 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003372 break;
3373 }
3374
3375 if (Consolidated)
3376 continue;
3377
3378 // If we did not consolidate MA, thus did not find an equivalence class
3379 // for it, we create a new one.
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003380 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA}, MACtx,
3381 Ty);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003382 }
3383
3384 isl_set_free(DomainCtx);
3385}
3386
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003387bool Scop::isHoistableAccess(MemoryAccess *Access,
3388 __isl_keep isl_union_map *Writes) {
3389 // TODO: Loads that are not loop carried, hence are in a statement with
3390 // zero iterators, are by construction invariant, though we
3391 // currently "hoist" them anyway. This is necessary because we allow
3392 // them to be treated as parameters (e.g., in conditions) and our code
3393 // generation would otherwise use the old value.
3394
3395 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003396 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003397
3398 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
3399 return false;
3400
3401 // Skip accesses that have an invariant base pointer which is defined but
3402 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3403 // returns a pointer that is used as a base address. However, as we want
3404 // to hoist indirect pointers, we allow the base pointer to be defined in
3405 // the region if it is also a memory access. Each ScopArrayInfo object
3406 // that has a base pointer origin has a base pointer that is loaded and
3407 // that it is invariant, thus it will be hoisted too. However, if there is
3408 // no base pointer origin we check that the base pointer is defined
3409 // outside the region.
3410 const ScopArrayInfo *SAI = Access->getScopArrayInfo();
Johannes Doerfert4cf15802016-02-15 12:42:05 +00003411 auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr());
3412 if (SAI->getBasePtrOriginSAI()) {
3413 assert(BasePtrInst && R.contains(BasePtrInst));
3414 if (!isa<LoadInst>(BasePtrInst))
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003415 return false;
Michael Kruse6f7721f2016-02-24 22:08:19 +00003416 auto *BasePtrStmt = getStmtFor(BasePtrInst);
Johannes Doerfert4cf15802016-02-15 12:42:05 +00003417 assert(BasePtrStmt);
3418 auto *BasePtrMA = BasePtrStmt->getArrayAccessOrNULLFor(BasePtrInst);
3419 if (BasePtrMA && !isHoistableAccess(BasePtrMA, Writes))
3420 return false;
3421 } else if (BasePtrInst && R.contains(BasePtrInst))
3422 return false;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003423
3424 // Skip accesses in non-affine subregions as they might not be executed
3425 // under the same condition as the entry of the non-affine subregion.
3426 if (BB != Access->getAccessInstruction()->getParent())
3427 return false;
3428
3429 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003430 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003431
3432 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3433 Stmt.getNumIterators())) {
3434 isl_map_free(AccessRelation);
3435 return false;
3436 }
3437
3438 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3439 isl_set *AccessRange = isl_map_range(AccessRelation);
3440
3441 isl_union_map *Written = isl_union_map_intersect_range(
3442 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
3443 bool IsWritten = !isl_union_map_is_empty(Written);
3444 isl_union_map_free(Written);
3445
3446 if (IsWritten)
3447 return false;
3448
3449 return true;
3450}
3451
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003452void Scop::verifyInvariantLoads(ScopDetection &SD) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003453 auto &RIL = *SD.getRequiredInvariantLoads(&getRegion());
3454 for (LoadInst *LI : RIL) {
3455 assert(LI && getRegion().contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003456 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003457 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003458 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3459 return;
3460 }
3461 }
3462}
3463
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003464void Scop::hoistInvariantLoads(ScopDetection &SD) {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003465 if (!PollyInvariantLoadHoisting)
3466 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003467
Tobias Grosser0865e7752016-02-29 07:29:42 +00003468 isl_union_map *Writes = getWrites();
3469 for (ScopStmt &Stmt : *this) {
3470 MemoryAccessList InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003471
Tobias Grosser0865e7752016-02-29 07:29:42 +00003472 for (MemoryAccess *Access : Stmt)
3473 if (isHoistableAccess(Access, Writes))
3474 InvariantAccesses.push_front(Access);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003475
Tobias Grosser0865e7752016-02-29 07:29:42 +00003476 // We inserted invariant accesses always in the front but need them to be
3477 // sorted in a "natural order". The statements are already sorted in
3478 // reverse post order and that suffices for the accesses too. The reason
3479 // we require an order in the first place is the dependences between
3480 // invariant loads that can be caused by indirect loads.
3481 InvariantAccesses.reverse();
3482
3483 // Transfer the memory access from the statement to the SCoP.
3484 Stmt.removeMemoryAccesses(InvariantAccesses);
3485 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003486 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003487 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003488}
3489
Johannes Doerfert80ef1102014-11-07 08:31:31 +00003490const ScopArrayInfo *
Tobias Grossercc779502016-02-02 13:22:54 +00003491Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003492 ArrayRef<const SCEV *> Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00003493 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003494 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003495 if (!SAI) {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003496 auto &DL = getRegion().getEntry()->getModule()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003497 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003498 DL, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003499 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003500 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003501 // In case of mismatching array sizes, we bail out by setting the run-time
3502 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003503 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003504 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003505 }
Tobias Grosserab671442015-05-23 05:58:27 +00003506 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003507}
3508
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003509const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00003510 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003511 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003512 assert(SAI && "No ScopArrayInfo available for this base pointer");
3513 return SAI;
3514}
3515
Tobias Grosser74394f02013-01-14 22:40:23 +00003516std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003517
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003518std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003519 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003520 return stringFromIslObj(AssumedContext);
3521}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003522
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003523std::string Scop::getInvalidContextStr() const {
3524 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003525}
Tobias Grosser75805372011-04-29 06:27:02 +00003526
3527std::string Scop::getNameStr() const {
3528 std::string ExitName, EntryName;
3529 raw_string_ostream ExitStr(ExitName);
3530 raw_string_ostream EntryStr(EntryName);
3531
Tobias Grosserf240b482014-01-09 10:42:15 +00003532 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003533 EntryStr.str();
3534
3535 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003536 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003537 ExitStr.str();
3538 } else
3539 ExitName = "FunctionExit";
3540
3541 return EntryName + "---" + ExitName;
3542}
3543
Tobias Grosser74394f02013-01-14 22:40:23 +00003544__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003545__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003546 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003547}
3548
Tobias Grossere86109f2013-10-29 21:05:49 +00003549__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003550 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003551 return isl_set_copy(AssumedContext);
3552}
3553
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003554bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003555 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003556 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00003557 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3558 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
3559 isl_set_is_subset(PositiveContext, NegativeContext));
3560 isl_set_free(PositiveContext);
3561 if (!IsFeasible) {
3562 isl_set_free(NegativeContext);
3563 return false;
3564 }
3565
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003566 auto *DomainContext = isl_union_set_params(getDomains());
3567 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00003568 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003569 isl_set_free(NegativeContext);
3570 isl_set_free(DomainContext);
3571
Johannes Doerfert43788c52015-08-20 05:58:56 +00003572 return IsFeasible;
3573}
3574
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003575static std::string toString(AssumptionKind Kind) {
3576 switch (Kind) {
3577 case ALIASING:
3578 return "No-aliasing";
3579 case INBOUNDS:
3580 return "Inbounds";
3581 case WRAPPING:
3582 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00003583 case UNSIGNED:
3584 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003585 case COMPLEXITY:
3586 return "Low complexity";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003587 case ERRORBLOCK:
3588 return "No-error";
3589 case INFINITELOOP:
3590 return "Finite loop";
3591 case INVARIANTLOAD:
3592 return "Invariant load";
3593 case DELINEARIZATION:
3594 return "Delinearization";
3595 }
3596 llvm_unreachable("Unknown AssumptionKind!");
3597}
3598
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003599bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3600 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert2f705842016-04-12 16:09:44 +00003601 if (PollyRemarksMinimal) {
3602 if (Sign == AS_ASSUMPTION) {
3603 if (isl_set_is_subset(Context, Set))
3604 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003605
Johannes Doerfert2f705842016-04-12 16:09:44 +00003606 if (isl_set_is_subset(AssumedContext, Set))
3607 return false;
3608 } else {
3609 if (isl_set_is_disjoint(Set, Context))
3610 return false;
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003611
Johannes Doerfert2f705842016-04-12 16:09:44 +00003612 if (isl_set_is_subset(Set, InvalidContext))
3613 return false;
3614 }
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003615 }
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003616
3617 auto &F = *getRegion().getEntry()->getParent();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003618 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
3619 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003620 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003621 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003622}
3623
3624void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003625 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003626 // Simplify the assumptions/restrictions first.
3627 Set = isl_set_gist_params(Set, getContext());
3628
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003629 if (!trackAssumption(Kind, Set, Loc, Sign)) {
3630 isl_set_free(Set);
3631 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003632 }
3633
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003634 if (Sign == AS_ASSUMPTION) {
3635 AssumedContext = isl_set_intersect(AssumedContext, Set);
3636 AssumedContext = isl_set_coalesce(AssumedContext);
3637 } else {
3638 InvalidContext = isl_set_union(InvalidContext, Set);
3639 InvalidContext = isl_set_coalesce(InvalidContext);
3640 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003641}
3642
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003643void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003644 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
3645 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003646}
3647
3648void Scop::addRecordedAssumptions() {
3649 while (!RecordedAssumptions.empty()) {
3650 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003651
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003652 if (!AS.BB) {
3653 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
3654 continue;
3655 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003656
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003657 // If a basic block was given use its domain to simplify the assumption.
3658 // In case of restrictions we know they only have to hold on the domain,
3659 // thus we can intersect them with the domain of the block. However, for
3660 // assumptions the domain has to imply them, thus:
3661 // _ _____
3662 // Dom => S <==> A v B <==> A - B
3663 //
3664 // To avoid the complement we will register A - B as a restricton not an
3665 // assumption.
3666 isl_set *S = AS.Set;
3667 isl_set *Dom = getDomainConditions(AS.BB);
3668 if (AS.Sign == AS_RESTRICTION)
3669 S = isl_set_params(isl_set_intersect(S, Dom));
3670 else /* (AS.Sign == AS_ASSUMPTION) */
3671 S = isl_set_params(isl_set_subtract(Dom, S));
3672
3673 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003674 }
3675}
3676
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003677void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003678 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003679}
3680
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003681__isl_give isl_set *Scop::getInvalidContext() const {
3682 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003683}
3684
Tobias Grosser75805372011-04-29 06:27:02 +00003685void Scop::printContext(raw_ostream &OS) const {
3686 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003687 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003688
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003689 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003690 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003691
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003692 OS.indent(4) << "Invalid Context:\n";
3693 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003694
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003695 unsigned Dim = 0;
3696 for (const SCEV *Parameter : Parameters)
3697 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003698}
3699
Johannes Doerfertb164c792014-09-18 11:17:17 +00003700void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003701 int noOfGroups = 0;
3702 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003703 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003704 noOfGroups += 1;
3705 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003706 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003707 }
3708
Tobias Grosserbb853c22015-07-25 12:31:03 +00003709 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003710 if (MinMaxAliasGroups.empty()) {
3711 OS.indent(8) << "n/a\n";
3712 return;
3713 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003714
Tobias Grosserbb853c22015-07-25 12:31:03 +00003715 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003716
3717 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003718 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003719 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003720 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003721 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3722 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003723 }
3724 OS << " ]]\n";
3725 }
3726
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003727 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003728 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003729 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003730 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003731 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3732 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003733 }
3734 OS << " ]]\n";
3735 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003736 }
3737}
3738
Tobias Grosser75805372011-04-29 06:27:02 +00003739void Scop::printStatements(raw_ostream &OS) const {
3740 OS << "Statements {\n";
3741
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003742 for (const ScopStmt &Stmt : *this)
3743 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003744
3745 OS.indent(4) << "}\n";
3746}
3747
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003748void Scop::printArrayInfo(raw_ostream &OS) const {
3749 OS << "Arrays {\n";
3750
Tobias Grosserab671442015-05-23 05:58:27 +00003751 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003752 Array.second->print(OS);
3753
3754 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003755
3756 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3757
3758 for (auto &Array : arrays())
3759 Array.second->print(OS, /* SizeAsPwAff */ true);
3760
3761 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003762}
3763
Tobias Grosser75805372011-04-29 06:27:02 +00003764void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00003765 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
3766 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003767 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003768 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003769 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003770 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003771 const auto &MAs = std::get<1>(IAClass);
3772 if (MAs.empty()) {
3773 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003774 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003775 MAs.front()->print(OS);
3776 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003777 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003778 }
3779 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003780 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003781 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003782 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003783 printStatements(OS.indent(4));
3784}
3785
3786void Scop::dump() const { print(dbgs()); }
3787
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003788isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00003789
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003790__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
3791 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003792 // First try to use the SCEVAffinator to generate a piecewise defined
3793 // affine function from @p E in the context of @p BB. If that tasks becomes to
3794 // complex the affinator might return a nullptr. In such a case we invalidate
3795 // the SCoP and return a dummy value. This way we do not need to add error
3796 // handling cdoe to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003797 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003798 if (PWAC.first) {
3799 if (NonNegative)
3800 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003801 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003802 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003803
3804 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
3805 invalidate(COMPLEXITY, DL);
3806 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003807}
3808
Tobias Grosser808cd692015-07-14 09:33:13 +00003809__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003810 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003811
Tobias Grosser808cd692015-07-14 09:33:13 +00003812 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003813 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003814
3815 return Domain;
3816}
3817
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003818__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
3819 PWACtx PWAC = getPwAff(E, BB);
3820 isl_set_free(PWAC.second);
3821 return PWAC.first;
3822}
3823
Tobias Grossere5a35142015-11-12 14:07:09 +00003824__isl_give isl_union_map *
3825Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3826 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003827
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003828 for (ScopStmt &Stmt : *this) {
3829 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003830 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003831 continue;
3832
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003833 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003834 isl_map *AccessDomain = MA->getAccessRelation();
3835 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003836 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003837 }
3838 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003839 return isl_union_map_coalesce(Accesses);
3840}
3841
3842__isl_give isl_union_map *Scop::getMustWrites() {
3843 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003844}
3845
3846__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003847 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003848}
3849
Tobias Grosser37eb4222014-02-20 21:43:54 +00003850__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003851 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003852}
3853
3854__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003855 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003856}
3857
Tobias Grosser2ac23382015-11-12 14:07:13 +00003858__isl_give isl_union_map *Scop::getAccesses() {
3859 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3860}
3861
Tobias Grosser808cd692015-07-14 09:33:13 +00003862__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00003863 auto *Tree = getScheduleTree();
3864 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00003865 isl_schedule_free(Tree);
3866 return S;
3867}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003868
Tobias Grosser808cd692015-07-14 09:33:13 +00003869__isl_give isl_schedule *Scop::getScheduleTree() const {
3870 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3871 getDomains());
3872}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003873
Tobias Grosser808cd692015-07-14 09:33:13 +00003874void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3875 auto *S = isl_schedule_from_domain(getDomains());
3876 S = isl_schedule_insert_partial_schedule(
3877 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3878 isl_schedule_free(Schedule);
3879 Schedule = S;
3880}
3881
3882void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3883 isl_schedule_free(Schedule);
3884 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003885}
3886
3887bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3888 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003889 for (ScopStmt &Stmt : *this) {
3890 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003891 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3892 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3893
3894 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3895 isl_union_set_free(StmtDomain);
3896 isl_union_set_free(NewStmtDomain);
3897 continue;
3898 }
3899
3900 Changed = true;
3901
3902 isl_union_set_free(StmtDomain);
3903 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3904
3905 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003906 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003907 isl_union_set_free(NewStmtDomain);
3908 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003909 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003910 }
3911 isl_union_set_free(Domain);
3912 return Changed;
3913}
3914
Tobias Grosser75805372011-04-29 06:27:02 +00003915ScalarEvolution *Scop::getSE() const { return SE; }
3916
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003917bool Scop::isIgnored(RegionNode *RN, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003918 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Michael Kruse6f7721f2016-02-24 22:08:19 +00003919 ScopStmt *Stmt = getStmtFor(RN);
Michael Krusea902ba62015-12-13 19:21:45 +00003920
3921 // If there is no stmt, then it already has been removed.
3922 if (!Stmt)
3923 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00003924
Johannes Doerfertf5673802015-10-01 23:48:18 +00003925 // Check if there are accesses contained.
Michael Krusea902ba62015-12-13 19:21:45 +00003926 if (Stmt->isEmpty())
Johannes Doerfertf5673802015-10-01 23:48:18 +00003927 return true;
3928
3929 // Check for reachability via non-error blocks.
3930 if (!DomainMap.count(BB))
3931 return true;
3932
3933 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003934 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003935 return true;
3936
3937 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003938}
3939
Tobias Grosser808cd692015-07-14 09:33:13 +00003940struct MapToDimensionDataTy {
3941 int N;
3942 isl_union_pw_multi_aff *Res;
3943};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003944
Tobias Grosser808cd692015-07-14 09:33:13 +00003945// @brief Create a function that maps the elements of 'Set' to its N-th
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003946// dimension and add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00003947//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003948// @param Set The input set.
3949// @param User->N The dimension to map to.
3950// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00003951//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003952// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00003953static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3954 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3955 int Dim;
3956 isl_space *Space;
3957 isl_pw_multi_aff *PMA;
3958
3959 Dim = isl_set_dim(Set, isl_dim_set);
3960 Space = isl_set_get_space(Set);
3961 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3962 Dim - Data->N);
3963 if (Data->N > 1)
3964 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3965 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3966
3967 isl_set_free(Set);
3968
3969 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003970}
3971
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003972// @brief Create an isl_multi_union_aff that defines an identity mapping
3973// from the elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003974//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003975// # Example:
3976//
3977// Domain: { A[i,j]; B[i,j,k] }
3978// N: 1
3979//
3980// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
3981//
3982// @param USet A union set describing the elements for which to generate a
3983// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00003984// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003985// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003986static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003987mapToDimension(__isl_take isl_union_set *USet, int N) {
3988 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00003989 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003990 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003991
Tobias Grosser808cd692015-07-14 09:33:13 +00003992 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00003993
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003994 auto *Space = isl_union_set_get_space(USet);
3995 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00003996
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003997 Data = {N, PwAff};
3998
3999 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004000 (void)Res;
4001
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004002 assert(Res == isl_stat_ok);
4003
4004 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00004005 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4006}
4007
Tobias Grosser316b5b22015-11-11 19:28:14 +00004008void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00004009 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00004010 Stmts.emplace_back(*this, *BB);
Johannes Doerferta90943d2016-02-21 16:37:25 +00004011 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00004012 StmtMap[BB] = Stmt;
4013 } else {
4014 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00004015 Stmts.emplace_back(*this, *R);
Johannes Doerferta90943d2016-02-21 16:37:25 +00004016 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00004017 for (BasicBlock *BB : R->blocks())
4018 StmtMap[BB] = Stmt;
4019 }
Tobias Grosser808cd692015-07-14 09:33:13 +00004020}
4021
Hongbin Zheng192f69a2016-02-13 15:12:54 +00004022void Scop::buildSchedule(ScopDetection &SD, LoopInfo &LI) {
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004023 Loop *L = getLoopSurroundingRegion(getRegion(), LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004024 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Hongbin Zheng192f69a2016-02-13 15:12:54 +00004025 buildSchedule(getRegion().getNode(), LoopStack, SD, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004026 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4027 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004028}
4029
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004030/// To generate a schedule for the elements in a Region we traverse the Region
4031/// in reverse-post-order and add the contained RegionNodes in traversal order
4032/// to the schedule of the loop that is currently at the top of the LoopStack.
4033/// For loop-free codes, this results in a correct sequential ordering.
4034///
4035/// Example:
4036/// bb1(0)
4037/// / \.
4038/// bb2(1) bb3(2)
4039/// \ / \.
4040/// bb4(3) bb5(4)
4041/// \ /
4042/// bb6(5)
4043///
4044/// Including loops requires additional processing. Whenever a loop header is
4045/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4046/// from an empty schedule, we first process all RegionNodes that are within
4047/// this loop and complete the sequential schedule at this loop-level before
4048/// processing about any other nodes. To implement this
4049/// loop-nodes-first-processing, the reverse post-order traversal is
4050/// insufficient. Hence, we additionally check if the traversal yields
4051/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4052/// These region-nodes are then queue and only traverse after the all nodes
4053/// within the current loop have been processed.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00004054void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, ScopDetection &SD,
4055 LoopInfo &LI) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004056 Loop *OuterScopLoop = getLoopSurroundingRegion(getRegion(), LI);
4057
4058 ReversePostOrderTraversal<Region *> RTraversal(R);
4059 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4060 std::deque<RegionNode *> DelayList;
4061 bool LastRNWaiting = false;
4062
4063 // Iterate over the region @p R in reverse post-order but queue
4064 // sub-regions/blocks iff they are not part of the last encountered but not
4065 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4066 // that we queued the last sub-region/block from the reverse post-order
4067 // iterator. If it is set we have to explore the next sub-region/block from
4068 // the iterator (if any) to guarantee progress. If it is not set we first try
4069 // the next queued sub-region/blocks.
4070 while (!WorkList.empty() || !DelayList.empty()) {
4071 RegionNode *RN;
4072
4073 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4074 RN = WorkList.front();
4075 WorkList.pop_front();
4076 LastRNWaiting = false;
4077 } else {
4078 RN = DelayList.front();
4079 DelayList.pop_front();
4080 }
4081
4082 Loop *L = getRegionNodeLoop(RN, LI);
4083 if (!getRegion().contains(L))
4084 L = OuterScopLoop;
4085
Tobias Grosser151ae322016-04-03 19:36:52 +00004086 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004087 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004088 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004089 LastRNWaiting = true;
4090 DelayList.push_back(RN);
4091 continue;
4092 }
4093 LoopStack.push_back({L, nullptr, 0});
4094 }
Hongbin Zheng192f69a2016-02-13 15:12:54 +00004095 buildSchedule(RN, LoopStack, SD, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004096 }
4097
4098 return;
4099}
4100
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00004101void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00004102 ScopDetection &SD, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004103
Tobias Grosser8362c262016-01-06 15:30:06 +00004104 if (RN->isSubRegion()) {
4105 auto *LocalRegion = RN->getNodeAs<Region>();
4106 if (!SD.isNonAffineSubRegion(LocalRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00004107 buildSchedule(LocalRegion, LoopStack, SD, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004108 return;
4109 }
4110 }
Michael Kruse046dde42015-08-10 13:01:57 +00004111
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004112 auto &LoopData = LoopStack.back();
4113 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004114
Michael Kruse6f7721f2016-02-24 22:08:19 +00004115 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004116 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4117 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004118 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004119 }
4120
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004121 // Check if we just processed the last node in this loop. If we did, finalize
4122 // the loop by:
4123 //
4124 // - adding new schedule dimensions
4125 // - folding the resulting schedule into the parent loop schedule
4126 // - dropping the loop schedule from the LoopStack.
4127 //
4128 // Then continue to check surrounding loops, which might also have been
4129 // completed by this node.
4130 while (LoopData.L &&
4131 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004132 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004133 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004134
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004135 LoopStack.pop_back();
4136 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004137
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004138 if (Schedule) {
4139 auto *Domain = isl_schedule_get_domain(Schedule);
4140 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4141 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4142 NextLoopData.Schedule =
4143 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004144 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004145
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004146 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4147 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004148 }
Tobias Grosser75805372011-04-29 06:27:02 +00004149}
4150
Michael Kruse6f7721f2016-02-24 22:08:19 +00004151ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004152 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004153 if (StmtMapIt == StmtMap.end())
4154 return nullptr;
4155 return StmtMapIt->second;
4156}
4157
Michael Kruse6f7721f2016-02-24 22:08:19 +00004158ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4159 if (RN->isSubRegion())
4160 return getStmtFor(RN->getNodeAs<Region>());
4161 return getStmtFor(RN->getNodeAs<BasicBlock>());
4162}
4163
4164ScopStmt *Scop::getStmtFor(Region *R) const {
4165 ScopStmt *Stmt = getStmtFor(R->getEntry());
4166 assert(!Stmt || Stmt->getRegion() == R);
4167 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004168}
4169
Johannes Doerfert96425c22015-08-30 21:13:53 +00004170int Scop::getRelativeLoopDepth(const Loop *L) const {
4171 Loop *OuterLoop =
4172 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4173 if (!OuterLoop)
4174 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004175 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4176}
4177
Michael Krused868b5d2015-09-10 15:25:24 +00004178void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00004179 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00004180
4181 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
4182 // true, are not modeled as ordinary PHI nodes as they are not part of the
4183 // region. However, we model the operands in the predecessor blocks that are
4184 // part of the region as regular scalar accesses.
4185
4186 // If we can synthesize a PHI we can skip it, however only if it is in
4187 // the region. If it is not it can only be in the exit block of the region.
4188 // In this case we model the operands but not the PHI itself.
Michael Krusec7e0d9c2016-03-01 21:44:06 +00004189 auto *Scope = LI->getLoopFor(PHI->getParent());
4190 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R, Scope))
Michael Kruse7bf39442015-09-10 12:46:52 +00004191 return;
4192
4193 // PHI nodes are modeled as if they had been demoted prior to the SCoP
4194 // detection. Hence, the PHI is a load of a new memory location in which the
4195 // incoming value was written at the end of the incoming basic block.
4196 bool OnlyNonAffineSubRegionOperands = true;
4197 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
4198 Value *Op = PHI->getIncomingValue(u);
4199 BasicBlock *OpBB = PHI->getIncomingBlock(u);
4200
4201 // Do not build scalar dependences inside a non-affine subregion.
4202 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
4203 continue;
4204
4205 OnlyNonAffineSubRegionOperands = false;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004206 ensurePHIWrite(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00004207 }
4208
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004209 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
4210 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00004211 }
4212}
4213
Michael Kruse2e02d562016-02-06 09:19:40 +00004214void ScopInfo::buildScalarDependences(Instruction *Inst) {
4215 assert(!isa<PHINode>(Inst));
Michael Kruse7bf39442015-09-10 12:46:52 +00004216
Michael Kruse2e02d562016-02-06 09:19:40 +00004217 // Pull-in required operands.
4218 for (Use &Op : Inst->operands())
4219 ensureValueRead(Op.get(), Inst->getParent());
4220}
Michael Kruse7bf39442015-09-10 12:46:52 +00004221
Michael Kruse2e02d562016-02-06 09:19:40 +00004222void ScopInfo::buildEscapingDependences(Instruction *Inst) {
4223 Region *R = &scop->getRegion();
Michael Kruse7bf39442015-09-10 12:46:52 +00004224
Michael Kruse2e02d562016-02-06 09:19:40 +00004225 // Check for uses of this instruction outside the scop. Because we do not
4226 // iterate over such instructions and therefore did not "ensure" the existence
4227 // of a write, we must determine such use here.
4228 for (Use &U : Inst->uses()) {
4229 Instruction *UI = dyn_cast<Instruction>(U.getUser());
4230 if (!UI)
Michael Kruse7bf39442015-09-10 12:46:52 +00004231 continue;
4232
Michael Kruse2e02d562016-02-06 09:19:40 +00004233 BasicBlock *UseParent = getUseBlock(U);
4234 BasicBlock *UserParent = UI->getParent();
Michael Kruse7bf39442015-09-10 12:46:52 +00004235
Michael Kruse2e02d562016-02-06 09:19:40 +00004236 // An escaping value is either used by an instruction not within the scop,
4237 // or (when the scop region's exit needs to be simplified) by a PHI in the
4238 // scop's exit block. This is because region simplification before code
4239 // generation inserts new basic blocks before the PHI such that its incoming
4240 // blocks are not in the scop anymore.
4241 if (!R->contains(UseParent) ||
4242 (isa<PHINode>(UI) && UserParent == R->getExit() &&
4243 R->getExitingBlock())) {
4244 // At least one escaping use found.
4245 ensureValueWrite(Inst);
4246 break;
Michael Kruse7bf39442015-09-10 12:46:52 +00004247 }
4248 }
Michael Kruse7bf39442015-09-10 12:46:52 +00004249}
4250
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004251bool ScopInfo::buildAccessMultiDimFixed(
Michael Kruse70131d32016-01-27 17:09:17 +00004252 MemAccInst Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00004253 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
4254 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse70131d32016-01-27 17:09:17 +00004255 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004256 Type *ElementType = Val->getType();
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004257 Value *Address = Inst.getPointerOperand();
Tobias Grosser5fd8c092015-09-17 17:28:15 +00004258 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00004259 const SCEVUnknown *BasePointer =
4260 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004261 enum MemoryAccess::AccessType AccType =
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004262 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00004263
Michael Kruse37d136e2016-02-26 16:08:24 +00004264 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
4265 auto *Src = BitCast->getOperand(0);
4266 auto *SrcTy = Src->getType();
4267 auto *DstTy = BitCast->getType();
Johannes Doerfert41725a12016-04-08 19:20:03 +00004268 // Do not try to delinearize non-sized (opaque) pointers.
4269 if ((SrcTy->isPointerTy() && !SrcTy->getPointerElementType()->isSized()) ||
4270 (DstTy->isPointerTy() && !DstTy->getPointerElementType()->isSized())) {
4271 return false;
4272 }
Michael Kruse436c9062016-04-08 16:20:08 +00004273 if (SrcTy->isPointerTy() && DstTy->isPointerTy() &&
4274 DL->getTypeAllocSize(SrcTy->getPointerElementType()) ==
4275 DL->getTypeAllocSize(DstTy->getPointerElementType()))
Michael Kruse37d136e2016-02-26 16:08:24 +00004276 Address = Src;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00004277 }
Michael Kruse37d136e2016-02-26 16:08:24 +00004278
4279 auto *GEP = dyn_cast<GetElementPtrInst>(Address);
4280 if (!GEP)
4281 return false;
4282
4283 std::vector<const SCEV *> Subscripts;
4284 std::vector<int> Sizes;
4285 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
4286 auto *BasePtr = GEP->getOperand(0);
4287
Tobias Grosser535afd82016-04-05 06:23:45 +00004288 if (auto *BasePtrCast = dyn_cast<BitCastInst>(BasePtr))
4289 BasePtr = BasePtrCast->getOperand(0);
4290
4291 // Check for identical base pointers to ensure that we do not miss index
4292 // offsets that have been added before this GEP is applied.
4293 if (BasePtr != BasePointer->getValue())
4294 return false;
4295
Michael Kruse37d136e2016-02-26 16:08:24 +00004296 std::vector<const SCEV *> SizesSCEV;
4297
4298 for (auto *Subscript : Subscripts) {
4299 InvariantLoadsSetTy AccessILS;
Johannes Doerfertec8a2172016-04-25 13:32:36 +00004300 if (!isAffineExpr(R, L, Subscript, *SE, &AccessILS))
Michael Kruse37d136e2016-02-26 16:08:24 +00004301 return false;
4302
4303 for (LoadInst *LInst : AccessILS)
4304 if (!ScopRIL.count(LInst))
4305 return false;
4306 }
4307
4308 if (Sizes.empty())
4309 return false;
4310
4311 for (auto V : Sizes)
4312 SizesSCEV.push_back(SE->getSCEV(
4313 ConstantInt::get(IntegerType::getInt64Ty(BasePtr->getContext()), V)));
4314
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004315 addArrayAccess(Inst, AccType, BasePointer->getValue(), ElementType, true,
Michael Kruse37d136e2016-02-26 16:08:24 +00004316 Subscripts, SizesSCEV, Val);
4317 return true;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004318}
4319
4320bool ScopInfo::buildAccessMultiDimParam(
4321 MemAccInst Inst, Loop *L, Region *R,
4322 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
Hongbin Zheng22623202016-02-15 00:20:58 +00004323 const InvariantLoadsSetTy &ScopRIL, const MapInsnToMemAcc &InsnToMemAcc) {
Michael Kruse37d136e2016-02-26 16:08:24 +00004324 if (!PollyDelinearize)
4325 return false;
4326
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004327 Value *Address = Inst.getPointerOperand();
4328 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004329 Type *ElementType = Val->getType();
4330 unsigned ElementSize = DL->getTypeAllocSize(ElementType);
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004331 enum MemoryAccess::AccessType AccType =
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004332 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004333
4334 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
4335 const SCEVUnknown *BasePointer =
4336 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
4337
4338 assert(BasePointer && "Could not find base pointer");
4339 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00004340
Michael Kruse7bf39442015-09-10 12:46:52 +00004341 auto AccItr = InsnToMemAcc.find(Inst);
Michael Kruse37d136e2016-02-26 16:08:24 +00004342 if (AccItr == InsnToMemAcc.end())
4343 return false;
Tobias Grosser5d51afe2016-02-02 16:46:45 +00004344
Michael Kruse37d136e2016-02-26 16:08:24 +00004345 std::vector<const SCEV *> Sizes(
4346 AccItr->second.Shape->DelinearizedSizes.begin(),
4347 AccItr->second.Shape->DelinearizedSizes.end());
4348 // Remove the element size. This information is already provided by the
4349 // ElementSize parameter. In case the element size of this access and the
4350 // element size used for delinearization differs the delinearization is
4351 // incorrect. Hence, we invalidate the scop.
4352 //
4353 // TODO: Handle delinearization with differing element sizes.
4354 auto DelinearizedSize =
4355 cast<SCEVConstant>(Sizes.back())->getAPInt().getSExtValue();
4356 Sizes.pop_back();
4357 if (ElementSize != DelinearizedSize)
4358 scop->invalidate(DELINEARIZATION, Inst->getDebugLoc());
4359
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004360 addArrayAccess(Inst, AccType, BasePointer->getValue(), ElementType, true,
Michael Kruse37d136e2016-02-26 16:08:24 +00004361 AccItr->second.DelinearizedSubscripts, Sizes, Val);
4362 return true;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004363}
4364
Johannes Doerfertcea61932016-02-21 19:13:19 +00004365bool ScopInfo::buildAccessMemIntrinsic(
4366 MemAccInst Inst, Loop *L, Region *R,
4367 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
4368 const InvariantLoadsSetTy &ScopRIL) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004369 auto *MemIntr = dyn_cast_or_null<MemIntrinsic>(Inst);
4370
4371 if (MemIntr == nullptr)
Johannes Doerfertcea61932016-02-21 19:13:19 +00004372 return false;
4373
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004374 auto *LengthVal = SE->getSCEVAtScope(MemIntr->getLength(), L);
Johannes Doerfertcea61932016-02-21 19:13:19 +00004375 assert(LengthVal);
4376
Johannes Doerferta7920982016-02-25 14:08:48 +00004377 // Check if the length val is actually affine or if we overapproximate it
4378 InvariantLoadsSetTy AccessILS;
Johannes Doerfertec8a2172016-04-25 13:32:36 +00004379 bool LengthIsAffine = isAffineExpr(R, L, LengthVal, *SE, &AccessILS);
Johannes Doerferta7920982016-02-25 14:08:48 +00004380 for (LoadInst *LInst : AccessILS)
4381 if (!ScopRIL.count(LInst))
4382 LengthIsAffine = false;
4383 if (!LengthIsAffine)
4384 LengthVal = nullptr;
4385
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004386 auto *DestPtrVal = MemIntr->getDest();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004387 assert(DestPtrVal);
Johannes Doerfert733ea342016-03-24 13:50:04 +00004388
Johannes Doerfertcea61932016-02-21 19:13:19 +00004389 auto *DestAccFunc = SE->getSCEVAtScope(DestPtrVal, L);
4390 assert(DestAccFunc);
Johannes Doerfert733ea342016-03-24 13:50:04 +00004391 // Ignore accesses to "NULL".
4392 // TODO: We could use this to optimize the region further, e.g., intersect
4393 // the context with
4394 // isl_set_complement(isl_set_params(getDomain()))
4395 // as we know it would be undefined to execute this instruction anyway.
4396 if (DestAccFunc->isZero())
4397 return true;
4398
Johannes Doerfertcea61932016-02-21 19:13:19 +00004399 auto *DestPtrSCEV = dyn_cast<SCEVUnknown>(SE->getPointerBase(DestAccFunc));
4400 assert(DestPtrSCEV);
4401 DestAccFunc = SE->getMinusSCEV(DestAccFunc, DestPtrSCEV);
4402 addArrayAccess(Inst, MemoryAccess::MUST_WRITE, DestPtrSCEV->getValue(),
4403 IntegerType::getInt8Ty(DestPtrVal->getContext()), false,
4404 {DestAccFunc, LengthVal}, {}, Inst.getValueOperand());
4405
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004406 auto *MemTrans = dyn_cast<MemTransferInst>(MemIntr);
4407 if (!MemTrans)
Johannes Doerfertcea61932016-02-21 19:13:19 +00004408 return true;
4409
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004410 auto *SrcPtrVal = MemTrans->getSource();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004411 assert(SrcPtrVal);
Johannes Doerfert733ea342016-03-24 13:50:04 +00004412
Johannes Doerfertcea61932016-02-21 19:13:19 +00004413 auto *SrcAccFunc = SE->getSCEVAtScope(SrcPtrVal, L);
4414 assert(SrcAccFunc);
Johannes Doerfert733ea342016-03-24 13:50:04 +00004415 // Ignore accesses to "NULL".
4416 // TODO: See above TODO
4417 if (SrcAccFunc->isZero())
4418 return true;
4419
Johannes Doerfertcea61932016-02-21 19:13:19 +00004420 auto *SrcPtrSCEV = dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccFunc));
4421 assert(SrcPtrSCEV);
4422 SrcAccFunc = SE->getMinusSCEV(SrcAccFunc, SrcPtrSCEV);
4423 addArrayAccess(Inst, MemoryAccess::READ, SrcPtrSCEV->getValue(),
4424 IntegerType::getInt8Ty(SrcPtrVal->getContext()), false,
4425 {SrcAccFunc, LengthVal}, {}, Inst.getValueOperand());
4426
4427 return true;
4428}
4429
Johannes Doerferta7920982016-02-25 14:08:48 +00004430bool ScopInfo::buildAccessCallInst(
4431 MemAccInst Inst, Loop *L, Region *R,
4432 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
4433 const InvariantLoadsSetTy &ScopRIL) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004434 auto *CI = dyn_cast_or_null<CallInst>(Inst);
4435
4436 if (CI == nullptr)
Johannes Doerferta7920982016-02-25 14:08:48 +00004437 return false;
4438
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004439 if (CI->doesNotAccessMemory() || isIgnoredIntrinsic(CI))
Johannes Doerferta7920982016-02-25 14:08:48 +00004440 return true;
4441
4442 bool ReadOnly = false;
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004443 auto *AF = SE->getConstant(IntegerType::getInt64Ty(CI->getContext()), 0);
4444 auto *CalledFunction = CI->getCalledFunction();
Johannes Doerferta7920982016-02-25 14:08:48 +00004445 switch (AA->getModRefBehavior(CalledFunction)) {
4446 case llvm::FMRB_UnknownModRefBehavior:
4447 llvm_unreachable("Unknown mod ref behaviour cannot be represented.");
4448 case llvm::FMRB_DoesNotAccessMemory:
4449 return true;
4450 case llvm::FMRB_OnlyReadsMemory:
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004451 GlobalReads.push_back(CI);
Johannes Doerferta7920982016-02-25 14:08:48 +00004452 return true;
4453 case llvm::FMRB_OnlyReadsArgumentPointees:
4454 ReadOnly = true;
4455 // Fall through
4456 case llvm::FMRB_OnlyAccessesArgumentPointees:
4457 auto AccType = ReadOnly ? MemoryAccess::READ : MemoryAccess::MAY_WRITE;
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004458 for (const auto &Arg : CI->arg_operands()) {
Johannes Doerferta7920982016-02-25 14:08:48 +00004459 if (!Arg->getType()->isPointerTy())
4460 continue;
4461
4462 auto *ArgSCEV = SE->getSCEVAtScope(Arg, L);
4463 if (ArgSCEV->isZero())
4464 continue;
4465
4466 auto *ArgBasePtr = cast<SCEVUnknown>(SE->getPointerBase(ArgSCEV));
4467 addArrayAccess(Inst, AccType, ArgBasePtr->getValue(),
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004468 ArgBasePtr->getType(), false, {AF}, {}, CI);
Johannes Doerferta7920982016-02-25 14:08:48 +00004469 }
4470 return true;
4471 }
4472
4473 return true;
4474}
4475
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004476void ScopInfo::buildAccessSingleDim(
4477 MemAccInst Inst, Loop *L, Region *R,
4478 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
4479 const InvariantLoadsSetTy &ScopRIL) {
4480 Value *Address = Inst.getPointerOperand();
4481 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004482 Type *ElementType = Val->getType();
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004483 enum MemoryAccess::AccessType AccType =
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004484 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004485
4486 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
4487 const SCEVUnknown *BasePointer =
4488 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
4489
4490 assert(BasePointer && "Could not find base pointer");
4491 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
Michael Kruse7bf39442015-09-10 12:46:52 +00004492
4493 // Check if the access depends on a loop contained in a non-affine subregion.
4494 bool isVariantInNonAffineLoop = false;
4495 if (BoxedLoops) {
4496 SetVector<const Loop *> Loops;
4497 findLoops(AccessFunction, Loops);
4498 for (const Loop *L : Loops)
4499 if (BoxedLoops->count(L))
4500 isVariantInNonAffineLoop = true;
4501 }
4502
Johannes Doerfert09e36972015-10-07 20:17:36 +00004503 InvariantLoadsSetTy AccessILS;
Michael Kruse09eb4452016-03-03 22:10:47 +00004504 bool IsAffine = !isVariantInNonAffineLoop &&
Johannes Doerfertec8a2172016-04-25 13:32:36 +00004505 isAffineExpr(R, L, AccessFunction, *SE, &AccessILS);
Johannes Doerfert09e36972015-10-07 20:17:36 +00004506
4507 for (LoadInst *LInst : AccessILS)
4508 if (!ScopRIL.count(LInst))
4509 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00004510
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004511 if (!IsAffine && AccType == MemoryAccess::MUST_WRITE)
4512 AccType = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00004513
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004514 addArrayAccess(Inst, AccType, BasePointer->getValue(), ElementType, IsAffine,
Tobias Grosser5d51afe2016-02-02 16:46:45 +00004515 {AccessFunction}, {}, Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00004516}
4517
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004518void ScopInfo::buildMemoryAccess(
4519 MemAccInst Inst, Loop *L, Region *R,
4520 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
Hongbin Zheng22623202016-02-15 00:20:58 +00004521 const InvariantLoadsSetTy &ScopRIL, const MapInsnToMemAcc &InsnToMemAcc) {
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004522
Johannes Doerfertcea61932016-02-21 19:13:19 +00004523 if (buildAccessMemIntrinsic(Inst, L, R, BoxedLoops, ScopRIL))
4524 return;
4525
Johannes Doerferta7920982016-02-25 14:08:48 +00004526 if (buildAccessCallInst(Inst, L, R, BoxedLoops, ScopRIL))
4527 return;
4528
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004529 if (buildAccessMultiDimFixed(Inst, L, R, BoxedLoops, ScopRIL))
4530 return;
4531
Hongbin Zheng22623202016-02-15 00:20:58 +00004532 if (buildAccessMultiDimParam(Inst, L, R, BoxedLoops, ScopRIL, InsnToMemAcc))
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004533 return;
4534
4535 buildAccessSingleDim(Inst, L, R, BoxedLoops, ScopRIL);
4536}
4537
Hongbin Zheng22623202016-02-15 00:20:58 +00004538void ScopInfo::buildAccessFunctions(Region &R, Region &SR,
4539 const MapInsnToMemAcc &InsnToMemAcc) {
Michael Kruse7bf39442015-09-10 12:46:52 +00004540
4541 if (SD->isNonAffineSubRegion(&SR, &R)) {
4542 for (BasicBlock *BB : SR.blocks())
Hongbin Zheng22623202016-02-15 00:20:58 +00004543 buildAccessFunctions(R, *BB, InsnToMemAcc, &SR);
Michael Kruse7bf39442015-09-10 12:46:52 +00004544 return;
4545 }
4546
4547 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
4548 if (I->isSubRegion())
Hongbin Zheng22623202016-02-15 00:20:58 +00004549 buildAccessFunctions(R, *I->getNodeAs<Region>(), InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00004550 else
Hongbin Zheng22623202016-02-15 00:20:58 +00004551 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>(), InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00004552}
4553
Johannes Doerferta8781032016-02-02 14:14:40 +00004554void ScopInfo::buildStmts(Region &R, Region &SR) {
Michael Krusecac948e2015-10-02 13:53:07 +00004555
Johannes Doerferta8781032016-02-02 14:14:40 +00004556 if (SD->isNonAffineSubRegion(&SR, &R)) {
Michael Krusecac948e2015-10-02 13:53:07 +00004557 scop->addScopStmt(nullptr, &SR);
4558 return;
4559 }
4560
4561 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
4562 if (I->isSubRegion())
Johannes Doerferta8781032016-02-02 14:14:40 +00004563 buildStmts(R, *I->getNodeAs<Region>());
Michael Krusecac948e2015-10-02 13:53:07 +00004564 else
4565 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
4566}
4567
Michael Krused868b5d2015-09-10 15:25:24 +00004568void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
Hongbin Zheng22623202016-02-15 00:20:58 +00004569 const MapInsnToMemAcc &InsnToMemAcc,
Michael Krused868b5d2015-09-10 15:25:24 +00004570 Region *NonAffineSubRegion,
4571 bool IsExitBlock) {
Tobias Grosser910cf262015-11-11 20:15:49 +00004572 // We do not build access functions for error blocks, as they may contain
4573 // instructions we can not model.
Johannes Doerfertc36d39b2016-02-02 14:14:20 +00004574 if (isErrorBlock(BB, R, *LI, *DT) && !IsExitBlock)
Tobias Grosser910cf262015-11-11 20:15:49 +00004575 return;
4576
Michael Kruse7bf39442015-09-10 12:46:52 +00004577 Loop *L = LI->getLoopFor(&BB);
4578
4579 // The set of loops contained in non-affine subregions that are part of R.
4580 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
4581
Johannes Doerfert09e36972015-10-07 20:17:36 +00004582 // The set of loads that are required to be invariant.
4583 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
4584
Michael Kruse2e02d562016-02-06 09:19:40 +00004585 for (Instruction &Inst : BB) {
4586 PHINode *PHI = dyn_cast<PHINode>(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00004587 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00004588 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00004589
4590 // For the exit block we stop modeling after the last PHI node.
4591 if (!PHI && IsExitBlock)
4592 break;
4593
Johannes Doerfert09e36972015-10-07 20:17:36 +00004594 // TODO: At this point we only know that elements of ScopRIL have to be
4595 // invariant and will be hoisted for the SCoP to be processed. Though,
4596 // there might be other invariant accesses that will be hoisted and
4597 // that would allow to make a non-affine access affine.
Michael Kruse70131d32016-01-27 17:09:17 +00004598 if (auto MemInst = MemAccInst::dyn_cast(Inst))
Hongbin Zheng22623202016-02-15 00:20:58 +00004599 buildMemoryAccess(MemInst, L, &R, BoxedLoops, ScopRIL, InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00004600
Michael Kruse2e02d562016-02-06 09:19:40 +00004601 if (isIgnoredIntrinsic(&Inst))
Michael Kruse7bf39442015-09-10 12:46:52 +00004602 continue;
4603
Tobias Grosser0904c692016-03-16 23:33:54 +00004604 // PHI nodes have already been modeled above and TerminatorInsts that are
4605 // not part of a non-affine subregion are fully modeled and regenerated
4606 // from the polyhedral domains. Hence, they do not need to be modeled as
4607 // explicit data dependences.
4608 if (!PHI && (!isa<TerminatorInst>(&Inst) || NonAffineSubRegion))
Michael Kruse2e02d562016-02-06 09:19:40 +00004609 buildScalarDependences(&Inst);
Tobias Grosser0904c692016-03-16 23:33:54 +00004610
Michael Kruse2e02d562016-02-06 09:19:40 +00004611 if (!IsExitBlock)
4612 buildEscapingDependences(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00004613 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00004614}
Michael Kruse7bf39442015-09-10 12:46:52 +00004615
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004616MemoryAccess *ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004617 MemoryAccess::AccessType AccType,
4618 Value *BaseAddress, Type *ElementType,
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004619 bool Affine, Value *AccessValue,
4620 ArrayRef<const SCEV *> Subscripts,
4621 ArrayRef<const SCEV *> Sizes,
4622 ScopArrayInfo::MemoryKind Kind) {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004623 ScopStmt *Stmt = scop->getStmtFor(BB);
Michael Krusecac948e2015-10-02 13:53:07 +00004624
4625 // Do not create a memory access for anything not in the SCoP. It would be
4626 // ignored anyway.
4627 if (!Stmt)
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004628 return nullptr;
Michael Krusecac948e2015-10-02 13:53:07 +00004629
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00004630 AccFuncSetType &AccList = scop->getOrCreateAccessFunctions(BB);
Michael Krusee2bccbb2015-09-18 19:59:43 +00004631 Value *BaseAddr = BaseAddress;
4632 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
4633
Tobias Grosserf4f68702015-12-14 15:05:37 +00004634 bool isKnownMustAccess = false;
4635
4636 // Accesses in single-basic block statements are always excuted.
4637 if (Stmt->isBlockStmt())
4638 isKnownMustAccess = true;
4639
4640 if (Stmt->isRegionStmt()) {
4641 // Accesses that dominate the exit block of a non-affine region are always
4642 // executed. In non-affine regions there may exist MK_Values that do not
4643 // dominate the exit. MK_Values will always dominate the exit and MK_PHIs
4644 // only if there is at most one PHI_WRITE in the non-affine region.
4645 if (DT->dominates(BB, Stmt->getRegion()->getExit()))
4646 isKnownMustAccess = true;
4647 }
4648
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004649 // Non-affine PHI writes do not "happen" at a particular instruction, but
4650 // after exiting the statement. Therefore they are guaranteed execute and
4651 // overwrite the old value.
4652 if (Kind == ScopArrayInfo::MK_PHI || Kind == ScopArrayInfo::MK_ExitPHI)
4653 isKnownMustAccess = true;
4654
Johannes Doerfertcea61932016-02-21 19:13:19 +00004655 if (!isKnownMustAccess && AccType == MemoryAccess::MUST_WRITE)
4656 AccType = MemoryAccess::MAY_WRITE;
Michael Krusecac948e2015-10-02 13:53:07 +00004657
Johannes Doerfertcea61932016-02-21 19:13:19 +00004658 AccList.emplace_back(Stmt, Inst, AccType, BaseAddress, ElementType, Affine,
Tobias Grossera535dff2015-12-13 19:59:01 +00004659 Subscripts, Sizes, AccessValue, Kind, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00004660 Stmt->addAccess(&AccList.back());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004661 return &AccList.back();
Michael Kruse7bf39442015-09-10 12:46:52 +00004662}
4663
Michael Kruse70131d32016-01-27 17:09:17 +00004664void ScopInfo::addArrayAccess(MemAccInst MemAccInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004665 MemoryAccess::AccessType AccType,
4666 Value *BaseAddress, Type *ElementType,
4667 bool IsAffine, ArrayRef<const SCEV *> Subscripts,
Tobias Grossera535dff2015-12-13 19:59:01 +00004668 ArrayRef<const SCEV *> Sizes,
4669 Value *AccessValue) {
Johannes Doerferta7920982016-02-25 14:08:48 +00004670 ArrayBasePointers.insert(BaseAddress);
Hongbin Zhengf3d66122016-02-26 09:47:11 +00004671 addMemoryAccess(MemAccInst->getParent(), MemAccInst, AccType, BaseAddress,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004672 ElementType, IsAffine, AccessValue, Subscripts, Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00004673 ScopArrayInfo::MK_Array);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004674}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004675
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004676void ScopInfo::ensureValueWrite(Instruction *Inst) {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004677 ScopStmt *Stmt = scop->getStmtFor(Inst);
Michael Kruse436db622016-01-26 13:33:10 +00004678
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004679 // Inst not defined within this SCoP.
Michael Kruse436db622016-01-26 13:33:10 +00004680 if (!Stmt)
4681 return;
4682
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004683 // Do not process further if the instruction is already written.
4684 if (Stmt->lookupValueWriteOf(Inst))
Michael Kruse436db622016-01-26 13:33:10 +00004685 return;
4686
Johannes Doerfertcea61932016-02-21 19:13:19 +00004687 addMemoryAccess(Inst->getParent(), Inst, MemoryAccess::MUST_WRITE, Inst,
4688 Inst->getType(), true, Inst, ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004689 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004690}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004691
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004692void ScopInfo::ensureValueRead(Value *V, BasicBlock *UserBB) {
Michael Krusefd463082016-01-27 22:51:56 +00004693
Michael Kruse2e02d562016-02-06 09:19:40 +00004694 // There cannot be an "access" for literal constants. BasicBlock references
4695 // (jump destinations) also never change.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004696 if ((isa<Constant>(V) && !isa<GlobalVariable>(V)) || isa<BasicBlock>(V))
Michael Kruse2e02d562016-02-06 09:19:40 +00004697 return;
4698
Michael Krusefd463082016-01-27 22:51:56 +00004699 // If the instruction can be synthesized and the user is in the region we do
4700 // not need to add a value dependences.
4701 Region &ScopRegion = scop->getRegion();
Michael Krusec7e0d9c2016-03-01 21:44:06 +00004702 auto *Scope = LI->getLoopFor(UserBB);
4703 if (canSynthesize(V, LI, SE, &ScopRegion, Scope))
Michael Krusefd463082016-01-27 22:51:56 +00004704 return;
4705
Michael Kruse2e02d562016-02-06 09:19:40 +00004706 // Do not build scalar dependences for required invariant loads as we will
4707 // hoist them later on anyway or drop the SCoP if we cannot.
Johannes Doerferta90943d2016-02-21 16:37:25 +00004708 auto *ScopRIL = SD->getRequiredInvariantLoads(&ScopRegion);
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004709 if (ScopRIL->count(dyn_cast<LoadInst>(V)))
Michael Kruse2e02d562016-02-06 09:19:40 +00004710 return;
4711
4712 // Determine the ScopStmt containing the value's definition and use. There is
4713 // no defining ScopStmt if the value is a function argument, a global value,
4714 // or defined outside the SCoP.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004715 Instruction *ValueInst = dyn_cast<Instruction>(V);
Michael Kruse6f7721f2016-02-24 22:08:19 +00004716 ScopStmt *ValueStmt = ValueInst ? scop->getStmtFor(ValueInst) : nullptr;
Michael Kruse2e02d562016-02-06 09:19:40 +00004717
Michael Kruse6f7721f2016-02-24 22:08:19 +00004718 ScopStmt *UserStmt = scop->getStmtFor(UserBB);
Michael Krusead28e5a2016-01-26 13:33:15 +00004719
4720 // We do not model uses outside the scop.
4721 if (!UserStmt)
4722 return;
4723
Michael Kruse2e02d562016-02-06 09:19:40 +00004724 // Add MemoryAccess for invariant values only if requested.
4725 if (!ModelReadOnlyScalars && !ValueStmt)
4726 return;
4727
4728 // Ignore use-def chains within the same ScopStmt.
4729 if (ValueStmt == UserStmt)
4730 return;
4731
Michael Krusead28e5a2016-01-26 13:33:15 +00004732 // Do not create another MemoryAccess for reloading the value if one already
4733 // exists.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004734 if (UserStmt->lookupValueReadOf(V))
Michael Krusead28e5a2016-01-26 13:33:15 +00004735 return;
4736
Johannes Doerfert2075b5d2016-04-03 11:16:00 +00004737 // For exit PHIs use the MK_ExitPHI MemoryKind not MK_Value.
4738 ScopArrayInfo::MemoryKind Kind = ScopArrayInfo::MK_Value;
4739 if (!ValueStmt && isa<PHINode>(V))
4740 Kind = ScopArrayInfo::MK_ExitPHI;
4741
Johannes Doerfertcea61932016-02-21 19:13:19 +00004742 addMemoryAccess(UserBB, nullptr, MemoryAccess::READ, V, V->getType(), true, V,
Johannes Doerfert2075b5d2016-04-03 11:16:00 +00004743 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(), Kind);
Michael Kruse2e02d562016-02-06 09:19:40 +00004744 if (ValueInst)
4745 ensureValueWrite(ValueInst);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004746}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004747
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004748void ScopInfo::ensurePHIWrite(PHINode *PHI, BasicBlock *IncomingBlock,
4749 Value *IncomingValue, bool IsExitBlock) {
Johannes Doerfert57c5f0b2016-04-05 13:44:21 +00004750 // As the incoming block might turn out to be an error statement ensure we
4751 // will create an exit PHI SAI object. It is needed during code generation
4752 // and would be created later anyway.
4753 if (IsExitBlock)
4754 scop->getOrCreateScopArrayInfo(PHI, PHI->getType(), {},
4755 ScopArrayInfo::MK_ExitPHI);
4756
Michael Kruse6f7721f2016-02-24 22:08:19 +00004757 ScopStmt *IncomingStmt = scop->getStmtFor(IncomingBlock);
Michael Kruse2e02d562016-02-06 09:19:40 +00004758 if (!IncomingStmt)
4759 return;
4760
4761 // Take care for the incoming value being available in the incoming block.
4762 // This must be done before the check for multiple PHI writes because multiple
4763 // exiting edges from subregion each can be the effective written value of the
4764 // subregion. As such, all of them must be made available in the subregion
4765 // statement.
4766 ensureValueRead(IncomingValue, IncomingBlock);
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004767
4768 // Do not add more than one MemoryAccess per PHINode and ScopStmt.
4769 if (MemoryAccess *Acc = IncomingStmt->lookupPHIWriteOf(PHI)) {
4770 assert(Acc->getAccessInstruction() == PHI);
4771 Acc->addIncoming(IncomingBlock, IncomingValue);
4772 return;
4773 }
4774
4775 MemoryAccess *Acc = addMemoryAccess(
Michael Kruse375cb5f2016-02-24 22:08:24 +00004776 IncomingStmt->getEntryBlock(), PHI, MemoryAccess::MUST_WRITE, PHI,
4777 PHI->getType(), true, PHI, ArrayRef<const SCEV *>(),
4778 ArrayRef<const SCEV *>(),
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004779 IsExitBlock ? ScopArrayInfo::MK_ExitPHI : ScopArrayInfo::MK_PHI);
4780 assert(Acc);
4781 Acc->addIncoming(IncomingBlock, IncomingValue);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004782}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004783
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004784void ScopInfo::addPHIReadAccess(PHINode *PHI) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00004785 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI,
4786 PHI->getType(), true, PHI, ArrayRef<const SCEV *>(),
4787 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004788}
4789
Michael Krusedaf66942015-12-13 22:10:37 +00004790void ScopInfo::buildScop(Region &R, AssumptionCache &AC) {
Michael Kruse9d080092015-09-11 21:41:48 +00004791 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Michael Kruse09eb4452016-03-03 22:10:47 +00004792 scop.reset(new Scop(R, *SE, *LI, MaxLoopDepth));
Michael Kruse7bf39442015-09-10 12:46:52 +00004793
Johannes Doerferta8781032016-02-02 14:14:40 +00004794 buildStmts(R, R);
Hongbin Zheng22623202016-02-15 00:20:58 +00004795 buildAccessFunctions(R, R, *SD->getInsnToMemAccMap(&R));
Michael Kruse7bf39442015-09-10 12:46:52 +00004796
4797 // In case the region does not have an exiting block we will later (during
4798 // code generation) split the exit block. This will move potential PHI nodes
4799 // from the current exit block into the new region exiting block. Hence, PHI
4800 // nodes that are at this point not part of the region will be.
4801 // To handle these PHI nodes later we will now model their operands as scalar
4802 // accesses. Note that we do not model anything in the exit block if we have
4803 // an exiting block in the region, as there will not be any splitting later.
4804 if (!R.getExitingBlock())
Hongbin Zheng22623202016-02-15 00:20:58 +00004805 buildAccessFunctions(R, *R.getExit(), *SD->getInsnToMemAccMap(&R), nullptr,
4806 /* IsExitBlock */ true);
Michael Kruse7bf39442015-09-10 12:46:52 +00004807
Johannes Doerferta7920982016-02-25 14:08:48 +00004808 // Create memory accesses for global reads since all arrays are now known.
4809 auto *AF = SE->getConstant(IntegerType::getInt64Ty(SE->getContext()), 0);
4810 for (auto *GlobalRead : GlobalReads)
4811 for (auto *BP : ArrayBasePointers)
4812 addArrayAccess(MemAccInst(GlobalRead), MemoryAccess::READ, BP,
4813 BP->getType(), false, {AF}, {}, GlobalRead);
4814
Hongbin Zheng192f69a2016-02-13 15:12:54 +00004815 scop->init(*AA, AC, *SD, *DT, *LI);
Michael Kruse7bf39442015-09-10 12:46:52 +00004816}
4817
Michael Krused868b5d2015-09-10 15:25:24 +00004818void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00004819 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00004820 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00004821 return;
4822 }
4823
Michael Kruse9d080092015-09-11 21:41:48 +00004824 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00004825}
4826
Hongbin Zhengfec32802016-02-13 15:13:02 +00004827void ScopInfo::clear() { scop.reset(); }
Michael Kruse7bf39442015-09-10 12:46:52 +00004828
4829//===----------------------------------------------------------------------===//
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004830ScopInfo::ScopInfo() : RegionPass(ID) {}
Tobias Grosserb76f38532011-08-20 11:11:25 +00004831
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004832ScopInfo::~ScopInfo() { clear(); }
Tobias Grosserb76f38532011-08-20 11:11:25 +00004833
Tobias Grosser75805372011-04-29 06:27:02 +00004834void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00004835 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00004836 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00004837 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00004838 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4839 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004840 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004841 AU.addRequired<AssumptionCacheTracker>();
Tobias Grosser75805372011-04-29 06:27:02 +00004842 AU.setPreservesAll();
4843}
4844
4845bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00004846 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00004847
Michael Krused868b5d2015-09-10 15:25:24 +00004848 if (!SD->isMaxRegionInScop(*R))
4849 return false;
4850
4851 Function *F = R->getEntry()->getParent();
4852 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4853 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4854 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Johannes Doerferta1f291e2016-02-02 14:15:13 +00004855 DL = &F->getParent()->getDataLayout();
Michael Krusedaf66942015-12-13 22:10:37 +00004856 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004857 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krused868b5d2015-09-10 15:25:24 +00004858
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004859 DebugLoc Beg, End;
4860 getDebugLocations(R, Beg, End);
4861 std::string Msg = "SCoP begins here.";
4862 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg);
4863
Michael Krusedaf66942015-12-13 22:10:37 +00004864 buildScop(*R, AC);
Tobias Grosser75805372011-04-29 06:27:02 +00004865
Tobias Grosserd6a50b32015-05-30 06:26:21 +00004866 DEBUG(scop->print(dbgs()));
4867
Michael Kruseafe06702015-10-02 16:33:27 +00004868 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004869 Msg = "SCoP ends here but was dismissed.";
Hongbin Zhengfec32802016-02-13 15:13:02 +00004870 scop.reset();
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004871 } else {
4872 Msg = "SCoP ends here.";
4873 ++ScopFound;
4874 if (scop->getMaxLoopDepth() > 0)
4875 ++RichScopFound;
Johannes Doerfert43788c52015-08-20 05:58:56 +00004876 }
4877
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004878 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg);
4879
Tobias Grosser75805372011-04-29 06:27:02 +00004880 return false;
4881}
4882
4883char ScopInfo::ID = 0;
4884
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004885Pass *polly::createScopInfoPass() { return new ScopInfo(); }
4886
Tobias Grosser73600b82011-10-08 00:30:40 +00004887INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
4888 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004889 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004890INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004891INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004892INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004893INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004894INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004895INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004896INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00004897INITIALIZE_PASS_END(ScopInfo, "polly-scops",
4898 "Polly - Create polyhedral description of Scops", false,
4899 false)