blob: 6ad607e62ac3a3dc48227f714737553fad26e141 [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
Michael Kruse7bf39442015-09-10 12:46:52 +0000108//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000109
Michael Kruse046dde42015-08-10 13:01:57 +0000110// Create a sequence of two schedules. Either argument may be null and is
111// interpreted as the empty schedule. Can also return null if both schedules are
112// empty.
113static __isl_give isl_schedule *
114combineInSequence(__isl_take isl_schedule *Prev,
115 __isl_take isl_schedule *Succ) {
116 if (!Prev)
117 return Succ;
118 if (!Succ)
119 return Prev;
120
121 return isl_schedule_sequence(Prev, Succ);
122}
123
Johannes Doerferte7044942015-02-24 11:58:30 +0000124static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
125 const ConstantRange &Range,
126 int dim,
127 enum isl_dim_type type) {
128 isl_val *V;
129 isl_ctx *ctx = isl_set_get_ctx(S);
130
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000131 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
132 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000133 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000134 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
135
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000136 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000137 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000138 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000139 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000140 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
141
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000142 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000143 return isl_set_union(SLB, SUB);
144 else
145 return isl_set_intersect(SLB, SUB);
146}
147
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000148static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
149 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
150 if (!BasePtrLI)
151 return nullptr;
152
153 if (!S->getRegion().contains(BasePtrLI))
154 return nullptr;
155
156 ScalarEvolution &SE = *S->getSE();
157
158 auto *OriginBaseSCEV =
159 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
160 if (!OriginBaseSCEV)
161 return nullptr;
162
163 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
164 if (!OriginBaseSCEVUnknown)
165 return nullptr;
166
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000167 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grossera535dff2015-12-13 19:59:01 +0000168 ScopArrayInfo::MK_Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000169}
170
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000171ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grossera535dff2015-12-13 19:59:01 +0000172 ArrayRef<const SCEV *> Sizes, enum MemoryKind Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000173 const DataLayout &DL, Scop *S)
174 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000175 std::string BasePtrName =
Tobias Grossera535dff2015-12-13 19:59:01 +0000176 getIslCompatibleName("MemRef_", BasePtr, Kind == MK_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000177 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000178
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000179 updateSizes(Sizes);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000180 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
181 if (BasePtrOriginSAI)
182 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000183}
184
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000185__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000186 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000187 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
188 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
189 return Space;
190}
191
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000192void ScopArrayInfo::updateElementType(Type *NewElementType) {
193 if (NewElementType == ElementType)
194 return;
195
Tobias Grosserd840fc72016-02-04 13:18:42 +0000196 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
197 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
198
Johannes Doerferta7920982016-02-25 14:08:48 +0000199 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000200 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000201
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000202 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
203 ElementType = NewElementType;
204 } else {
205 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
206 ElementType = IntegerType::get(ElementType->getContext(), GCD);
207 }
208}
209
210bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000211 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
212 int ExtraDimsNew = NewSizes.size() - SharedDims;
213 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Tobias Grosser8286b832015-11-02 11:29:32 +0000214 for (int i = 0; i < SharedDims; i++)
215 if (NewSizes[i + ExtraDimsNew] != DimensionSizes[i + ExtraDimsOld])
216 return false;
217
218 if (DimensionSizes.size() >= NewSizes.size())
219 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000220
221 DimensionSizes.clear();
222 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
223 NewSizes.end());
224 for (isl_pw_aff *Size : DimensionSizesPw)
225 isl_pw_aff_free(Size);
226 DimensionSizesPw.clear();
227 for (const SCEV *Expr : DimensionSizes) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000228 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000229 DimensionSizesPw.push_back(Size);
230 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000231 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000232}
233
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000234ScopArrayInfo::~ScopArrayInfo() {
235 isl_id_free(Id);
236 for (isl_pw_aff *Size : DimensionSizesPw)
237 isl_pw_aff_free(Size);
238}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000239
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000240std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
241
242int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000243 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000244}
245
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000246__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
247 return isl_id_copy(Id);
248}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000249
250void ScopArrayInfo::dump() const { print(errs()); }
251
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000252void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000253 OS.indent(8) << *getElementType() << " " << getName();
254 if (getNumberOfDimensions() > 0)
255 OS << "[*]";
Tobias Grosser26253842015-11-10 14:24:21 +0000256 for (unsigned u = 1; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000257 OS << "[";
258
Tobias Grosser26253842015-11-10 14:24:21 +0000259 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000260 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000261 OS << " " << Size << " ";
262 isl_pw_aff_free(Size);
263 } else {
264 OS << *getDimensionSize(u);
265 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000266
267 OS << "]";
268 }
269
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000270 OS << ";";
271
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000272 if (BasePtrOriginSAI)
273 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
274
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000275 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000276}
277
278const ScopArrayInfo *
279ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
280 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
281 assert(Id && "Output dimension didn't have an ID");
282 return getFromId(Id);
283}
284
285const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
286 void *User = isl_id_get_user(Id);
287 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
288 isl_id_free(Id);
289 return SAI;
290}
291
Michael Kruse3b425ff2016-04-11 14:34:08 +0000292void MemoryAccess::wrapConstantDimensions() {
293 auto *SAI = getScopArrayInfo();
294 auto *ArraySpace = SAI->getSpace();
295 auto *Ctx = isl_space_get_ctx(ArraySpace);
296 unsigned DimsArray = SAI->getNumberOfDimensions();
297
298 auto *DivModAff = isl_multi_aff_identity(isl_space_map_from_domain_and_range(
299 isl_space_copy(ArraySpace), isl_space_copy(ArraySpace)));
300 auto *LArraySpace = isl_local_space_from_space(ArraySpace);
301
302 // Begin with last dimension, to iteratively carry into higher dimensions.
303 for (int i = DimsArray - 1; i > 0; i--) {
304 auto *DimSize = SAI->getDimensionSize(i);
305 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
306
307 // This transformation is not applicable to dimensions with dynamic size.
308 if (!DimSizeCst)
309 continue;
310
311 auto *DimSizeVal = isl_valFromAPInt(Ctx, DimSizeCst->getAPInt(), false);
312 auto *Var = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
313 isl_dim_set, i);
314 auto *PrevVar = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
315 isl_dim_set, i - 1);
316
317 // Compute: index % size
318 // Modulo must apply in the divide of the previous iteration, if any.
319 auto *Modulo = isl_aff_copy(Var);
320 Modulo = isl_aff_mod_val(Modulo, isl_val_copy(DimSizeVal));
321 Modulo = isl_aff_pullback_multi_aff(Modulo, isl_multi_aff_copy(DivModAff));
322
323 // Compute: floor(index / size)
324 auto *Divide = Var;
325 Divide = isl_aff_div(
326 Divide,
327 isl_aff_val_on_domain(isl_local_space_copy(LArraySpace), DimSizeVal));
328 Divide = isl_aff_floor(Divide);
329 Divide = isl_aff_add(Divide, PrevVar);
330 Divide = isl_aff_pullback_multi_aff(Divide, isl_multi_aff_copy(DivModAff));
331
332 // Apply Modulo and Divide.
333 DivModAff = isl_multi_aff_set_aff(DivModAff, i, Modulo);
334 DivModAff = isl_multi_aff_set_aff(DivModAff, i - 1, Divide);
335 }
336
337 // Apply all modulo/divides on the accesses.
338 AccessRelation =
339 isl_map_apply_range(AccessRelation, isl_map_from_multi_aff(DivModAff));
340 AccessRelation = isl_map_detect_equalities(AccessRelation);
341 isl_local_space_free(LArraySpace);
342}
343
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000344void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000345 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000346 auto *ArraySpace = SAI->getSpace();
347 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000348 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000349
350 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
351 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
352 auto DimsMissing = DimsArray - DimsAccess;
353
Michael Kruse375cb5f2016-02-24 22:08:24 +0000354 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000355 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000356 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000357 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000358
Johannes Doerferta90943d2016-02-21 16:37:25 +0000359 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000360 isl_set_universe(AccessSpace),
361 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000362
363 for (unsigned i = 0; i < DimsMissing; i++)
364 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
365
366 for (unsigned i = DimsMissing; i < DimsArray; i++)
367 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
368
369 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000370
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000371 // For the non delinearized arrays, divide the access function of the last
372 // subscript by the size of the elements in the array.
373 //
374 // A stride one array access in C expressed as A[i] is expressed in
375 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
376 // two subsequent values of 'i' index two values that are stored next to
377 // each other in memory. By this division we make this characteristic
378 // obvious again. If the base pointer was accessed with offsets not divisible
379 // by the accesses element size, we will have choosen a smaller ArrayElemSize
380 // that divides the offsets of all accesses to this base pointer.
381 if (DimsAccess == 1) {
382 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
383 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
384 }
385
Michael Kruse3b425ff2016-04-11 14:34:08 +0000386 // We currently do this only if we added at least one dimension, which means
387 // some dimension's indices have not been specified, an indicator that some
388 // index values have been added together.
389 // TODO: Investigate general usefulness; Effect on unit tests is to make index
390 // expressions more complicated.
391 if (DimsMissing)
392 wrapConstantDimensions();
393
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000394 if (!isAffine())
395 computeBoundsOnAccessRelation(ArrayElemSize);
396
Tobias Grosserd840fc72016-02-04 13:18:42 +0000397 // Introduce multi-element accesses in case the type loaded by this memory
398 // access is larger than the canonical element type of the array.
399 //
400 // An access ((float *)A)[i] to an array char *A is modeled as
401 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000402 if (ElemBytes > ArrayElemSize) {
403 assert(ElemBytes % ArrayElemSize == 0 &&
404 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000405 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000406 isl_set_universe(isl_space_copy(ArraySpace)),
407 isl_set_universe(isl_space_copy(ArraySpace)));
408 for (unsigned i = 0; i < DimsArray - 1; i++)
409 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
410
Tobias Grosserd840fc72016-02-04 13:18:42 +0000411 isl_constraint *C;
412 isl_local_space *LS;
413
414 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000415 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
416
417 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
418 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000419 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000420 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
421 Map = isl_map_add_constraint(Map, C);
422
423 C = isl_constraint_alloc_inequality(LS);
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 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
427 Map = isl_map_add_constraint(Map, C);
428 AccessRelation = isl_map_apply_range(AccessRelation, Map);
429 }
430
431 isl_space_free(ArraySpace);
432
Roman Gareev10595a12016-01-08 14:01:59 +0000433 assumeNoOutOfBound();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000434}
435
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000436const std::string
437MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
438 switch (RT) {
439 case MemoryAccess::RT_NONE:
440 llvm_unreachable("Requested a reduction operator string for a memory "
441 "access which isn't a reduction");
442 case MemoryAccess::RT_ADD:
443 return "+";
444 case MemoryAccess::RT_MUL:
445 return "*";
446 case MemoryAccess::RT_BOR:
447 return "|";
448 case MemoryAccess::RT_BXOR:
449 return "^";
450 case MemoryAccess::RT_BAND:
451 return "&";
452 }
453 llvm_unreachable("Unknown reduction type");
454 return "";
455}
456
Johannes Doerfertf6183392014-07-01 20:52:51 +0000457/// @brief Return the reduction type for a given binary operator
458static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
459 const Instruction *Load) {
460 if (!BinOp)
461 return MemoryAccess::RT_NONE;
462 switch (BinOp->getOpcode()) {
463 case Instruction::FAdd:
464 if (!BinOp->hasUnsafeAlgebra())
465 return MemoryAccess::RT_NONE;
466 // Fall through
467 case Instruction::Add:
468 return MemoryAccess::RT_ADD;
469 case Instruction::Or:
470 return MemoryAccess::RT_BOR;
471 case Instruction::Xor:
472 return MemoryAccess::RT_BXOR;
473 case Instruction::And:
474 return MemoryAccess::RT_BAND;
475 case Instruction::FMul:
476 if (!BinOp->hasUnsafeAlgebra())
477 return MemoryAccess::RT_NONE;
478 // Fall through
479 case Instruction::Mul:
480 if (DisableMultiplicativeReductions)
481 return MemoryAccess::RT_NONE;
482 return MemoryAccess::RT_MUL;
483 default:
484 return MemoryAccess::RT_NONE;
485 }
486}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000487
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000488/// @brief Derive the individual index expressions from a GEP instruction
489///
490/// This function optimistically assumes the GEP references into a fixed size
491/// array. If this is actually true, this function returns a list of array
492/// subscript expressions as SCEV as well as a list of integers describing
493/// the size of the individual array dimensions. Both lists have either equal
494/// length of the size list is one element shorter in case there is no known
495/// size available for the outermost array dimension.
496///
497/// @param GEP The GetElementPtr instruction to analyze.
498///
499/// @return A tuple with the subscript expressions and the dimension sizes.
500static std::tuple<std::vector<const SCEV *>, std::vector<int>>
501getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
502 std::vector<const SCEV *> Subscripts;
503 std::vector<int> Sizes;
504
505 Type *Ty = GEP->getPointerOperandType();
506
507 bool DroppedFirstDim = false;
508
Michael Kruse26ed65e2015-09-24 17:32:49 +0000509 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000510
511 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
512
513 if (i == 1) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000514 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000515 Ty = PtrTy->getElementType();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000516 } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000517 Ty = ArrayTy->getElementType();
518 } else {
519 Subscripts.clear();
520 Sizes.clear();
521 break;
522 }
Johannes Doerferta90943d2016-02-21 16:37:25 +0000523 if (auto *Const = dyn_cast<SCEVConstant>(Expr))
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000524 if (Const->getValue()->isZero()) {
525 DroppedFirstDim = true;
526 continue;
527 }
528 Subscripts.push_back(Expr);
529 continue;
530 }
531
Johannes Doerferta90943d2016-02-21 16:37:25 +0000532 auto *ArrayTy = dyn_cast<ArrayType>(Ty);
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000533 if (!ArrayTy) {
534 Subscripts.clear();
535 Sizes.clear();
536 break;
537 }
538
539 Subscripts.push_back(Expr);
540 if (!(DroppedFirstDim && i == 2))
541 Sizes.push_back(ArrayTy->getNumElements());
542
543 Ty = ArrayTy->getElementType();
544 }
545
546 return std::make_tuple(Subscripts, Sizes);
547}
548
Tobias Grosser75805372011-04-29 06:27:02 +0000549MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000550 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000551 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000552 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000553 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000554}
555
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000556const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
557 isl_id *ArrayId = getArrayId();
558 void *User = isl_id_get_user(ArrayId);
559 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
560 isl_id_free(ArrayId);
561 return SAI;
562}
563
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000564__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000565 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
566}
567
Tobias Grosserd840fc72016-02-04 13:18:42 +0000568__isl_give isl_map *MemoryAccess::getAddressFunction() const {
569 return isl_map_lexmin(getAccessRelation());
570}
571
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000572__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
573 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000574 isl_map *Schedule, *ScheduledAccRel;
575 isl_union_set *UDomain;
576
577 UDomain = isl_union_set_from_set(getStatement()->getDomain());
578 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
579 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000580 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000581 return isl_pw_multi_aff_from_map(ScheduledAccRel);
582}
583
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000584__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000585 return isl_map_copy(AccessRelation);
586}
587
Johannes Doerferta99130f2014-10-13 12:58:03 +0000588std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000589 return stringFromIslObj(AccessRelation);
590}
591
Johannes Doerferta99130f2014-10-13 12:58:03 +0000592__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000593 return isl_map_get_space(AccessRelation);
594}
595
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000596__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000597 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000598}
599
Tobias Grosser6f730082015-09-05 07:46:47 +0000600std::string MemoryAccess::getNewAccessRelationStr() const {
601 return stringFromIslObj(NewAccessRelation);
602}
603
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000604__isl_give isl_basic_map *
605MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000606 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000607 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000608
Tobias Grosser084d8f72012-05-29 09:29:44 +0000609 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000610 isl_basic_set_universe(Statement->getDomainSpace()),
611 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000612}
613
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000614// Formalize no out-of-bound access assumption
615//
616// When delinearizing array accesses we optimistically assume that the
617// delinearized accesses do not access out of bound locations (the subscript
618// expression of each array evaluates for each statement instance that is
619// executed to a value that is larger than zero and strictly smaller than the
620// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000621// dimension for which we do not need to assume any upper bound. At this point
622// we formalize this assumption to ensure that at code generation time the
623// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000624//
625// To find the set of constraints necessary to avoid out of bound accesses, we
626// first build the set of data locations that are not within array bounds. We
627// then apply the reverse access relation to obtain the set of iterations that
628// may contain invalid accesses and reduce this set of iterations to the ones
629// that are actually executed by intersecting them with the domain of the
630// statement. If we now project out all loop dimensions, we obtain a set of
631// parameters that may cause statement instances to be executed that may
632// possibly yield out of bound memory accesses. The complement of these
633// constraints is the set of constraints that needs to be assumed to ensure such
634// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000635void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000636 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000637 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000638 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000639 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000640 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
641 isl_pw_aff *Var =
642 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
643 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
644
645 isl_set *DimOutside;
646
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000647 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000648 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000649 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
650 isl_space_dim(Space, isl_dim_set));
651 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
652 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000653
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000654 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000655
656 Outside = isl_set_union(Outside, DimOutside);
657 }
658
659 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
660 Outside = isl_set_intersect(Outside, Statement->getDomain());
661 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000662
663 // Remove divs to avoid the construction of overly complicated assumptions.
664 // Doing so increases the set of parameter combinations that are assumed to
665 // not appear. This is always save, but may make the resulting run-time check
666 // bail out more often than strictly necessary.
667 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000668 Outside = isl_set_complement(Outside);
Michael Kruse7071e8b2016-04-11 13:24:29 +0000669 const auto &Loc = getAccessInstruction()
670 ? getAccessInstruction()->getDebugLoc()
671 : DebugLoc();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000672 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
673 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000674 isl_space_free(Space);
675}
676
Johannes Doerfertcea61932016-02-21 19:13:19 +0000677void MemoryAccess::buildMemIntrinsicAccessRelation() {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000678 assert(isa<MemIntrinsic>(getAccessInstruction()));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000679 assert(Subscripts.size() == 2 && Sizes.size() == 0);
680
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000681 auto *SubscriptPWA = getPwAff(Subscripts[0]);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000682 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000683
684 isl_map *LengthMap;
685 if (Subscripts[1] == nullptr) {
686 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
687 } else {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000688 auto *LengthPWA = getPwAff(Subscripts[1]);
Johannes Doerferta7920982016-02-25 14:08:48 +0000689 LengthMap = isl_map_from_pw_aff(LengthPWA);
690 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
691 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
692 }
693 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
694 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000695 SubscriptMap =
696 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000697 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
698 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
699 getStatement()->getDomainId());
700}
701
Johannes Doerferte7044942015-02-24 11:58:30 +0000702void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
703 ScalarEvolution *SE = Statement->getParent()->getSE();
704
Johannes Doerfertcea61932016-02-21 19:13:19 +0000705 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000706 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000707 return;
708
709 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000710 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
711 return;
712
713 auto *PtrSCEV = SE->getSCEV(Ptr);
714 if (isa<SCEVCouldNotCompute>(PtrSCEV))
715 return;
716
717 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
718 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
719 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
720
721 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
722 if (Range.isFullSet())
723 return;
724
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000725 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000726 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000727 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000728 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000729 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000730
731 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000732 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000733
734 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
735 AccessRange =
736 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
737 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
738}
739
Michael Krusee2bccbb2015-09-18 19:59:43 +0000740__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000741 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000742 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000743
744 for (int i = Size - 2; i >= 0; --i) {
745 isl_space *Space;
746 isl_map *MapOne, *MapTwo;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000747 isl_pw_aff *DimSize = getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000748
749 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
750 isl_pw_aff_free(DimSize);
751 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
752
753 Space = isl_map_get_space(AccessRelation);
754 Space = isl_space_map_from_set(isl_space_range(Space));
755 Space = isl_space_align_params(Space, SpaceSize);
756
757 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
758 isl_id_free(ParamId);
759
760 MapOne = isl_map_universe(isl_space_copy(Space));
761 for (int j = 0; j < Size; ++j)
762 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
763 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
764
765 MapTwo = isl_map_universe(isl_space_copy(Space));
766 for (int j = 0; j < Size; ++j)
767 if (j < i || j > i + 1)
768 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
769
770 isl_local_space *LS = isl_local_space_from_space(Space);
771 isl_constraint *C;
772 C = isl_equality_alloc(isl_local_space_copy(LS));
773 C = isl_constraint_set_constant_si(C, -1);
774 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
775 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
776 MapTwo = isl_map_add_constraint(MapTwo, C);
777 C = isl_equality_alloc(LS);
778 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
779 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
780 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
781 MapTwo = isl_map_add_constraint(MapTwo, C);
782 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
783
784 MapOne = isl_map_union(MapOne, MapTwo);
785 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
786 }
787 return AccessRelation;
788}
789
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000790/// @brief Check if @p Expr is divisible by @p Size.
791static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000792 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000793 if (Size == 1)
794 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000795
796 // Only one factor needs to be divisible.
797 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
798 for (auto *FactorExpr : MulExpr->operands())
799 if (isDivisible(FactorExpr, Size, SE))
800 return true;
801 return false;
802 }
803
804 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
805 // to be divisble.
806 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
807 for (auto *OpExpr : NAryExpr->operands())
808 if (!isDivisible(OpExpr, Size, SE))
809 return false;
810 return true;
811 }
812
813 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
814 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
815 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
816 return MulSCEV == Expr;
817}
818
Michael Krusee2bccbb2015-09-18 19:59:43 +0000819void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
820 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000821
Johannes Doerfert85676e32016-04-23 14:32:34 +0000822 // Initialize the invalid domain which describes all iterations for which the
823 // access relation is not modeled correctly.
824 InvalidDomain = getStatement()->getInvalidDomain();
825
Michael Krusee2bccbb2015-09-18 19:59:43 +0000826 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000827 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000828
Michael Krusee2bccbb2015-09-18 19:59:43 +0000829 if (!isAffine()) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000830 if (isa<MemIntrinsic>(getAccessInstruction()))
831 buildMemIntrinsicAccessRelation();
832
Tobias Grosser4f967492013-06-23 05:21:18 +0000833 // We overapproximate non-affine accesses with a possible access to the
834 // whole array. For read accesses it does not make a difference, if an
835 // access must or may happen. However, for write accesses it is important to
836 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000837 if (!AccessRelation)
838 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
839
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000840 AccessRelation =
841 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000842 return;
843 }
844
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000845 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000846 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000847
Michael Krusee2bccbb2015-09-18 19:59:43 +0000848 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000849 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000850 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000851 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000852 }
853
Tobias Grosser5d51afe2016-02-02 16:46:45 +0000854 if (Sizes.size() >= 1 && !isa<SCEVConstant>(Sizes[0]))
Michael Krusee2bccbb2015-09-18 19:59:43 +0000855 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000856
Tobias Grosser79baa212014-04-10 08:38:02 +0000857 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000858 AccessRelation = isl_map_set_tuple_id(
859 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000860 AccessRelation =
861 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
862
Tobias Grosseraa660a92015-03-30 00:07:50 +0000863 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000864 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000865}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000866
Michael Krusecac948e2015-10-02 13:53:07 +0000867MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000868 AccessType AccType, Value *BaseAddress,
869 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000870 ArrayRef<const SCEV *> Subscripts,
871 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000872 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000873 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Johannes Doerfert85676e32016-04-23 14:32:34 +0000874 InvalidDomain(nullptr), BaseAddr(BaseAddress), BaseName(BaseName),
875 ElementType(ElementType), Sizes(Sizes.begin(), Sizes.end()),
876 AccessInstruction(AccessInst), AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000877 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000878 NewAccessRelation(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000879 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Johannes Doerfertcea61932016-02-21 19:13:19 +0000880 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000881
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000882 std::string IdName =
883 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000884 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
885}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000886
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000887void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000888 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Johannes Doerfert85676e32016-04-23 14:32:34 +0000889 InvalidDomain =
890 isl_set_align_params(InvalidDomain, isl_space_copy(ParamSpace));
Tobias Grosser37487052011-10-06 00:03:42 +0000891 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000892}
893
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000894const std::string MemoryAccess::getReductionOperatorStr() const {
895 return MemoryAccess::getReductionOperatorStr(getReductionType());
896}
897
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000898__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
899
Johannes Doerfertf6183392014-07-01 20:52:51 +0000900raw_ostream &polly::operator<<(raw_ostream &OS,
901 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000902 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000903 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000904 else
905 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000906 return OS;
907}
908
Tobias Grosser75805372011-04-29 06:27:02 +0000909void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000910 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000911 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000912 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000913 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000914 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000915 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000916 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000917 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000918 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000919 break;
920 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000921 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000922 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000923 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000924 if (hasNewAccessRelation())
925 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000926}
927
Tobias Grosser74394f02013-01-14 22:40:23 +0000928void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000929
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000930__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
931 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +0000932 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
933 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
934 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000935}
936
Tobias Grosser75805372011-04-29 06:27:02 +0000937// Create a map in the size of the provided set domain, that maps from the
938// one element of the provided set domain to another element of the provided
939// set domain.
940// The mapping is limited to all points that are equal in all but the last
941// dimension and for which the last dimension of the input is strict smaller
942// than the last dimension of the output.
943//
944// getEqualAndLarger(set[i0, i1, ..., iX]):
945//
946// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
947// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
948//
Tobias Grosserf5338802011-10-06 00:03:35 +0000949static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000950 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000951 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000952 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000953
954 // Set all but the last dimension to be equal for the input and output
955 //
956 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
957 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000958 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000959 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000960
961 // Set the last dimension of the input to be strict smaller than the
962 // last dimension of the output.
963 //
964 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000965 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
966 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000967 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000968}
969
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000970__isl_give isl_set *
971MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000972 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000973 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000974 isl_space *Space = isl_space_range(isl_map_get_space(S));
975 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000976
Sebastian Popa00a0292012-12-18 07:46:06 +0000977 S = isl_map_reverse(S);
978 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000979
Sebastian Popa00a0292012-12-18 07:46:06 +0000980 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
981 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
982 NextScatt = isl_map_apply_domain(NextScatt, S);
983 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000984
Sebastian Popa00a0292012-12-18 07:46:06 +0000985 isl_set *Deltas = isl_map_deltas(NextScatt);
986 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000987}
988
Sebastian Popa00a0292012-12-18 07:46:06 +0000989bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000990 int StrideWidth) const {
991 isl_set *Stride, *StrideX;
992 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000993
Sebastian Popa00a0292012-12-18 07:46:06 +0000994 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000995 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000996 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
997 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
998 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
999 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +00001000 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +00001001
Tobias Grosser28dd4862012-01-24 16:42:16 +00001002 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +00001003 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001004
Tobias Grosser28dd4862012-01-24 16:42:16 +00001005 return IsStrideX;
1006}
1007
Sebastian Popa00a0292012-12-18 07:46:06 +00001008bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
1009 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001010}
1011
Sebastian Popa00a0292012-12-18 07:46:06 +00001012bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
1013 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001014}
1015
Tobias Grosser166c4222015-09-05 07:46:40 +00001016void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
1017 isl_map_free(NewAccessRelation);
1018 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001019}
Tobias Grosser75805372011-04-29 06:27:02 +00001020
1021//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001022
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001023__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001024 isl_set *Domain = getDomain();
1025 if (isl_set_is_empty(Domain)) {
1026 isl_set_free(Domain);
1027 return isl_map_from_aff(
1028 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1029 }
1030 auto *Schedule = getParent()->getSchedule();
1031 Schedule = isl_union_map_intersect_domain(
1032 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1033 if (isl_union_map_is_empty(Schedule)) {
1034 isl_set_free(Domain);
1035 isl_union_map_free(Schedule);
1036 return isl_map_from_aff(
1037 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1038 }
1039 auto *M = isl_map_from_union_map(Schedule);
1040 M = isl_map_coalesce(M);
1041 M = isl_map_gist_domain(M, Domain);
1042 M = isl_map_coalesce(M);
1043 return M;
1044}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001045
Johannes Doerfert574182d2015-08-12 10:19:50 +00001046__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00001047 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock());
1048 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1049 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +00001050}
1051
Tobias Grosser37eb4222014-02-20 21:43:54 +00001052void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1053 assert(isl_set_is_subset(NewDomain, Domain) &&
1054 "New domain is not a subset of old domain!");
1055 isl_set_free(Domain);
1056 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001057}
1058
Michael Krusecac948e2015-10-02 13:53:07 +00001059void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001060 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001061 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001062 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001063
Tobias Grossera535dff2015-12-13 19:59:01 +00001064 ScopArrayInfo::MemoryKind Ty;
1065 if (Access->isPHIKind())
1066 Ty = ScopArrayInfo::MK_PHI;
1067 else if (Access->isExitPHIKind())
1068 Ty = ScopArrayInfo::MK_ExitPHI;
1069 else if (Access->isValueKind())
1070 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001071 else
Tobias Grossera535dff2015-12-13 19:59:01 +00001072 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001073
Johannes Doerfertadeab372016-02-07 13:57:32 +00001074 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
1075 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001076 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001077 }
1078}
1079
Michael Krusecac948e2015-10-02 13:53:07 +00001080void ScopStmt::addAccess(MemoryAccess *Access) {
1081 Instruction *AccessInst = Access->getAccessInstruction();
1082
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001083 if (Access->isArrayKind()) {
1084 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1085 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001086 } else if (Access->isValueKind() && Access->isWrite()) {
1087 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001088 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001089 assert(!ValueWrites.lookup(AccessVal));
1090
1091 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001092 } else if (Access->isValueKind() && Access->isRead()) {
1093 Value *AccessVal = Access->getAccessValue();
1094 assert(!ValueReads.lookup(AccessVal));
1095
1096 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001097 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1098 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
1099 assert(!PHIWrites.lookup(PHI));
1100
1101 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001102 }
1103
1104 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001105}
1106
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001107void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001108 for (MemoryAccess *MA : *this)
1109 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001110
Johannes Doerferta3519512016-04-23 13:02:23 +00001111 InvalidDomain = isl_set_align_params(InvalidDomain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001112 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001113}
1114
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001115/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
1116static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1117 void *User) {
1118 isl_set **BoundedParts = static_cast<isl_set **>(User);
1119 if (isl_basic_set_is_bounded(BSet))
1120 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1121 else
1122 isl_basic_set_free(BSet);
1123 return isl_stat_ok;
1124}
1125
1126/// @brief Return the bounded parts of @p S.
1127static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1128 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1129 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1130 isl_set_free(S);
1131 return BoundedParts;
1132}
1133
1134/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
1135///
1136/// @returns A separation of @p S into first an unbounded then a bounded subset,
1137/// both with regards to the dimension @p Dim.
1138static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1139partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1140
1141 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001142 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001143
1144 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001145 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001146
1147 // Remove dimensions that are greater than Dim as they are not interesting.
1148 assert(NumDimsS >= Dim + 1);
1149 OnlyDimS =
1150 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1151
1152 // Create artificial parametric upper bounds for dimensions smaller than Dim
1153 // as we are not interested in them.
1154 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1155 for (unsigned u = 0; u < Dim; u++) {
1156 isl_constraint *C = isl_inequality_alloc(
1157 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1158 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1159 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1160 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1161 }
1162
1163 // Collect all bounded parts of OnlyDimS.
1164 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1165
1166 // Create the dimensions greater than Dim again.
1167 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1168 NumDimsS - Dim - 1);
1169
1170 // Remove the artificial upper bound parameters again.
1171 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1172
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001173 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001174 return std::make_pair(UnboundedParts, BoundedParts);
1175}
1176
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001177/// @brief Set the dimension Ids from @p From in @p To.
1178static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1179 __isl_take isl_set *To) {
1180 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1181 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1182 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1183 }
1184 return To;
1185}
1186
1187/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001188static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001189 __isl_take isl_pw_aff *L,
1190 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001191 switch (Pred) {
1192 case ICmpInst::ICMP_EQ:
1193 return isl_pw_aff_eq_set(L, R);
1194 case ICmpInst::ICMP_NE:
1195 return isl_pw_aff_ne_set(L, R);
1196 case ICmpInst::ICMP_SLT:
1197 return isl_pw_aff_lt_set(L, R);
1198 case ICmpInst::ICMP_SLE:
1199 return isl_pw_aff_le_set(L, R);
1200 case ICmpInst::ICMP_SGT:
1201 return isl_pw_aff_gt_set(L, R);
1202 case ICmpInst::ICMP_SGE:
1203 return isl_pw_aff_ge_set(L, R);
1204 case ICmpInst::ICMP_ULT:
1205 return isl_pw_aff_lt_set(L, R);
1206 case ICmpInst::ICMP_UGT:
1207 return isl_pw_aff_gt_set(L, R);
1208 case ICmpInst::ICMP_ULE:
1209 return isl_pw_aff_le_set(L, R);
1210 case ICmpInst::ICMP_UGE:
1211 return isl_pw_aff_ge_set(L, R);
1212 default:
1213 llvm_unreachable("Non integer predicate not supported");
1214 }
1215}
1216
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001217/// @brief Create the conditions under which @p L @p Pred @p R is true.
1218///
1219/// Helper function that will make sure the dimensions of the result have the
1220/// same isl_id's as the @p Domain.
1221static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1222 __isl_take isl_pw_aff *L,
1223 __isl_take isl_pw_aff *R,
1224 __isl_keep isl_set *Domain) {
1225 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1226 return setDimensionIds(Domain, ConsequenceCondSet);
1227}
1228
1229/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001230///
1231/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001232/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1233/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001234static void
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001235buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1236 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001237 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1238
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001239 Value *Condition = getConditionFromTerminator(SI);
1240 assert(Condition && "No condition for switch");
1241
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001242 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001243 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001244 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001245 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001246
1247 unsigned NumSuccessors = SI->getNumSuccessors();
1248 ConditionSets.resize(NumSuccessors);
1249 for (auto &Case : SI->cases()) {
1250 unsigned Idx = Case.getSuccessorIndex();
1251 ConstantInt *CaseValue = Case.getCaseValue();
1252
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001253 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001254 isl_set *CaseConditionSet =
1255 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1256 ConditionSets[Idx] = isl_set_coalesce(
1257 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1258 }
1259
1260 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1261 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1262 for (unsigned u = 2; u < NumSuccessors; u++)
1263 ConditionSetUnion =
1264 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1265 ConditionSets[0] = setDimensionIds(
1266 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1267
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001268 isl_pw_aff_free(LHS);
1269}
1270
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001271/// @brief Build the conditions sets for the branch condition @p Condition in
1272/// the @p Domain.
1273///
1274/// This will fill @p ConditionSets with the conditions under which control
1275/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001276/// have as many elements as @p TI has successors. If @p TI is nullptr the
1277/// context under which @p Condition is true/false will be returned as the
1278/// new elements of @p ConditionSets.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001279static void
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001280buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1281 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001282 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1283
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001284 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001285 isl_set *ConsequenceCondSet = nullptr;
1286 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1287 if (CCond->isZero())
1288 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1289 else
1290 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1291 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1292 auto Opcode = BinOp->getOpcode();
1293 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1294
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001295 buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1296 ConditionSets);
1297 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1298 ConditionSets);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001299
1300 isl_set_free(ConditionSets.pop_back_val());
1301 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1302 isl_set_free(ConditionSets.pop_back_val());
1303 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1304
1305 if (Opcode == Instruction::And)
1306 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1307 else
1308 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1309 } else {
1310 auto *ICond = dyn_cast<ICmpInst>(Condition);
1311 assert(ICond &&
1312 "Condition of exiting branch was neither constant nor ICmp!");
1313
1314 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001315 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001316 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L));
1317 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001318 ConsequenceCondSet =
1319 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1320 }
1321
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001322 // If no terminator was given we are only looking for parameter constraints
1323 // under which @p Condition is true/false.
1324 if (!TI)
1325 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001326 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001327 ConsequenceCondSet = isl_set_coalesce(
1328 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001329
Johannes Doerfert15194912016-04-04 07:59:41 +00001330 isl_set *AlternativeCondSet;
1331 unsigned NumParams = isl_set_n_param(ConsequenceCondSet);
1332 unsigned NumBasicSets = isl_set_n_basic_set(ConsequenceCondSet);
1333 if (NumBasicSets + NumParams < MaxConjunctsInDomain) {
1334 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1335 isl_set_copy(ConsequenceCondSet));
1336 } else {
1337 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
1338 AlternativeCondSet = isl_set_empty(isl_set_get_space(ConsequenceCondSet));
1339 }
1340
1341 ConditionSets.push_back(ConsequenceCondSet);
1342 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001343}
1344
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001345/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1346///
1347/// This will fill @p ConditionSets with the conditions under which control
1348/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1349/// have as many elements as @p TI has successors.
1350static void
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001351buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001352 __isl_keep isl_set *Domain,
1353 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1354
1355 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001356 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001357
1358 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1359
1360 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001361 ConditionSets.push_back(isl_set_copy(Domain));
1362 return;
1363 }
1364
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001365 Value *Condition = getConditionFromTerminator(TI);
1366 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001367
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001368 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001369}
1370
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001371void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001372 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001373
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001374 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001375 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001376}
1377
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001378void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP,
1379 ScopDetection &SD) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001380 isl_ctx *Ctx = Parent.getIslCtx();
1381 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1382 Type *Ty = GEP->getPointerOperandType();
1383 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001384
1385 // The set of loads that are required to be invariant.
1386 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001387
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001388 std::vector<const SCEV *> Subscripts;
1389 std::vector<int> Sizes;
1390
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001391 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001392
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001393 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001394 Ty = PtrTy->getElementType();
1395 }
1396
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001397 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001398
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001399 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001400
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001401 auto *NotExecuted = isl_set_complement(isl_set_params(getDomain()));
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001402 for (size_t i = 0; i < Sizes.size(); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001403 auto *Expr = Subscripts[i + IndexOffset];
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001404 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001405
Michael Kruse09eb4452016-03-03 22:10:47 +00001406 auto *Scope = SD.getLI()->getLoopFor(getEntryBlock());
Johannes Doerfert09e36972015-10-07 20:17:36 +00001407 InvariantLoadsSetTy AccessILS;
Johannes Doerfertec8a2172016-04-25 13:32:36 +00001408 if (!isAffineExpr(&Parent.getRegion(), Scope, Expr, SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +00001409 continue;
1410
1411 bool NonAffine = false;
1412 for (LoadInst *LInst : AccessILS)
1413 if (!ScopRIL.count(LInst))
1414 NonAffine = true;
1415
1416 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001417 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001418
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001419 isl_pw_aff *AccessOffset = getPwAff(Expr);
1420 AccessOffset =
1421 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001422
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001423 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1424 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001425
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001426 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1427 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1428 OutOfBound = isl_set_params(OutOfBound);
1429 isl_set *InBound = isl_set_complement(OutOfBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001430
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001431 // A => B == !A or B
1432 isl_set *InBoundIfExecuted =
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001433 isl_set_union(isl_set_copy(NotExecuted), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001434
Roman Gareev10595a12016-01-08 14:01:59 +00001435 InBoundIfExecuted = isl_set_coalesce(InBoundIfExecuted);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00001436 Parent.recordAssumption(INBOUNDS, InBoundIfExecuted, GEP->getDebugLoc(),
1437 AS_ASSUMPTION);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001438 }
1439
1440 isl_local_space_free(LSpace);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001441 isl_set_free(NotExecuted);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001442}
1443
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001444void ScopStmt::deriveAssumptions(BasicBlock *Block, ScopDetection &SD) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001445 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001446 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001447 deriveAssumptionsFromGEP(GEP, SD);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001448}
1449
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001450void ScopStmt::collectSurroundingLoops() {
1451 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1452 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1453 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1454 isl_id_free(DimId);
1455 }
1456}
1457
Michael Kruse9d080092015-09-11 21:41:48 +00001458ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerferta3519512016-04-23 13:02:23 +00001459 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
1460 R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001461
Tobias Grosser16c44032015-07-09 07:31:45 +00001462 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001463}
1464
Michael Kruse9d080092015-09-11 21:41:48 +00001465ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerferta3519512016-04-23 13:02:23 +00001466 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
1467 R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001468
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001469 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001470}
1471
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001472void ScopStmt::init(ScopDetection &SD) {
Michael Krusecac948e2015-10-02 13:53:07 +00001473 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001474
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001475 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001476 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001477 buildAccessRelations();
1478
1479 if (BB) {
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001480 deriveAssumptions(BB, SD);
Michael Krusecac948e2015-10-02 13:53:07 +00001481 } else {
1482 for (BasicBlock *Block : R->blocks()) {
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001483 deriveAssumptions(Block, SD);
Michael Krusecac948e2015-10-02 13:53:07 +00001484 }
1485 }
1486
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001487 if (DetectReductions)
1488 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001489}
1490
Johannes Doerferte58a0122014-06-27 20:31:28 +00001491/// @brief Collect loads which might form a reduction chain with @p StoreMA
1492///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001493/// Check if the stored value for @p StoreMA is a binary operator with one or
1494/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001495/// used only once (by @p StoreMA) and its load operands are also used only
1496/// once, we have found a possible reduction chain. It starts at an operand
1497/// load and includes the binary operator and @p StoreMA.
1498///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001499/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001500/// escape this block or into any other store except @p StoreMA.
1501void ScopStmt::collectCandiateReductionLoads(
1502 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1503 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1504 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001505 return;
1506
1507 // Skip if there is not one binary operator between the load and the store
1508 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001509 if (!BinOp)
1510 return;
1511
1512 // Skip if the binary operators has multiple uses
1513 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001514 return;
1515
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001516 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001517 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1518 return;
1519
Johannes Doerfert9890a052014-07-01 00:32:29 +00001520 // Skip if the binary operator is outside the current SCoP
1521 if (BinOp->getParent() != Store->getParent())
1522 return;
1523
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001524 // Skip if it is a multiplicative reduction and we disabled them
1525 if (DisableMultiplicativeReductions &&
1526 (BinOp->getOpcode() == Instruction::Mul ||
1527 BinOp->getOpcode() == Instruction::FMul))
1528 return;
1529
Johannes Doerferte58a0122014-06-27 20:31:28 +00001530 // Check the binary operator operands for a candidate load
1531 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1532 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1533 if (!PossibleLoad0 && !PossibleLoad1)
1534 return;
1535
1536 // A load is only a candidate if it cannot escape (thus has only this use)
1537 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001538 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001539 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001540 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001541 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001542 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001543}
1544
1545/// @brief Check for reductions in this ScopStmt
1546///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001547/// Iterate over all store memory accesses and check for valid binary reduction
1548/// like chains. For all candidates we check if they have the same base address
1549/// and there are no other accesses which overlap with them. The base address
1550/// check rules out impossible reductions candidates early. The overlap check,
1551/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001552/// guarantees that none of the intermediate results will escape during
1553/// execution of the loop nest. We basically check here that no other memory
1554/// access can access the same memory as the potential reduction.
1555void ScopStmt::checkForReductions() {
1556 SmallVector<MemoryAccess *, 2> Loads;
1557 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1558
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001559 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001560 // stores and collecting possible reduction loads.
1561 for (MemoryAccess *StoreMA : MemAccs) {
1562 if (StoreMA->isRead())
1563 continue;
1564
1565 Loads.clear();
1566 collectCandiateReductionLoads(StoreMA, Loads);
1567 for (MemoryAccess *LoadMA : Loads)
1568 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1569 }
1570
1571 // Then check each possible candidate pair.
1572 for (const auto &CandidatePair : Candidates) {
1573 bool Valid = true;
1574 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1575 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1576
1577 // Skip those with obviously unequal base addresses.
1578 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1579 isl_map_free(LoadAccs);
1580 isl_map_free(StoreAccs);
1581 continue;
1582 }
1583
1584 // And check if the remaining for overlap with other memory accesses.
1585 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1586 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1587 isl_set *AllAccs = isl_map_range(AllAccsRel);
1588
1589 for (MemoryAccess *MA : MemAccs) {
1590 if (MA == CandidatePair.first || MA == CandidatePair.second)
1591 continue;
1592
1593 isl_map *AccRel =
1594 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1595 isl_set *Accs = isl_map_range(AccRel);
1596
1597 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1598 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1599 Valid = Valid && isl_set_is_empty(OverlapAccs);
1600 isl_set_free(OverlapAccs);
1601 }
1602 }
1603
1604 isl_set_free(AllAccs);
1605 if (!Valid)
1606 continue;
1607
Johannes Doerfertf6183392014-07-01 20:52:51 +00001608 const LoadInst *Load =
1609 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1610 MemoryAccess::ReductionType RT =
1611 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1612
Johannes Doerferte58a0122014-06-27 20:31:28 +00001613 // If no overlapping access was found we mark the load and store as
1614 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001615 CandidatePair.first->markAsReductionLike(RT);
1616 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001617 }
Tobias Grosser75805372011-04-29 06:27:02 +00001618}
1619
Tobias Grosser74394f02013-01-14 22:40:23 +00001620std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001621
Tobias Grosser54839312015-04-21 11:37:25 +00001622std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001623 auto *S = getSchedule();
1624 auto Str = stringFromIslObj(S);
1625 isl_map_free(S);
1626 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001627}
1628
Johannes Doerferta3519512016-04-23 13:02:23 +00001629void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1630 isl_set_free(InvalidDomain);
1631 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001632}
1633
Michael Kruse375cb5f2016-02-24 22:08:24 +00001634BasicBlock *ScopStmt::getEntryBlock() const {
1635 if (isBlockStmt())
1636 return getBasicBlock();
1637 return getRegion()->getEntry();
1638}
1639
Michael Kruse7b5caa42016-02-24 22:08:28 +00001640RegionNode *ScopStmt::getRegionNode() const {
1641 if (isRegionStmt())
1642 return getRegion()->getNode();
1643 return getParent()->getRegion().getBBNode(getBasicBlock());
1644}
1645
Tobias Grosser74394f02013-01-14 22:40:23 +00001646unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001647
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001648unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001649
Tobias Grosser75805372011-04-29 06:27:02 +00001650const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1651
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001652const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001653 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001654}
1655
Tobias Grosser74394f02013-01-14 22:40:23 +00001656isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001657
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001658__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001659
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001660__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001661 return isl_set_get_space(Domain);
1662}
1663
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001664__isl_give isl_id *ScopStmt::getDomainId() const {
1665 return isl_set_get_tuple_id(Domain);
1666}
Tobias Grossercd95b772012-08-30 11:49:38 +00001667
Johannes Doerfert7c013572016-04-12 09:57:34 +00001668ScopStmt::~ScopStmt() {
1669 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001670 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001671}
Tobias Grosser75805372011-04-29 06:27:02 +00001672
1673void ScopStmt::print(raw_ostream &OS) const {
1674 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001675 OS.indent(12) << "Domain :=\n";
1676
1677 if (Domain) {
1678 OS.indent(16) << getDomainStr() << ";\n";
1679 } else
1680 OS.indent(16) << "n/a\n";
1681
Tobias Grosser54839312015-04-21 11:37:25 +00001682 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001683
1684 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001685 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001686 } else
1687 OS.indent(16) << "n/a\n";
1688
Tobias Grosser083d3d32014-06-28 08:59:45 +00001689 for (MemoryAccess *Access : MemAccs)
1690 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001691}
1692
1693void ScopStmt::dump() const { print(dbgs()); }
1694
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001695void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001696 // Remove all memory accesses in @p InvMAs from this statement
1697 // together with all scalar accesses that were caused by them.
Michael Krusead28e5a2016-01-26 13:33:15 +00001698 // MK_Value READs have no access instruction, hence would not be removed by
1699 // this function. However, it is only used for invariant LoadInst accesses,
1700 // its arguments are always affine, hence synthesizable, and therefore there
1701 // are no MK_Value READ accesses to be removed.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001702 for (MemoryAccess *MA : InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001703 auto Predicate = [&](MemoryAccess *Acc) {
Tobias Grosser3a6ac9f2015-11-30 21:13:43 +00001704 return Acc->getAccessInstruction() == MA->getAccessInstruction();
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001705 };
1706 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1707 MemAccs.end());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001708 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001709 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001710}
1711
Tobias Grosser75805372011-04-29 06:27:02 +00001712//===----------------------------------------------------------------------===//
1713/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001714
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001715void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001716 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1717 isl_set_free(Context);
1718 Context = NewContext;
1719}
1720
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001721/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1722struct SCEVSensitiveParameterRewriter
1723 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1724 ValueToValueMap &VMap;
1725 ScalarEvolution &SE;
1726
1727public:
1728 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1729 : VMap(VMap), SE(SE) {}
1730
1731 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1732 ValueToValueMap &VMap) {
1733 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1734 return SSPR.visit(E);
1735 }
1736
1737 const SCEV *visit(const SCEV *E) {
1738 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1739 }
1740
1741 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1742
1743 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1744 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1745 }
1746
1747 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1748 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1749 }
1750
1751 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1752 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1753 }
1754
1755 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1756 SmallVector<const SCEV *, 4> Operands;
1757 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1758 Operands.push_back(visit(E->getOperand(i)));
1759 return SE.getAddExpr(Operands);
1760 }
1761
1762 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1763 SmallVector<const SCEV *, 4> Operands;
1764 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1765 Operands.push_back(visit(E->getOperand(i)));
1766 return SE.getMulExpr(Operands);
1767 }
1768
1769 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1770 SmallVector<const SCEV *, 4> Operands;
1771 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1772 Operands.push_back(visit(E->getOperand(i)));
1773 return SE.getSMaxExpr(Operands);
1774 }
1775
1776 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1777 SmallVector<const SCEV *, 4> Operands;
1778 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1779 Operands.push_back(visit(E->getOperand(i)));
1780 return SE.getUMaxExpr(Operands);
1781 }
1782
1783 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1784 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1785 }
1786
1787 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1788 auto *Start = visit(E->getStart());
1789 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1790 visit(E->getStepRecurrence(SE)),
1791 E->getLoop(), SCEV::FlagAnyWrap);
1792 return SE.getAddExpr(Start, AddRec);
1793 }
1794
1795 const SCEV *visitUnknown(const SCEVUnknown *E) {
1796 if (auto *NewValue = VMap.lookup(E->getValue()))
1797 return SE.getUnknown(NewValue);
1798 return E;
1799 }
1800};
1801
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001802const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001803 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001804}
1805
Johannes Doerfertf560b3d2016-04-25 13:33:07 +00001806void Scop::addParams(const ParameterSetTy &NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001807 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001808 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001809
1810 // Normalize the SCEV to get the representing element for an invariant load.
1811 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1812
Tobias Grosser60b54f12011-11-08 15:41:28 +00001813 if (ParameterIds.find(Parameter) != ParameterIds.end())
1814 continue;
1815
1816 int dimension = Parameters.size();
1817
1818 Parameters.push_back(Parameter);
1819 ParameterIds[Parameter] = dimension;
1820 }
1821}
1822
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001823__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001824 // Normalize the SCEV to get the representing element for an invariant load.
1825 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1826
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001827 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001828
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001829 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001830 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001831
Tobias Grosser8f99c162011-11-15 11:38:55 +00001832 std::string ParameterName;
1833
Craig Topper7fb6e472016-01-31 20:36:20 +00001834 ParameterName = "p_" + utostr(IdIter->second);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001835
Tobias Grosser8f99c162011-11-15 11:38:55 +00001836 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1837 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001838
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001839 // If this parameter references a specific Value and this value has a name
1840 // we use this name as it is likely to be unique and more useful than just
1841 // a number.
1842 if (Val->hasName())
1843 ParameterName = Val->getName();
1844 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001845 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001846 if (LoadOrigin->hasName()) {
1847 ParameterName += "_loaded_from_";
1848 ParameterName +=
1849 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1850 }
1851 }
1852 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001853
Tobias Grosser20532b82014-04-11 17:56:49 +00001854 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1855 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001856}
Tobias Grosser75805372011-04-29 06:27:02 +00001857
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001858__isl_give isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001859 isl_set *DomainContext = isl_union_set_params(getDomains());
1860 return isl_set_intersect_params(C, DomainContext);
1861}
1862
Hongbin Zheng192f69a2016-02-13 15:12:54 +00001863void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
1864 LoopInfo &LI) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001865 auto *R = &getRegion();
1866 auto &F = *R->getEntry()->getParent();
1867 for (auto &Assumption : AC.assumptions()) {
1868 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1869 if (!CI || CI->getNumArgOperands() != 1)
1870 continue;
1871 if (!DT.dominates(CI->getParent(), R->getEntry()))
1872 continue;
1873
Michael Kruse09eb4452016-03-03 22:10:47 +00001874 auto *L = LI.getLoopFor(CI->getParent());
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001875 auto *Val = CI->getArgOperand(0);
Johannes Doerfertf560b3d2016-04-25 13:33:07 +00001876 ParameterSetTy DetectedParams;
1877 if (!isAffineParamConstraint(Val, R, L, *SE, DetectedParams)) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001878 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1879 CI->getDebugLoc(),
1880 "Non-affine user assumption ignored.");
1881 continue;
1882 }
1883
Johannes Doerfertf560b3d2016-04-25 13:33:07 +00001884 addParams(DetectedParams);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001885
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001886 SmallVector<isl_set *, 2> ConditionSets;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001887 buildConditionSets(*Stmts.begin(), Val, nullptr, L, Context, ConditionSets);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001888 assert(ConditionSets.size() == 2);
1889 isl_set_free(ConditionSets[1]);
1890
1891 auto *AssumptionCtx = ConditionSets[0];
1892 emitOptimizationRemarkAnalysis(
1893 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1894 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1895 Context = isl_set_intersect(Context, AssumptionCtx);
1896 }
1897}
1898
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001899void Scop::addUserContext() {
1900 if (UserContextStr.empty())
1901 return;
1902
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001903 isl_set *UserContext =
1904 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001905 isl_space *Space = getParamSpace();
1906 if (isl_space_dim(Space, isl_dim_param) !=
1907 isl_set_dim(UserContext, isl_dim_param)) {
1908 auto SpaceStr = isl_space_to_str(Space);
1909 errs() << "Error: the context provided in -polly-context has not the same "
1910 << "number of dimensions than the computed context. Due to this "
1911 << "mismatch, the -polly-context option is ignored. Please provide "
1912 << "the context in the parameter space: " << SpaceStr << ".\n";
1913 free(SpaceStr);
1914 isl_set_free(UserContext);
1915 isl_space_free(Space);
1916 return;
1917 }
1918
1919 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001920 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1921 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001922
1923 if (strcmp(NameContext, NameUserContext) != 0) {
1924 auto SpaceStr = isl_space_to_str(Space);
1925 errs() << "Error: the name of dimension " << i
1926 << " provided in -polly-context "
1927 << "is '" << NameUserContext << "', but the name in the computed "
1928 << "context is '" << NameContext
1929 << "'. Due to this name mismatch, "
1930 << "the -polly-context option is ignored. Please provide "
1931 << "the context in the parameter space: " << SpaceStr << ".\n";
1932 free(SpaceStr);
1933 isl_set_free(UserContext);
1934 isl_space_free(Space);
1935 return;
1936 }
1937
1938 UserContext =
1939 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1940 isl_space_get_dim_id(Space, isl_dim_param, i));
1941 }
1942
1943 Context = isl_set_intersect(Context, UserContext);
1944 isl_space_free(Space);
1945}
1946
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001947void Scop::buildInvariantEquivalenceClasses(ScopDetection &SD) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00001948 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001949
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001950 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001951 for (LoadInst *LInst : RIL) {
1952 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1953
Johannes Doerfert96e54712016-02-07 17:30:13 +00001954 Type *Ty = LInst->getType();
1955 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001956 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001957 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001958 continue;
1959 }
1960
1961 ClassRep = LInst;
Johannes Doerfert96e54712016-02-07 17:30:13 +00001962 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(), nullptr,
1963 Ty);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001964 }
1965}
1966
Tobias Grosser6be480c2011-11-08 15:41:13 +00001967void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001968 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001969 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001970 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00001971 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001972}
1973
Tobias Grosser18daaca2012-05-22 10:47:27 +00001974void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001975 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001976 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001977
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001978 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001979
Johannes Doerferte7044942015-02-24 11:58:30 +00001980 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001981 }
1982}
1983
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001984void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001985 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001986 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001987
Tobias Grosser083d3d32014-06-28 08:59:45 +00001988 for (const auto &ParamID : ParameterIds) {
1989 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001990 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001991 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001992 }
1993
1994 // Align the parameters of all data structures to the model.
1995 Context = isl_set_align_params(Context, Space);
1996
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001997 for (ScopStmt &Stmt : *this)
1998 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001999}
2000
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002001static __isl_give isl_set *
2002simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2003 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002004 // If we modelt all blocks in the SCoP that have side effects we can simplify
2005 // the context with the constraints that are needed for anything to be
2006 // executed at all. However, if we have error blocks in the SCoP we already
2007 // assumed some parameter combinations cannot occure and removed them from the
2008 // domains, thus we cannot use the remaining domain to simplify the
2009 // assumptions.
2010 if (!S.hasErrorBlock()) {
2011 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2012 AssumptionContext =
2013 isl_set_gist_params(AssumptionContext, DomainParameters);
2014 }
2015
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002016 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2017 return AssumptionContext;
2018}
2019
2020void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002021 // The parameter constraints of the iteration domains give us a set of
2022 // constraints that need to hold for all cases where at least a single
2023 // statement iteration is executed in the whole scop. We now simplify the
2024 // assumed context under the assumption that such constraints hold and at
2025 // least a single statement iteration is executed. For cases where no
2026 // statement instances are executed, the assumptions we have taken about
2027 // the executed code do not matter and can be changed.
2028 //
2029 // WARNING: This only holds if the assumptions we have taken do not reduce
2030 // the set of statement instances that are executed. Otherwise we
2031 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002032 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002033 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002034 // performed. In such a case, modifying the run-time conditions and
2035 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002036 // to not be executed.
2037 //
2038 // Example:
2039 //
2040 // When delinearizing the following code:
2041 //
2042 // for (long i = 0; i < 100; i++)
2043 // for (long j = 0; j < m; j++)
2044 // A[i+p][j] = 1.0;
2045 //
2046 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002047 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002048 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002049 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002050 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002051}
2052
Johannes Doerfertb164c792014-09-18 11:17:17 +00002053/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002054static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002055 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
2056 isl_pw_multi_aff *MinPMA, *MaxPMA;
2057 isl_pw_aff *LastDimAff;
2058 isl_aff *OneAff;
2059 unsigned Pos;
2060
Johannes Doerfert6296d952016-04-22 11:38:19 +00002061 Set = isl_set_remove_divs(Set);
2062
2063 if (isl_set_n_basic_set(Set) >= MaxConjunctsInDomain) {
2064 isl_set_free(Set);
2065 return isl_stat_error;
2066 }
2067
Johannes Doerfert9143d672014-09-27 11:02:39 +00002068 // Restrict the number of parameters involved in the access as the lexmin/
2069 // lexmax computation will take too long if this number is high.
2070 //
2071 // Experiments with a simple test case using an i7 4800MQ:
2072 //
2073 // #Parameters involved | Time (in sec)
2074 // 6 | 0.01
2075 // 7 | 0.04
2076 // 8 | 0.12
2077 // 9 | 0.40
2078 // 10 | 1.54
2079 // 11 | 6.78
2080 // 12 | 30.38
2081 //
2082 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2083 unsigned InvolvedParams = 0;
2084 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2085 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2086 InvolvedParams++;
2087
2088 if (InvolvedParams > RunTimeChecksMaxParameters) {
2089 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002090 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002091 }
2092 }
2093
Johannes Doerfertb164c792014-09-18 11:17:17 +00002094 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2095 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2096
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002097 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2098 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2099
Johannes Doerfertb164c792014-09-18 11:17:17 +00002100 // Adjust the last dimension of the maximal access by one as we want to
2101 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2102 // we test during code generation might now point after the end of the
2103 // allocated array but we will never dereference it anyway.
2104 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2105 "Assumed at least one output dimension");
2106 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2107 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2108 OneAff = isl_aff_zero_on_domain(
2109 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2110 OneAff = isl_aff_add_constant_si(OneAff, 1);
2111 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2112 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2113
2114 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2115
2116 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002117 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002118}
2119
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002120static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2121 isl_set *Domain = MA->getStatement()->getDomain();
2122 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2123 return isl_set_reset_tuple_id(Domain);
2124}
2125
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002126/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
2127static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00002128 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002129 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002130
2131 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2132 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002133 Locations = isl_union_set_coalesce(Locations);
2134 Locations = isl_union_set_detect_equalities(Locations);
2135 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002136 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002137 isl_union_set_free(Locations);
2138 return Valid;
2139}
2140
Johannes Doerfert96425c22015-08-30 21:13:53 +00002141/// @brief Helper to treat non-affine regions and basic blocks the same.
2142///
2143///{
2144
2145/// @brief Return the block that is the representing block for @p RN.
2146static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2147 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2148 : RN->getNodeAs<BasicBlock>();
2149}
2150
2151/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002152static inline BasicBlock *
2153getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002154 if (RN->isSubRegion()) {
2155 assert(idx == 0);
2156 return RN->getNodeAs<Region>()->getExit();
2157 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002158 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002159}
2160
2161/// @brief Return the smallest loop surrounding @p RN.
2162static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2163 if (!RN->isSubRegion())
2164 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2165
2166 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2167 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2168 while (L && NonAffineSubRegion->contains(L))
2169 L = L->getParentLoop();
2170 return L;
2171}
2172
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002173static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2174 if (!RN->isSubRegion())
2175 return 1;
2176
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002177 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002178 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002179}
2180
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002181static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2182 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002183 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002184 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002185 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002186 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002187 return true;
2188 return false;
2189}
2190
Johannes Doerfert96425c22015-08-30 21:13:53 +00002191///}
2192
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002193static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2194 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002195 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002196 isl_id *DimId =
2197 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2198 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2199}
2200
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002201__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002202 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002203}
2204
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002205__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002206 auto DIt = DomainMap.find(BB);
2207 if (DIt != DomainMap.end())
2208 return isl_set_copy(DIt->getSecond());
2209
2210 auto &RI = *R.getRegionInfo();
2211 auto *BBR = RI.getRegionFor(BB);
2212 while (BBR->getEntry() == BB)
2213 BBR = BBR->getParent();
2214 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002215}
2216
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002217bool Scop::buildDomains(Region *R, ScopDetection &SD, DominatorTree &DT,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002218 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002219
Johannes Doerfert432658d2016-01-26 11:01:41 +00002220 bool IsOnlyNonAffineRegion = SD.isNonAffineSubRegion(R, R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002221 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002222 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2223 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002224 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002225
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002226 while (LD-- >= 0) {
2227 S = addDomainDimId(S, LD + 1, L);
2228 L = L->getParentLoop();
2229 }
2230
Johannes Doerferta3519512016-04-23 13:02:23 +00002231 // Initialize the invalid domain.
2232 auto *EntryStmt = getStmtFor(EntryBB);
2233 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2234
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002235 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002236
Johannes Doerfert432658d2016-01-26 11:01:41 +00002237 if (IsOnlyNonAffineRegion)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002238 return true;
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002239
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002240 if (!buildDomainsWithBranchConstraints(R, SD, DT, LI))
2241 return false;
2242
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002243 propagateDomainConstraints(R, SD, DT, LI);
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002244
2245 // Error blocks and blocks dominated by them have been assumed to never be
2246 // executed. Representing them in the Scop does not add any value. In fact,
2247 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002248 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002249 // will cause problems when building up a ScopStmt for them.
2250 // Furthermore, basic blocks dominated by error blocks may reference
2251 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002252 // can themselves not be constructed properly. To this end we will replace
2253 // the domains of error blocks and those only reachable via error blocks
2254 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002255 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002256 // InvalidDomain. This information is needed during load hoisting.
2257 propagateInvalidStmtDomains(R, SD, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002258
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002259 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002260}
2261
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002262static Loop *
2263getFirstNonBoxedLoopFor(BasicBlock *BB, LoopInfo &LI,
2264 const ScopDetection::BoxedLoopsSetTy &BoxedLoops) {
2265 auto *L = LI.getLoopFor(BB);
2266 while (BoxedLoops.count(L))
2267 L = L->getParentLoop();
2268 return L;
2269}
2270
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002271/// @brief Adjust the dimensions of @p Dom that was constructed for @p OldL
2272/// to be compatible to domains constructed for loop @p NewL.
2273///
2274/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2275/// edge from @p OldL to @p NewL.
2276static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2277 __isl_take isl_set *Dom,
2278 Loop *OldL, Loop *NewL) {
2279
2280 // If the loops are the same there is nothing to do.
2281 if (NewL == OldL)
2282 return Dom;
2283
2284 int OldDepth = S.getRelativeLoopDepth(OldL);
2285 int NewDepth = S.getRelativeLoopDepth(NewL);
2286 // If both loops are non-affine loops there is nothing to do.
2287 if (OldDepth == -1 && NewDepth == -1)
2288 return Dom;
2289
2290 // Distinguish three cases:
2291 // 1) The depth is the same but the loops are not.
2292 // => One loop was left one was entered.
2293 // 2) The depth increased from OldL to NewL.
2294 // => One loop was entered, none was left.
2295 // 3) The depth decreased from OldL to NewL.
2296 // => Loops were left were difference of the depths defines how many.
2297 if (OldDepth == NewDepth) {
2298 assert(OldL->getParentLoop() == NewL->getParentLoop());
2299 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2300 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2301 Dom = addDomainDimId(Dom, NewDepth, NewL);
2302 } else if (OldDepth < NewDepth) {
2303 assert(OldDepth + 1 == NewDepth);
2304 auto &R = S.getRegion();
2305 (void)R;
2306 assert(NewL->getParentLoop() == OldL ||
2307 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2308 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2309 Dom = addDomainDimId(Dom, NewDepth, NewL);
2310 } else {
2311 assert(OldDepth > NewDepth);
2312 int Diff = OldDepth - NewDepth;
2313 int NumDim = isl_set_n_dim(Dom);
2314 assert(NumDim >= Diff);
2315 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2316 }
2317
2318 return Dom;
2319}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002320
Johannes Doerferta3519512016-04-23 13:02:23 +00002321void Scop::propagateInvalidStmtDomains(Region *R, ScopDetection &SD,
2322 DominatorTree &DT, LoopInfo &LI) {
2323 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002324
2325 ReversePostOrderTraversal<Region *> RTraversal(R);
2326 for (auto *RN : RTraversal) {
2327
2328 // Recurse for affine subregions but go on for basic blocks and non-affine
2329 // subregions.
2330 if (RN->isSubRegion()) {
2331 Region *SubRegion = RN->getNodeAs<Region>();
2332 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerferta3519512016-04-23 13:02:23 +00002333 propagateInvalidStmtDomains(SubRegion, SD, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002334 continue;
2335 }
2336 }
2337
2338 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2339 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002340 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002341 isl_set *&Domain = DomainMap[BB];
2342 assert(Domain && "Cannot propagate a nullptr");
2343
Johannes Doerferta3519512016-04-23 13:02:23 +00002344 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002345 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002346 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002347
Johannes Doerferta3519512016-04-23 13:02:23 +00002348 if (!IsInvalidBlock) {
2349 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002350 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002351 isl_set_free(InvalidDomain);
2352 InvalidDomain = Domain;
2353 auto *EmptyDom = isl_set_empty(isl_set_get_space(InvalidDomain));
2354 Domain = EmptyDom;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002355 }
2356
Johannes Doerferta3519512016-04-23 13:02:23 +00002357 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002358 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002359 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002360 }
2361
Johannes Doerferta3519512016-04-23 13:02:23 +00002362 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002363 auto *TI = BB->getTerminator();
2364 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2365 for (unsigned u = 0; u < NumSuccs; u++) {
2366 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002367 auto *SuccStmt = getStmtFor(SuccBB);
2368
2369 // Skip successors outside the SCoP.
2370 if (!SuccStmt)
2371 continue;
2372
Johannes Doerferte4459a22016-04-25 13:34:50 +00002373 // Skip backedges.
2374 if (DT.dominates(SuccBB, BB))
2375 continue;
2376
Johannes Doerferta3519512016-04-23 13:02:23 +00002377 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
2378 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2379 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2380 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2381 SuccInvalidDomain =
2382 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2383 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2384 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2385 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002386
2387 // Check if the maximal number of domain conjuncts was reached.
2388 // In case this happens we will bail.
Johannes Doerfert7c013572016-04-12 09:57:34 +00002389 if (NumConjucts < MaxConjunctsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002390 continue;
2391
Johannes Doerferta3519512016-04-23 13:02:23 +00002392 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002393 invalidate(COMPLEXITY, TI->getDebugLoc());
2394 return;
2395 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002396
2397 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002398 }
2399}
2400
Johannes Doerfert642594a2016-04-04 07:57:39 +00002401void Scop::propagateDomainConstraintsToRegionExit(
2402 BasicBlock *BB, Loop *BBLoop,
2403 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, ScopDetection &SD,
2404 LoopInfo &LI) {
2405
2406 // Check if the block @p BB is the entry of a region. If so we propagate it's
2407 // domain to the exit block of the region. Otherwise we are done.
2408 auto *RI = R.getRegionInfo();
2409 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2410 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
2411 if (!BBReg || BBReg->getEntry() != BB || !R.contains(ExitBB))
2412 return;
2413
2414 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2415 // Do not propagate the domain if there is a loop backedge inside the region
2416 // that would prevent the exit block from beeing executed.
2417 auto *L = BBLoop;
2418 while (L && R.contains(L)) {
2419 SmallVector<BasicBlock *, 4> LatchBBs;
2420 BBLoop->getLoopLatches(LatchBBs);
2421 for (auto *LatchBB : LatchBBs)
2422 if (BB != LatchBB && BBReg->contains(LatchBB))
2423 return;
2424 L = L->getParentLoop();
2425 }
2426
2427 auto *Domain = DomainMap[BB];
2428 assert(Domain && "Cannot propagate a nullptr");
2429
2430 auto *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, BoxedLoops);
2431
2432 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2433 // adjust the domain before we can propagate it.
2434 auto *AdjustedDomain =
2435 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2436 auto *&ExitDomain = DomainMap[ExitBB];
2437
2438 // If the exit domain is not yet created we set it otherwise we "add" the
2439 // current domain.
2440 ExitDomain =
2441 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2442
Johannes Doerferta3519512016-04-23 13:02:23 +00002443 // Initialize the invalid domain.
2444 auto *ExitStmt = getStmtFor(ExitBB);
2445 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2446
Johannes Doerfert642594a2016-04-04 07:57:39 +00002447 FinishedExitBlocks.insert(ExitBB);
2448}
2449
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002450bool Scop::buildDomainsWithBranchConstraints(Region *R, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002451 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert6f50c292016-01-26 11:03:25 +00002452 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002453
2454 // To create the domain for each block in R we iterate over all blocks and
2455 // subregions in R and propagate the conditions under which the current region
2456 // element is executed. To this end we iterate in reverse post order over R as
2457 // it ensures that we first visit all predecessors of a region node (either a
2458 // basic block or a subregion) before we visit the region node itself.
2459 // Initially, only the domain for the SCoP region entry block is set and from
2460 // there we propagate the current domain to all successors, however we add the
2461 // condition that the successor is actually executed next.
2462 // As we are only interested in non-loop carried constraints here we can
2463 // simply skip loop back edges.
2464
Johannes Doerfert642594a2016-04-04 07:57:39 +00002465 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002466 ReversePostOrderTraversal<Region *> RTraversal(R);
2467 for (auto *RN : RTraversal) {
2468
2469 // Recurse for affine subregions but go on for basic blocks and non-affine
2470 // subregions.
2471 if (RN->isSubRegion()) {
2472 Region *SubRegion = RN->getNodeAs<Region>();
2473 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002474 if (!buildDomainsWithBranchConstraints(SubRegion, SD, DT, LI))
2475 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002476 continue;
2477 }
2478 }
2479
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002480 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002481 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002482
Johannes Doerfert96425c22015-08-30 21:13:53 +00002483 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002484 TerminatorInst *TI = BB->getTerminator();
2485
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002486 if (isa<UnreachableInst>(TI))
2487 continue;
2488
Johannes Doerfertf5673802015-10-01 23:48:18 +00002489 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002490 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002491 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002492
Johannes Doerfert642594a2016-04-04 07:57:39 +00002493 auto *BBLoop = getRegionNodeLoop(RN, LI);
2494 // Propagate the domain from BB directly to blocks that have a superset
2495 // domain, at the moment only region exit nodes of regions that start in BB.
2496 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, SD,
2497 LI);
2498
2499 // If all successors of BB have been set a domain through the propagation
2500 // above we do not need to build condition sets but can just skip this
2501 // block. However, it is important to note that this is a local property
2502 // with regards to the region @p R. To this end FinishedExitBlocks is a
2503 // local variable.
2504 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2505 return FinishedExitBlocks.count(SuccBB);
2506 };
2507 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2508 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002509
2510 // Build the condition sets for the successor nodes of the current region
2511 // node. If it is a non-affine subregion we will always execute the single
2512 // exit node, hence the single entry node domain is the condition set. For
2513 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002514 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002515 if (RN->isSubRegion())
2516 ConditionSets.push_back(isl_set_copy(Domain));
2517 else
Johannes Doerfert171b92f2016-04-19 14:53:13 +00002518 buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002519
2520 // Now iterate over the successors and set their initial domain based on
2521 // their condition set. We skip back edges here and have to be careful when
2522 // we leave a loop not to keep constraints over a dimension that doesn't
2523 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002524 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002525 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002526 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002527 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002528
Johannes Doerfert535de032016-04-19 14:49:05 +00002529 auto *SuccStmt = getStmtFor(SuccBB);
2530 // Skip blocks outside the region.
2531 if (!SuccStmt) {
2532 isl_set_free(CondSet);
2533 continue;
2534 }
2535
Johannes Doerfert642594a2016-04-04 07:57:39 +00002536 // If we propagate the domain of some block to "SuccBB" we do not have to
2537 // adjust the domain.
2538 if (FinishedExitBlocks.count(SuccBB)) {
2539 isl_set_free(CondSet);
2540 continue;
2541 }
2542
Johannes Doerfert96425c22015-08-30 21:13:53 +00002543 // Skip back edges.
2544 if (DT.dominates(SuccBB, BB)) {
2545 isl_set_free(CondSet);
2546 continue;
2547 }
2548
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002549 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002550 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002551
2552 // Set the domain for the successor or merge it with an existing domain in
2553 // case there are multiple paths (without loop back edges) to the
2554 // successor block.
2555 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002556
Johannes Doerferta3519512016-04-23 13:02:23 +00002557 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002558 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002559 } else {
2560 // Initialize the invalid domain.
2561 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2562 SuccDomain = CondSet;
2563 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002564
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002565 // Check if the maximal number of domain conjuncts was reached.
2566 // In case this happens we will clean up and bail.
Johannes Doerfert15194912016-04-04 07:59:41 +00002567 if (isl_set_n_basic_set(SuccDomain) < MaxConjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002568 continue;
2569
2570 invalidate(COMPLEXITY, DebugLoc());
2571 while (++u < ConditionSets.size())
2572 isl_set_free(ConditionSets[u]);
2573 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002574 }
2575 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002576
2577 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002578}
2579
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00002580__isl_give isl_set *Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2581 isl_set *Domain,
2582 ScopDetection &SD,
2583 DominatorTree &DT,
2584 LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002585 // If @p BB is the ScopEntry we are done
2586 if (R.getEntry() == BB)
2587 return isl_set_universe(isl_set_get_space(Domain));
2588
2589 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2590 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2591
2592 // The region info of this function.
2593 auto &RI = *R.getRegionInfo();
2594
2595 auto *BBLoop = getFirstNonBoxedLoopFor(BB, LI, BoxedLoops);
2596
2597 // A domain to collect all predecessor domains, thus all conditions under
2598 // which the block is executed. To this end we start with the empty domain.
2599 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2600
2601 // Set of regions of which the entry block domain has been propagated to BB.
2602 // all predecessors inside any of the regions can be skipped.
2603 SmallSet<Region *, 8> PropagatedRegions;
2604
2605 for (auto *PredBB : predecessors(BB)) {
2606 // Skip backedges.
2607 if (DT.dominates(BB, PredBB))
2608 continue;
2609
2610 // If the predecessor is in a region we used for propagation we can skip it.
2611 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2612 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2613 PredBBInRegion)) {
2614 continue;
2615 }
2616
2617 // Check if there is a valid region we can use for propagation, thus look
2618 // for a region that contains the predecessor and has @p BB as exit block.
2619 auto *PredR = RI.getRegionFor(PredBB);
2620 while (PredR->getExit() != BB && !PredR->contains(BB))
2621 PredR->getParent();
2622
2623 // If a valid region for propagation was found use the entry of that region
2624 // for propagation, otherwise the PredBB directly.
2625 if (PredR->getExit() == BB) {
2626 PredBB = PredR->getEntry();
2627 PropagatedRegions.insert(PredR);
2628 }
2629
Johannes Doerfert41cda152016-04-08 10:32:26 +00002630 auto *PredBBDom = getDomainConditions(PredBB);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002631 auto *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, BoxedLoops);
2632 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2633
2634 PredDom = isl_set_union(PredDom, PredBBDom);
2635 }
2636
2637 return PredDom;
2638}
2639
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002640void Scop::propagateDomainConstraints(Region *R, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002641 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002642 // Iterate over the region R and propagate the domain constrains from the
2643 // predecessors to the current node. In contrast to the
2644 // buildDomainsWithBranchConstraints function, this one will pull the domain
2645 // information from the predecessors instead of pushing it to the successors.
2646 // Additionally, we assume the domains to be already present in the domain
2647 // map here. However, we iterate again in reverse post order so we know all
2648 // predecessors have been visited before a block or non-affine subregion is
2649 // visited.
2650
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002651 ReversePostOrderTraversal<Region *> RTraversal(R);
2652 for (auto *RN : RTraversal) {
2653
2654 // Recurse for affine subregions but go on for basic blocks and non-affine
2655 // subregions.
2656 if (RN->isSubRegion()) {
2657 Region *SubRegion = RN->getNodeAs<Region>();
2658 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002659 propagateDomainConstraints(SubRegion, SD, DT, LI);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002660 continue;
2661 }
2662 }
2663
2664 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002665 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002666 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002667
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002668 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002669 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, SD, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002670 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002671 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002672
Johannes Doerfert642594a2016-04-04 07:57:39 +00002673 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002674 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002675 addLoopBoundsToHeaderDomain(BBLoop, LI);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002676
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002677 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002678 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002679 IsOptimized = true;
2680 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002681 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2682 AS_RESTRICTION);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002683 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002684 }
2685}
2686
2687/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2688/// is incremented by one and all other dimensions are equal, e.g.,
2689/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2690/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2691static __isl_give isl_map *
2692createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2693 auto *MapSpace = isl_space_map_from_set(SetSpace);
2694 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2695 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2696 if (u != Dim)
2697 NextIterationMap =
2698 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2699 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2700 C = isl_constraint_set_constant_si(C, 1);
2701 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2702 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2703 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2704 return NextIterationMap;
2705}
2706
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002707void Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002708 int LoopDepth = getRelativeLoopDepth(L);
2709 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002710
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002711 BasicBlock *HeaderBB = L->getHeader();
2712 assert(DomainMap.count(HeaderBB));
2713 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002714
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002715 isl_map *NextIterationMap =
2716 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002717
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002718 isl_set *UnionBackedgeCondition =
2719 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002720
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002721 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2722 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002723
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002724 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002725
2726 // If the latch is only reachable via error statements we skip it.
2727 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2728 if (!LatchBBDom)
2729 continue;
2730
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002731 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002732
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002733 TerminatorInst *TI = LatchBB->getTerminator();
2734 BranchInst *BI = dyn_cast<BranchInst>(TI);
2735 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002736 BackedgeCondition = isl_set_copy(LatchBBDom);
2737 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002738 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002739 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00002740 buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
2741 ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002742
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002743 // Free the non back edge condition set as we do not need it.
2744 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002745
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002746 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002747 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002748
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002749 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2750 assert(LatchLoopDepth >= LoopDepth);
2751 BackedgeCondition =
2752 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2753 LatchLoopDepth - LoopDepth);
2754 UnionBackedgeCondition =
2755 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002756 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002757
2758 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2759 for (int i = 0; i < LoopDepth; i++)
2760 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2761
2762 isl_set *UnionBackedgeConditionComplement =
2763 isl_set_complement(UnionBackedgeCondition);
2764 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2765 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2766 UnionBackedgeConditionComplement =
2767 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2768 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2769 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2770
2771 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2772 HeaderBBDom = Parts.second;
2773
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002774 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2775 // the bounded assumptions to the context as they are already implied by the
2776 // <nsw> tag.
2777 if (Affinator.hasNSWAddRecForLoop(L)) {
2778 isl_set_free(Parts.first);
2779 return;
2780 }
2781
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002782 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002783 recordAssumption(INFINITELOOP, UnboundedCtx,
2784 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002785}
2786
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002787void Scop::buildAliasChecks(AliasAnalysis &AA) {
2788 if (!PollyUseRuntimeAliasChecks)
2789 return;
2790
2791 if (buildAliasGroups(AA))
2792 return;
2793
2794 // If a problem occurs while building the alias groups we need to delete
2795 // this SCoP and pretend it wasn't valid in the first place. To this end
2796 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002797 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002798
2799 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2800 << " could not be created as the number of parameters involved "
2801 "is too high. The SCoP will be "
2802 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2803 "the maximal number of parameters but be advised that the "
2804 "compile time might increase exponentially.\n\n");
2805}
2806
Johannes Doerfert9143d672014-09-27 11:02:39 +00002807bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002808 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002809 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002810 // for all memory accesses inside the SCoP.
2811 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002812 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002813 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002814 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002815 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002816 // if their access domains intersect, otherwise they are in different
2817 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002818 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002819 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002820 // and maximal accesses to each array of a group in read only and non
2821 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002822 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2823
2824 AliasSetTracker AST(AA);
2825
2826 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002827 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002828 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002829
2830 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002831 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002832 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2833 isl_set_free(StmtDomain);
2834 if (StmtDomainEmpty)
2835 continue;
2836
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002837 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002838 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002839 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002840 if (!MA->isRead())
2841 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002842 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00002843 if (MA->isRead() && isa<MemTransferInst>(Acc))
2844 PtrToAcc[cast<MemTransferInst>(Acc)->getSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00002845 else
2846 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002847 AST.add(Acc);
2848 }
2849 }
2850
2851 SmallVector<AliasGroupTy, 4> AliasGroups;
2852 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002853 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002854 continue;
2855 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00002856 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00002857 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00002858 if (AG.size() < 2)
2859 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002860 AliasGroups.push_back(std::move(AG));
2861 }
2862
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002863 // Split the alias groups based on their domain.
2864 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2865 AliasGroupTy NewAG;
2866 AliasGroupTy &AG = AliasGroups[u];
2867 AliasGroupTy::iterator AGI = AG.begin();
2868 isl_set *AGDomain = getAccessDomain(*AGI);
2869 while (AGI != AG.end()) {
2870 MemoryAccess *MA = *AGI;
2871 isl_set *MADomain = getAccessDomain(MA);
2872 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2873 NewAG.push_back(MA);
2874 AGI = AG.erase(AGI);
2875 isl_set_free(MADomain);
2876 } else {
2877 AGDomain = isl_set_union(AGDomain, MADomain);
2878 AGI++;
2879 }
2880 }
2881 if (NewAG.size() > 1)
2882 AliasGroups.push_back(std::move(NewAG));
2883 isl_set_free(AGDomain);
2884 }
2885
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002886 auto &F = *getRegion().getEntry()->getParent();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002887 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002888 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2889 for (AliasGroupTy &AG : AliasGroups) {
2890 NonReadOnlyBaseValues.clear();
2891 ReadOnlyPairs.clear();
2892
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002893 if (AG.size() < 2) {
2894 AG.clear();
2895 continue;
2896 }
2897
Johannes Doerfert13771732014-10-01 12:40:46 +00002898 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002899 emitOptimizationRemarkAnalysis(
2900 F.getContext(), DEBUG_TYPE, F,
2901 (*II)->getAccessInstruction()->getDebugLoc(),
2902 "Possibly aliasing pointer, use restrict keyword.");
2903
Johannes Doerfert13771732014-10-01 12:40:46 +00002904 Value *BaseAddr = (*II)->getBaseAddr();
2905 if (HasWriteAccess.count(BaseAddr)) {
2906 NonReadOnlyBaseValues.insert(BaseAddr);
2907 II++;
2908 } else {
2909 ReadOnlyPairs[BaseAddr].insert(*II);
2910 II = AG.erase(II);
2911 }
2912 }
2913
2914 // If we don't have read only pointers check if there are at least two
2915 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002916 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002917 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002918 continue;
2919 }
2920
2921 // If we don't have non read only pointers clear the alias group.
2922 if (NonReadOnlyBaseValues.empty()) {
2923 AG.clear();
2924 continue;
2925 }
2926
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00002927 // Check if we have non-affine accesses left, if so bail out as we cannot
2928 // generate a good access range yet.
2929 for (auto *MA : AG)
2930 if (!MA->isAffine()) {
2931 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
2932 return false;
2933 }
2934 for (auto &ReadOnlyPair : ReadOnlyPairs)
2935 for (auto *MA : ReadOnlyPair.second)
2936 if (!MA->isAffine()) {
2937 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
2938 return false;
2939 }
2940
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002941 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002942 MinMaxAliasGroups.emplace_back();
2943 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2944 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2945 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2946 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002947
2948 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002949
2950 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002951 for (MemoryAccess *MA : AG)
2952 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002953
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002954 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2955 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002956
2957 // Bail out if the number of values we need to compare is too large.
2958 // This is important as the number of comparisions grows quadratically with
2959 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002960 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2961 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002962 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002963
2964 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002965 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002966 Accesses = isl_union_map_empty(getParamSpace());
2967
2968 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2969 for (MemoryAccess *MA : ReadOnlyPair.second)
2970 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2971
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002972 Valid =
2973 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002974
2975 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002976 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002977 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002978
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002979 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002980}
2981
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002982/// @brief Get the smallest loop that contains @p R but is not in @p R.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002983static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002984 // Start with the smallest loop containing the entry and expand that
2985 // loop until it contains all blocks in the region. If there is a loop
2986 // containing all blocks in the region check if it is itself contained
2987 // and if so take the parent loop as it will be the smallest containing
2988 // the region but not contained by it.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002989 Loop *L = LI.getLoopFor(R.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002990 while (L) {
2991 bool AllContained = true;
2992 for (auto *BB : R.blocks())
2993 AllContained &= L->contains(BB);
2994 if (AllContained)
2995 break;
2996 L = L->getParentLoop();
2997 }
2998
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002999 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
3000}
3001
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00003002static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
3003 ScopDetection &SD) {
3004
3005 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
3006
Johannes Doerferte3da05a2014-11-01 00:12:13 +00003007 unsigned MinLD = INT_MAX, MaxLD = 0;
3008 for (BasicBlock *BB : R.blocks()) {
3009 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00003010 if (!R.contains(L))
3011 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00003012 if (BoxedLoops && BoxedLoops->count(L))
3013 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00003014 unsigned LD = L->getLoopDepth();
3015 MinLD = std::min(MinLD, LD);
3016 MaxLD = std::max(MaxLD, LD);
3017 }
3018 }
3019
3020 // Handle the case that there is no loop in the SCoP first.
3021 if (MaxLD == 0)
3022 return 1;
3023
3024 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
3025 assert(MaxLD >= MinLD &&
3026 "Maximal loop depth was smaller than mininaml loop depth?");
3027 return MaxLD - MinLD + 1;
3028}
3029
Michael Kruse09eb4452016-03-03 22:10:47 +00003030Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
3031 unsigned MaxLoopDepth)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00003032 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003033 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003034 MaxLoopDepth(MaxLoopDepth), IslCtx(isl_ctx_alloc(), isl_ctx_free),
3035 Context(nullptr), Affinator(this, LI), AssumedContext(nullptr),
3036 InvalidContext(nullptr), Schedule(nullptr) {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003037 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003038 buildContext();
3039}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003040
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00003041void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003042 DominatorTree &DT, LoopInfo &LI) {
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003043 buildInvariantEquivalenceClasses(SD);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003044
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003045 if (!buildDomains(&R, SD, DT, LI))
3046 return;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003047
Johannes Doerfertff68f462016-04-19 14:49:42 +00003048 addUserAssumptions(AC, DT, LI);
3049
Michael Krusecac948e2015-10-02 13:53:07 +00003050 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00003051 // Exit early in case there are no executable statements left in this scop.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003052 simplifySCoP(true, DT, LI);
Michael Kruseafe06702015-10-02 16:33:27 +00003053 if (Stmts.empty())
3054 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003055
Michael Krusecac948e2015-10-02 13:53:07 +00003056 // The ScopStmts now have enough information to initialize themselves.
3057 for (ScopStmt &Stmt : Stmts)
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003058 Stmt.init(SD);
Michael Krusecac948e2015-10-02 13:53:07 +00003059
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003060 buildSchedule(SD, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00003061
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003062 if (!hasFeasibleRuntimeContext())
Tobias Grosser8286b832015-11-02 11:29:32 +00003063 return;
3064
3065 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00003066 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00003067 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00003068 addUserContext();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003069
3070 // After the context was fully constructed, thus all our knowledge about
3071 // the parameters is in there, we add all recorded assumptions to the
3072 // assumed/invalid context.
3073 addRecordedAssumptions();
3074
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003075 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003076 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003077
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003078 hoistInvariantLoads(SD);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003079 verifyInvariantLoads(SD);
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003080 simplifySCoP(false, DT, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00003081}
3082
3083Scop::~Scop() {
3084 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003085 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003086 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003087 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003088
Johannes Doerfert96425c22015-08-30 21:13:53 +00003089 for (auto It : DomainMap)
3090 isl_set_free(It.second);
3091
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003092 for (auto &AS : RecordedAssumptions)
3093 isl_set_free(AS.Set);
3094
Johannes Doerfertb164c792014-09-18 11:17:17 +00003095 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003096 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003097 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003098 isl_pw_multi_aff_free(MMA.first);
3099 isl_pw_multi_aff_free(MMA.second);
3100 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003101 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003102 isl_pw_multi_aff_free(MMA.first);
3103 isl_pw_multi_aff_free(MMA.second);
3104 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003105 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003106
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003107 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003108 isl_set_free(std::get<2>(IAClass));
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003109
3110 // Explicitly release all Scop objects and the underlying isl objects before
3111 // we relase the isl context.
3112 Stmts.clear();
3113 ScopArrayInfoMap.clear();
3114 AccFuncMap.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003115}
3116
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003117void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003118 // Check all array accesses for each base pointer and find a (virtual) element
3119 // size for the base pointer that divides all access functions.
3120 for (auto &Stmt : *this)
3121 for (auto *Access : Stmt) {
3122 if (!Access->isArrayKind())
3123 continue;
3124 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(),
3125 ScopArrayInfo::MK_Array)];
3126 if (SAI->getNumberOfDimensions() != 1)
3127 continue;
3128 unsigned DivisibleSize = SAI->getElemSizeInBytes();
3129 auto *Subscript = Access->getSubscript(0);
3130 while (!isDivisible(Subscript, DivisibleSize, *SE))
3131 DivisibleSize /= 2;
3132 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
3133 SAI->updateElementType(Ty);
3134 }
3135
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003136 for (auto &Stmt : *this)
3137 for (auto &Access : Stmt)
3138 Access->updateDimensionality();
3139}
3140
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003141void Scop::simplifySCoP(bool RemoveIgnoredStmts, DominatorTree &DT,
3142 LoopInfo &LI) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003143 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3144 ScopStmt &Stmt = *StmtIt;
Michael Kruse7b5caa42016-02-24 22:08:28 +00003145 RegionNode *RN = Stmt.getRegionNode();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003146
Johannes Doerferteca9e892015-11-03 16:54:49 +00003147 bool RemoveStmt = StmtIt->isEmpty();
3148 if (!RemoveStmt)
Michael Kruse375cb5f2016-02-24 22:08:24 +00003149 RemoveStmt = isl_set_is_empty(DomainMap[Stmt.getEntryBlock()]);
Johannes Doerferteca9e892015-11-03 16:54:49 +00003150 if (!RemoveStmt)
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003151 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN, DT, LI));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003152
Johannes Doerferteca9e892015-11-03 16:54:49 +00003153 // Remove read only statements only after invariant loop hoisting.
3154 if (!RemoveStmt && !RemoveIgnoredStmts) {
3155 bool OnlyRead = true;
3156 for (MemoryAccess *MA : Stmt) {
3157 if (MA->isRead())
3158 continue;
3159
3160 OnlyRead = false;
3161 break;
3162 }
3163
3164 RemoveStmt = OnlyRead;
3165 }
3166
3167 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00003168 // Remove the statement because it is unnecessary.
3169 if (Stmt.isRegionStmt())
3170 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3171 StmtMap.erase(BB);
3172 else
3173 StmtMap.erase(Stmt.getBasicBlock());
3174
3175 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003176 continue;
3177 }
3178
Michael Krusecac948e2015-10-02 13:53:07 +00003179 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003180 }
3181}
3182
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003183const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
3184 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3185 if (!LInst)
3186 return nullptr;
3187
3188 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3189 LInst = cast<LoadInst>(Rep);
3190
Johannes Doerfert96e54712016-02-07 17:30:13 +00003191 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003192 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003193 for (auto &IAClass : InvariantEquivClasses) {
3194 if (PointerSCEV != std::get<0>(IAClass) || Ty != std::get<3>(IAClass))
3195 continue;
3196
3197 auto &MAs = std::get<1>(IAClass);
3198 for (auto *MA : MAs)
3199 if (MA->getAccessInstruction() == Val)
3200 return &IAClass;
3201 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003202
3203 return nullptr;
3204}
3205
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003206/// @brief Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003207static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
3208 bool MAInvalidCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003209 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3210 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3211 // TODO: We can provide more information for better but more expensive
3212 // results.
3213 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3214 LInst->getAlignment(), DL))
3215 return false;
3216
3217 // If a dereferencable load is in a statement that is modeled precisely we can
3218 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003219 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003220 return true;
3221
3222 // Even if the statement is not modeled precisely we can hoist the load if it
3223 // does not involve any parameters that might have been specilized by the
3224 // statement domain.
3225 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3226 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3227 return false;
3228 return true;
3229}
3230
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003231void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
3232
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003233 if (InvMAs.empty())
3234 return;
3235
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003236 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003237 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003238
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003239 // Get the context under which the statement is executed but remove the error
3240 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003241 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003242 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003243
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003244 if (isl_set_n_basic_set(DomainCtx) >= MaxConjunctsInDomain) {
3245 auto *AccInst = InvMAs.front()->getAccessInstruction();
3246 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3247 isl_set_free(DomainCtx);
3248 return;
3249 }
3250
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003251 // Project out all parameters that relate to loads in the statement. Otherwise
3252 // we could have cyclic dependences on the constraints under which the
3253 // hoisted loads are executed and we could not determine an order in which to
3254 // pre-load them. This happens because not only lower bounds are part of the
3255 // domain but also upper bounds.
3256 for (MemoryAccess *MA : InvMAs) {
3257 Instruction *AccInst = MA->getAccessInstruction();
3258 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003259 SetVector<Value *> Values;
3260 for (const SCEV *Parameter : Parameters) {
3261 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003262 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003263 if (!Values.count(AccInst))
3264 continue;
3265
3266 if (isl_id *ParamId = getIdForParam(Parameter)) {
3267 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
3268 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
3269 isl_id_free(ParamId);
3270 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003271 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003272 }
3273 }
3274
3275 for (MemoryAccess *MA : InvMAs) {
3276 // Check for another invariant access that accesses the same location as
3277 // MA and if found consolidate them. Otherwise create a new equivalence
3278 // class at the end of InvariantEquivClasses.
3279 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003280 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003281 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3282
Johannes Doerfert85676e32016-04-23 14:32:34 +00003283 auto *MAInvalidCtx = MA->getInvalidContext();
3284 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3285
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003286 isl_set *MACtx;
3287 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003288 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003289 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003290 isl_set_free(MAInvalidCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003291 } else {
3292 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003293 MACtx = isl_set_subtract(MACtx, MAInvalidCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003294 MACtx = isl_set_gist_params(MACtx, getContext());
3295 }
3296
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003297 bool Consolidated = false;
3298 for (auto &IAClass : InvariantEquivClasses) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00003299 if (PointerSCEV != std::get<0>(IAClass) || Ty != std::get<3>(IAClass))
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003300 continue;
3301
Johannes Doerfertdf880232016-03-03 12:26:58 +00003302 // If the pointer and the type is equal check if the access function wrt.
3303 // to the domain is equal too. It can happen that the domain fixes
3304 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003305 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003306 // create a new invariant load equivalence class.
3307 auto &MAs = std::get<1>(IAClass);
3308 if (!MAs.empty()) {
3309 auto *LastMA = MAs.front();
3310
3311 auto *AR = isl_map_range(MA->getAccessRelation());
3312 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3313 bool SameAR = isl_set_is_equal(AR, LastAR);
3314 isl_set_free(AR);
3315 isl_set_free(LastAR);
3316
3317 if (!SameAR)
3318 continue;
3319 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003320
3321 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003322 MAs.push_front(MA);
3323
Johannes Doerfertdf880232016-03-03 12:26:58 +00003324 Consolidated = true;
3325
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003326 // Unify the execution context of the class and this statement.
3327 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003328 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003329 IAClassDomainCtx =
3330 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003331 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003332 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003333 break;
3334 }
3335
3336 if (Consolidated)
3337 continue;
3338
3339 // If we did not consolidate MA, thus did not find an equivalence class
3340 // for it, we create a new one.
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003341 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA}, MACtx,
3342 Ty);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003343 }
3344
3345 isl_set_free(DomainCtx);
3346}
3347
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003348bool Scop::isHoistableAccess(MemoryAccess *Access,
3349 __isl_keep isl_union_map *Writes) {
3350 // TODO: Loads that are not loop carried, hence are in a statement with
3351 // zero iterators, are by construction invariant, though we
3352 // currently "hoist" them anyway. This is necessary because we allow
3353 // them to be treated as parameters (e.g., in conditions) and our code
3354 // generation would otherwise use the old value.
3355
3356 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003357 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003358
3359 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
3360 return false;
3361
3362 // Skip accesses that have an invariant base pointer which is defined but
3363 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3364 // returns a pointer that is used as a base address. However, as we want
3365 // to hoist indirect pointers, we allow the base pointer to be defined in
3366 // the region if it is also a memory access. Each ScopArrayInfo object
3367 // that has a base pointer origin has a base pointer that is loaded and
3368 // that it is invariant, thus it will be hoisted too. However, if there is
3369 // no base pointer origin we check that the base pointer is defined
3370 // outside the region.
3371 const ScopArrayInfo *SAI = Access->getScopArrayInfo();
Johannes Doerfert4cf15802016-02-15 12:42:05 +00003372 auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr());
3373 if (SAI->getBasePtrOriginSAI()) {
3374 assert(BasePtrInst && R.contains(BasePtrInst));
3375 if (!isa<LoadInst>(BasePtrInst))
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003376 return false;
Michael Kruse6f7721f2016-02-24 22:08:19 +00003377 auto *BasePtrStmt = getStmtFor(BasePtrInst);
Johannes Doerfert4cf15802016-02-15 12:42:05 +00003378 assert(BasePtrStmt);
3379 auto *BasePtrMA = BasePtrStmt->getArrayAccessOrNULLFor(BasePtrInst);
3380 if (BasePtrMA && !isHoistableAccess(BasePtrMA, Writes))
3381 return false;
3382 } else if (BasePtrInst && R.contains(BasePtrInst))
3383 return false;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003384
3385 // Skip accesses in non-affine subregions as they might not be executed
3386 // under the same condition as the entry of the non-affine subregion.
3387 if (BB != Access->getAccessInstruction()->getParent())
3388 return false;
3389
3390 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003391 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003392
3393 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3394 Stmt.getNumIterators())) {
3395 isl_map_free(AccessRelation);
3396 return false;
3397 }
3398
3399 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3400 isl_set *AccessRange = isl_map_range(AccessRelation);
3401
3402 isl_union_map *Written = isl_union_map_intersect_range(
3403 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
3404 bool IsWritten = !isl_union_map_is_empty(Written);
3405 isl_union_map_free(Written);
3406
3407 if (IsWritten)
3408 return false;
3409
3410 return true;
3411}
3412
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003413void Scop::verifyInvariantLoads(ScopDetection &SD) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003414 auto &RIL = *SD.getRequiredInvariantLoads(&getRegion());
3415 for (LoadInst *LI : RIL) {
3416 assert(LI && getRegion().contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003417 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003418 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003419 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3420 return;
3421 }
3422 }
3423}
3424
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003425void Scop::hoistInvariantLoads(ScopDetection &SD) {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003426 if (!PollyInvariantLoadHoisting)
3427 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003428
Tobias Grosser0865e7752016-02-29 07:29:42 +00003429 isl_union_map *Writes = getWrites();
3430 for (ScopStmt &Stmt : *this) {
3431 MemoryAccessList InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003432
Tobias Grosser0865e7752016-02-29 07:29:42 +00003433 for (MemoryAccess *Access : Stmt)
3434 if (isHoistableAccess(Access, Writes))
3435 InvariantAccesses.push_front(Access);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003436
Tobias Grosser0865e7752016-02-29 07:29:42 +00003437 // We inserted invariant accesses always in the front but need them to be
3438 // sorted in a "natural order". The statements are already sorted in
3439 // reverse post order and that suffices for the accesses too. The reason
3440 // we require an order in the first place is the dependences between
3441 // invariant loads that can be caused by indirect loads.
3442 InvariantAccesses.reverse();
3443
3444 // Transfer the memory access from the statement to the SCoP.
3445 Stmt.removeMemoryAccesses(InvariantAccesses);
3446 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003447 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003448 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003449}
3450
Johannes Doerfert80ef1102014-11-07 08:31:31 +00003451const ScopArrayInfo *
Tobias Grossercc779502016-02-02 13:22:54 +00003452Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003453 ArrayRef<const SCEV *> Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00003454 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003455 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003456 if (!SAI) {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003457 auto &DL = getRegion().getEntry()->getModule()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003458 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003459 DL, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003460 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003461 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003462 // In case of mismatching array sizes, we bail out by setting the run-time
3463 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003464 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003465 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003466 }
Tobias Grosserab671442015-05-23 05:58:27 +00003467 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003468}
3469
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003470const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00003471 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003472 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003473 assert(SAI && "No ScopArrayInfo available for this base pointer");
3474 return SAI;
3475}
3476
Tobias Grosser74394f02013-01-14 22:40:23 +00003477std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003478
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003479std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003480 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003481 return stringFromIslObj(AssumedContext);
3482}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003483
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003484std::string Scop::getInvalidContextStr() const {
3485 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003486}
Tobias Grosser75805372011-04-29 06:27:02 +00003487
3488std::string Scop::getNameStr() const {
3489 std::string ExitName, EntryName;
3490 raw_string_ostream ExitStr(ExitName);
3491 raw_string_ostream EntryStr(EntryName);
3492
Tobias Grosserf240b482014-01-09 10:42:15 +00003493 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003494 EntryStr.str();
3495
3496 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003497 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003498 ExitStr.str();
3499 } else
3500 ExitName = "FunctionExit";
3501
3502 return EntryName + "---" + ExitName;
3503}
3504
Tobias Grosser74394f02013-01-14 22:40:23 +00003505__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003506__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003507 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003508}
3509
Tobias Grossere86109f2013-10-29 21:05:49 +00003510__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003511 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003512 return isl_set_copy(AssumedContext);
3513}
3514
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003515bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003516 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003517 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00003518 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3519 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
3520 isl_set_is_subset(PositiveContext, NegativeContext));
3521 isl_set_free(PositiveContext);
3522 if (!IsFeasible) {
3523 isl_set_free(NegativeContext);
3524 return false;
3525 }
3526
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003527 auto *DomainContext = isl_union_set_params(getDomains());
3528 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00003529 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003530 isl_set_free(NegativeContext);
3531 isl_set_free(DomainContext);
3532
Johannes Doerfert43788c52015-08-20 05:58:56 +00003533 return IsFeasible;
3534}
3535
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003536static std::string toString(AssumptionKind Kind) {
3537 switch (Kind) {
3538 case ALIASING:
3539 return "No-aliasing";
3540 case INBOUNDS:
3541 return "Inbounds";
3542 case WRAPPING:
3543 return "No-overflows";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003544 case COMPLEXITY:
3545 return "Low complexity";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003546 case ERRORBLOCK:
3547 return "No-error";
3548 case INFINITELOOP:
3549 return "Finite loop";
3550 case INVARIANTLOAD:
3551 return "Invariant load";
3552 case DELINEARIZATION:
3553 return "Delinearization";
3554 }
3555 llvm_unreachable("Unknown AssumptionKind!");
3556}
3557
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003558bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3559 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert2f705842016-04-12 16:09:44 +00003560 if (PollyRemarksMinimal) {
3561 if (Sign == AS_ASSUMPTION) {
3562 if (isl_set_is_subset(Context, Set))
3563 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003564
Johannes Doerfert2f705842016-04-12 16:09:44 +00003565 if (isl_set_is_subset(AssumedContext, Set))
3566 return false;
3567 } else {
3568 if (isl_set_is_disjoint(Set, Context))
3569 return false;
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003570
Johannes Doerfert2f705842016-04-12 16:09:44 +00003571 if (isl_set_is_subset(Set, InvalidContext))
3572 return false;
3573 }
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003574 }
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003575
3576 auto &F = *getRegion().getEntry()->getParent();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003577 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
3578 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003579 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003580 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003581}
3582
3583void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003584 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003585 // Simplify the assumptions/restrictions first.
3586 Set = isl_set_gist_params(Set, getContext());
3587
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003588 if (!trackAssumption(Kind, Set, Loc, Sign)) {
3589 isl_set_free(Set);
3590 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003591 }
3592
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003593 if (Sign == AS_ASSUMPTION) {
3594 AssumedContext = isl_set_intersect(AssumedContext, Set);
3595 AssumedContext = isl_set_coalesce(AssumedContext);
3596 } else {
3597 InvalidContext = isl_set_union(InvalidContext, Set);
3598 InvalidContext = isl_set_coalesce(InvalidContext);
3599 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003600}
3601
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003602void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003603 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
3604 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003605}
3606
3607void Scop::addRecordedAssumptions() {
3608 while (!RecordedAssumptions.empty()) {
3609 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003610
3611 isl_set *S = AS.Set;
3612 // If a basic block was given use its domain to simplify the assumption.
3613 if (AS.BB)
3614 S = isl_set_params(isl_set_intersect(S, getDomainConditions(AS.BB)));
3615
3616 addAssumption(AS.Kind, S, AS.Loc, AS.Sign);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003617 }
3618}
3619
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003620void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003621 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003622}
3623
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003624__isl_give isl_set *Scop::getInvalidContext() const {
3625 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003626}
3627
Tobias Grosser75805372011-04-29 06:27:02 +00003628void Scop::printContext(raw_ostream &OS) const {
3629 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003630 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003631
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003632 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003633 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003634
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003635 OS.indent(4) << "Invalid Context:\n";
3636 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003637
Tobias Grosser083d3d32014-06-28 08:59:45 +00003638 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00003639 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00003640 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
3641 }
Tobias Grosser75805372011-04-29 06:27:02 +00003642}
3643
Johannes Doerfertb164c792014-09-18 11:17:17 +00003644void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003645 int noOfGroups = 0;
3646 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003647 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003648 noOfGroups += 1;
3649 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003650 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003651 }
3652
Tobias Grosserbb853c22015-07-25 12:31:03 +00003653 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003654 if (MinMaxAliasGroups.empty()) {
3655 OS.indent(8) << "n/a\n";
3656 return;
3657 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003658
Tobias Grosserbb853c22015-07-25 12:31:03 +00003659 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003660
3661 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003662 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003663 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003664 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003665 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3666 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003667 }
3668 OS << " ]]\n";
3669 }
3670
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003671 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003672 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003673 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003674 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003675 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3676 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003677 }
3678 OS << " ]]\n";
3679 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003680 }
3681}
3682
Tobias Grosser75805372011-04-29 06:27:02 +00003683void Scop::printStatements(raw_ostream &OS) const {
3684 OS << "Statements {\n";
3685
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003686 for (const ScopStmt &Stmt : *this)
3687 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003688
3689 OS.indent(4) << "}\n";
3690}
3691
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003692void Scop::printArrayInfo(raw_ostream &OS) const {
3693 OS << "Arrays {\n";
3694
Tobias Grosserab671442015-05-23 05:58:27 +00003695 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003696 Array.second->print(OS);
3697
3698 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003699
3700 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3701
3702 for (auto &Array : arrays())
3703 Array.second->print(OS, /* SizeAsPwAff */ true);
3704
3705 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003706}
3707
Tobias Grosser75805372011-04-29 06:27:02 +00003708void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00003709 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
3710 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003711 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003712 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003713 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003714 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003715 const auto &MAs = std::get<1>(IAClass);
3716 if (MAs.empty()) {
3717 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003718 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003719 MAs.front()->print(OS);
3720 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003721 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003722 }
3723 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003724 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003725 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003726 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003727 printStatements(OS.indent(4));
3728}
3729
3730void Scop::dump() const { print(dbgs()); }
3731
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003732isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00003733
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003734__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003735 // First try to use the SCEVAffinator to generate a piecewise defined
3736 // affine function from @p E in the context of @p BB. If that tasks becomes to
3737 // complex the affinator might return a nullptr. In such a case we invalidate
3738 // the SCoP and return a dummy value. This way we do not need to add error
3739 // handling cdoe to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003740 auto PWAC = Affinator.getPwAff(E, BB);
3741 if (PWAC.first)
3742 return PWAC;
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003743
3744 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
3745 invalidate(COMPLEXITY, DL);
3746 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003747}
3748
Tobias Grosser808cd692015-07-14 09:33:13 +00003749__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003750 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003751
Tobias Grosser808cd692015-07-14 09:33:13 +00003752 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003753 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003754
3755 return Domain;
3756}
3757
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003758__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
3759 PWACtx PWAC = getPwAff(E, BB);
3760 isl_set_free(PWAC.second);
3761 return PWAC.first;
3762}
3763
Tobias Grossere5a35142015-11-12 14:07:09 +00003764__isl_give isl_union_map *
3765Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3766 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003767
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003768 for (ScopStmt &Stmt : *this) {
3769 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003770 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003771 continue;
3772
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003773 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003774 isl_map *AccessDomain = MA->getAccessRelation();
3775 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003776 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003777 }
3778 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003779 return isl_union_map_coalesce(Accesses);
3780}
3781
3782__isl_give isl_union_map *Scop::getMustWrites() {
3783 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003784}
3785
3786__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003787 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003788}
3789
Tobias Grosser37eb4222014-02-20 21:43:54 +00003790__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003791 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003792}
3793
3794__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003795 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003796}
3797
Tobias Grosser2ac23382015-11-12 14:07:13 +00003798__isl_give isl_union_map *Scop::getAccesses() {
3799 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3800}
3801
Tobias Grosser808cd692015-07-14 09:33:13 +00003802__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00003803 auto *Tree = getScheduleTree();
3804 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00003805 isl_schedule_free(Tree);
3806 return S;
3807}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003808
Tobias Grosser808cd692015-07-14 09:33:13 +00003809__isl_give isl_schedule *Scop::getScheduleTree() const {
3810 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3811 getDomains());
3812}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003813
Tobias Grosser808cd692015-07-14 09:33:13 +00003814void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3815 auto *S = isl_schedule_from_domain(getDomains());
3816 S = isl_schedule_insert_partial_schedule(
3817 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3818 isl_schedule_free(Schedule);
3819 Schedule = S;
3820}
3821
3822void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3823 isl_schedule_free(Schedule);
3824 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003825}
3826
3827bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3828 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003829 for (ScopStmt &Stmt : *this) {
3830 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003831 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3832 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3833
3834 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3835 isl_union_set_free(StmtDomain);
3836 isl_union_set_free(NewStmtDomain);
3837 continue;
3838 }
3839
3840 Changed = true;
3841
3842 isl_union_set_free(StmtDomain);
3843 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3844
3845 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003846 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003847 isl_union_set_free(NewStmtDomain);
3848 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003849 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003850 }
3851 isl_union_set_free(Domain);
3852 return Changed;
3853}
3854
Tobias Grosser75805372011-04-29 06:27:02 +00003855ScalarEvolution *Scop::getSE() const { return SE; }
3856
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003857bool Scop::isIgnored(RegionNode *RN, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003858 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Michael Kruse6f7721f2016-02-24 22:08:19 +00003859 ScopStmt *Stmt = getStmtFor(RN);
Michael Krusea902ba62015-12-13 19:21:45 +00003860
3861 // If there is no stmt, then it already has been removed.
3862 if (!Stmt)
3863 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00003864
Johannes Doerfertf5673802015-10-01 23:48:18 +00003865 // Check if there are accesses contained.
Michael Krusea902ba62015-12-13 19:21:45 +00003866 if (Stmt->isEmpty())
Johannes Doerfertf5673802015-10-01 23:48:18 +00003867 return true;
3868
3869 // Check for reachability via non-error blocks.
3870 if (!DomainMap.count(BB))
3871 return true;
3872
3873 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003874 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003875 return true;
3876
3877 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003878}
3879
Tobias Grosser808cd692015-07-14 09:33:13 +00003880struct MapToDimensionDataTy {
3881 int N;
3882 isl_union_pw_multi_aff *Res;
3883};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003884
Tobias Grosser808cd692015-07-14 09:33:13 +00003885// @brief Create a function that maps the elements of 'Set' to its N-th
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003886// dimension and add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00003887//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003888// @param Set The input set.
3889// @param User->N The dimension to map to.
3890// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00003891//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003892// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00003893static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3894 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3895 int Dim;
3896 isl_space *Space;
3897 isl_pw_multi_aff *PMA;
3898
3899 Dim = isl_set_dim(Set, isl_dim_set);
3900 Space = isl_set_get_space(Set);
3901 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3902 Dim - Data->N);
3903 if (Data->N > 1)
3904 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3905 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3906
3907 isl_set_free(Set);
3908
3909 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003910}
3911
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003912// @brief Create an isl_multi_union_aff that defines an identity mapping
3913// from the elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003914//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003915// # Example:
3916//
3917// Domain: { A[i,j]; B[i,j,k] }
3918// N: 1
3919//
3920// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
3921//
3922// @param USet A union set describing the elements for which to generate a
3923// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00003924// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003925// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003926static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003927mapToDimension(__isl_take isl_union_set *USet, int N) {
3928 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00003929 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003930 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003931
Tobias Grosser808cd692015-07-14 09:33:13 +00003932 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00003933
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003934 auto *Space = isl_union_set_get_space(USet);
3935 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00003936
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003937 Data = {N, PwAff};
3938
3939 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00003940 (void)Res;
3941
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003942 assert(Res == isl_stat_ok);
3943
3944 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00003945 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3946}
3947
Tobias Grosser316b5b22015-11-11 19:28:14 +00003948void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003949 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003950 Stmts.emplace_back(*this, *BB);
Johannes Doerferta90943d2016-02-21 16:37:25 +00003951 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003952 StmtMap[BB] = Stmt;
3953 } else {
3954 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003955 Stmts.emplace_back(*this, *R);
Johannes Doerferta90943d2016-02-21 16:37:25 +00003956 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003957 for (BasicBlock *BB : R->blocks())
3958 StmtMap[BB] = Stmt;
3959 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003960}
3961
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003962void Scop::buildSchedule(ScopDetection &SD, LoopInfo &LI) {
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003963 Loop *L = getLoopSurroundingRegion(getRegion(), LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003964 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003965 buildSchedule(getRegion().getNode(), LoopStack, SD, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00003966 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
3967 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003968}
3969
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003970/// To generate a schedule for the elements in a Region we traverse the Region
3971/// in reverse-post-order and add the contained RegionNodes in traversal order
3972/// to the schedule of the loop that is currently at the top of the LoopStack.
3973/// For loop-free codes, this results in a correct sequential ordering.
3974///
3975/// Example:
3976/// bb1(0)
3977/// / \.
3978/// bb2(1) bb3(2)
3979/// \ / \.
3980/// bb4(3) bb5(4)
3981/// \ /
3982/// bb6(5)
3983///
3984/// Including loops requires additional processing. Whenever a loop header is
3985/// encountered, the corresponding loop is added to the @p LoopStack. Starting
3986/// from an empty schedule, we first process all RegionNodes that are within
3987/// this loop and complete the sequential schedule at this loop-level before
3988/// processing about any other nodes. To implement this
3989/// loop-nodes-first-processing, the reverse post-order traversal is
3990/// insufficient. Hence, we additionally check if the traversal yields
3991/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
3992/// These region-nodes are then queue and only traverse after the all nodes
3993/// within the current loop have been processed.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003994void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, ScopDetection &SD,
3995 LoopInfo &LI) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003996 Loop *OuterScopLoop = getLoopSurroundingRegion(getRegion(), LI);
3997
3998 ReversePostOrderTraversal<Region *> RTraversal(R);
3999 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4000 std::deque<RegionNode *> DelayList;
4001 bool LastRNWaiting = false;
4002
4003 // Iterate over the region @p R in reverse post-order but queue
4004 // sub-regions/blocks iff they are not part of the last encountered but not
4005 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4006 // that we queued the last sub-region/block from the reverse post-order
4007 // iterator. If it is set we have to explore the next sub-region/block from
4008 // the iterator (if any) to guarantee progress. If it is not set we first try
4009 // the next queued sub-region/blocks.
4010 while (!WorkList.empty() || !DelayList.empty()) {
4011 RegionNode *RN;
4012
4013 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4014 RN = WorkList.front();
4015 WorkList.pop_front();
4016 LastRNWaiting = false;
4017 } else {
4018 RN = DelayList.front();
4019 DelayList.pop_front();
4020 }
4021
4022 Loop *L = getRegionNodeLoop(RN, LI);
4023 if (!getRegion().contains(L))
4024 L = OuterScopLoop;
4025
Tobias Grosser151ae322016-04-03 19:36:52 +00004026 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004027 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004028 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004029 LastRNWaiting = true;
4030 DelayList.push_back(RN);
4031 continue;
4032 }
4033 LoopStack.push_back({L, nullptr, 0});
4034 }
Hongbin Zheng192f69a2016-02-13 15:12:54 +00004035 buildSchedule(RN, LoopStack, SD, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004036 }
4037
4038 return;
4039}
4040
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00004041void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00004042 ScopDetection &SD, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004043
Tobias Grosser8362c262016-01-06 15:30:06 +00004044 if (RN->isSubRegion()) {
4045 auto *LocalRegion = RN->getNodeAs<Region>();
4046 if (!SD.isNonAffineSubRegion(LocalRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00004047 buildSchedule(LocalRegion, LoopStack, SD, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004048 return;
4049 }
4050 }
Michael Kruse046dde42015-08-10 13:01:57 +00004051
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004052 auto &LoopData = LoopStack.back();
4053 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004054
Michael Kruse6f7721f2016-02-24 22:08:19 +00004055 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004056 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4057 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004058 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004059 }
4060
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004061 // Check if we just processed the last node in this loop. If we did, finalize
4062 // the loop by:
4063 //
4064 // - adding new schedule dimensions
4065 // - folding the resulting schedule into the parent loop schedule
4066 // - dropping the loop schedule from the LoopStack.
4067 //
4068 // Then continue to check surrounding loops, which might also have been
4069 // completed by this node.
4070 while (LoopData.L &&
4071 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004072 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004073 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004074
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004075 LoopStack.pop_back();
4076 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004077
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004078 if (Schedule) {
4079 auto *Domain = isl_schedule_get_domain(Schedule);
4080 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4081 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4082 NextLoopData.Schedule =
4083 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004084 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004085
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004086 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4087 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004088 }
Tobias Grosser75805372011-04-29 06:27:02 +00004089}
4090
Michael Kruse6f7721f2016-02-24 22:08:19 +00004091ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004092 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004093 if (StmtMapIt == StmtMap.end())
4094 return nullptr;
4095 return StmtMapIt->second;
4096}
4097
Michael Kruse6f7721f2016-02-24 22:08:19 +00004098ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4099 if (RN->isSubRegion())
4100 return getStmtFor(RN->getNodeAs<Region>());
4101 return getStmtFor(RN->getNodeAs<BasicBlock>());
4102}
4103
4104ScopStmt *Scop::getStmtFor(Region *R) const {
4105 ScopStmt *Stmt = getStmtFor(R->getEntry());
4106 assert(!Stmt || Stmt->getRegion() == R);
4107 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004108}
4109
Johannes Doerfert96425c22015-08-30 21:13:53 +00004110int Scop::getRelativeLoopDepth(const Loop *L) const {
4111 Loop *OuterLoop =
4112 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4113 if (!OuterLoop)
4114 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004115 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4116}
4117
Michael Krused868b5d2015-09-10 15:25:24 +00004118void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00004119 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00004120
4121 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
4122 // true, are not modeled as ordinary PHI nodes as they are not part of the
4123 // region. However, we model the operands in the predecessor blocks that are
4124 // part of the region as regular scalar accesses.
4125
4126 // If we can synthesize a PHI we can skip it, however only if it is in
4127 // the region. If it is not it can only be in the exit block of the region.
4128 // In this case we model the operands but not the PHI itself.
Michael Krusec7e0d9c2016-03-01 21:44:06 +00004129 auto *Scope = LI->getLoopFor(PHI->getParent());
4130 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R, Scope))
Michael Kruse7bf39442015-09-10 12:46:52 +00004131 return;
4132
4133 // PHI nodes are modeled as if they had been demoted prior to the SCoP
4134 // detection. Hence, the PHI is a load of a new memory location in which the
4135 // incoming value was written at the end of the incoming basic block.
4136 bool OnlyNonAffineSubRegionOperands = true;
4137 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
4138 Value *Op = PHI->getIncomingValue(u);
4139 BasicBlock *OpBB = PHI->getIncomingBlock(u);
4140
4141 // Do not build scalar dependences inside a non-affine subregion.
4142 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
4143 continue;
4144
4145 OnlyNonAffineSubRegionOperands = false;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004146 ensurePHIWrite(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00004147 }
4148
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004149 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
4150 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00004151 }
4152}
4153
Michael Kruse2e02d562016-02-06 09:19:40 +00004154void ScopInfo::buildScalarDependences(Instruction *Inst) {
4155 assert(!isa<PHINode>(Inst));
Michael Kruse7bf39442015-09-10 12:46:52 +00004156
Michael Kruse2e02d562016-02-06 09:19:40 +00004157 // Pull-in required operands.
4158 for (Use &Op : Inst->operands())
4159 ensureValueRead(Op.get(), Inst->getParent());
4160}
Michael Kruse7bf39442015-09-10 12:46:52 +00004161
Michael Kruse2e02d562016-02-06 09:19:40 +00004162void ScopInfo::buildEscapingDependences(Instruction *Inst) {
4163 Region *R = &scop->getRegion();
Michael Kruse7bf39442015-09-10 12:46:52 +00004164
Michael Kruse2e02d562016-02-06 09:19:40 +00004165 // Check for uses of this instruction outside the scop. Because we do not
4166 // iterate over such instructions and therefore did not "ensure" the existence
4167 // of a write, we must determine such use here.
4168 for (Use &U : Inst->uses()) {
4169 Instruction *UI = dyn_cast<Instruction>(U.getUser());
4170 if (!UI)
Michael Kruse7bf39442015-09-10 12:46:52 +00004171 continue;
4172
Michael Kruse2e02d562016-02-06 09:19:40 +00004173 BasicBlock *UseParent = getUseBlock(U);
4174 BasicBlock *UserParent = UI->getParent();
Michael Kruse7bf39442015-09-10 12:46:52 +00004175
Michael Kruse2e02d562016-02-06 09:19:40 +00004176 // An escaping value is either used by an instruction not within the scop,
4177 // or (when the scop region's exit needs to be simplified) by a PHI in the
4178 // scop's exit block. This is because region simplification before code
4179 // generation inserts new basic blocks before the PHI such that its incoming
4180 // blocks are not in the scop anymore.
4181 if (!R->contains(UseParent) ||
4182 (isa<PHINode>(UI) && UserParent == R->getExit() &&
4183 R->getExitingBlock())) {
4184 // At least one escaping use found.
4185 ensureValueWrite(Inst);
4186 break;
Michael Kruse7bf39442015-09-10 12:46:52 +00004187 }
4188 }
Michael Kruse7bf39442015-09-10 12:46:52 +00004189}
4190
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004191bool ScopInfo::buildAccessMultiDimFixed(
Michael Kruse70131d32016-01-27 17:09:17 +00004192 MemAccInst Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00004193 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
4194 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse70131d32016-01-27 17:09:17 +00004195 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004196 Type *ElementType = Val->getType();
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004197 Value *Address = Inst.getPointerOperand();
Tobias Grosser5fd8c092015-09-17 17:28:15 +00004198 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00004199 const SCEVUnknown *BasePointer =
4200 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004201 enum MemoryAccess::AccessType AccType =
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004202 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00004203
Michael Kruse37d136e2016-02-26 16:08:24 +00004204 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
4205 auto *Src = BitCast->getOperand(0);
4206 auto *SrcTy = Src->getType();
4207 auto *DstTy = BitCast->getType();
Johannes Doerfert41725a12016-04-08 19:20:03 +00004208 // Do not try to delinearize non-sized (opaque) pointers.
4209 if ((SrcTy->isPointerTy() && !SrcTy->getPointerElementType()->isSized()) ||
4210 (DstTy->isPointerTy() && !DstTy->getPointerElementType()->isSized())) {
4211 return false;
4212 }
Michael Kruse436c9062016-04-08 16:20:08 +00004213 if (SrcTy->isPointerTy() && DstTy->isPointerTy() &&
4214 DL->getTypeAllocSize(SrcTy->getPointerElementType()) ==
4215 DL->getTypeAllocSize(DstTy->getPointerElementType()))
Michael Kruse37d136e2016-02-26 16:08:24 +00004216 Address = Src;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00004217 }
Michael Kruse37d136e2016-02-26 16:08:24 +00004218
4219 auto *GEP = dyn_cast<GetElementPtrInst>(Address);
4220 if (!GEP)
4221 return false;
4222
4223 std::vector<const SCEV *> Subscripts;
4224 std::vector<int> Sizes;
4225 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
4226 auto *BasePtr = GEP->getOperand(0);
4227
Tobias Grosser535afd82016-04-05 06:23:45 +00004228 if (auto *BasePtrCast = dyn_cast<BitCastInst>(BasePtr))
4229 BasePtr = BasePtrCast->getOperand(0);
4230
4231 // Check for identical base pointers to ensure that we do not miss index
4232 // offsets that have been added before this GEP is applied.
4233 if (BasePtr != BasePointer->getValue())
4234 return false;
4235
Michael Kruse37d136e2016-02-26 16:08:24 +00004236 std::vector<const SCEV *> SizesSCEV;
4237
4238 for (auto *Subscript : Subscripts) {
4239 InvariantLoadsSetTy AccessILS;
Johannes Doerfertec8a2172016-04-25 13:32:36 +00004240 if (!isAffineExpr(R, L, Subscript, *SE, &AccessILS))
Michael Kruse37d136e2016-02-26 16:08:24 +00004241 return false;
4242
4243 for (LoadInst *LInst : AccessILS)
4244 if (!ScopRIL.count(LInst))
4245 return false;
4246 }
4247
4248 if (Sizes.empty())
4249 return false;
4250
4251 for (auto V : Sizes)
4252 SizesSCEV.push_back(SE->getSCEV(
4253 ConstantInt::get(IntegerType::getInt64Ty(BasePtr->getContext()), V)));
4254
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004255 addArrayAccess(Inst, AccType, BasePointer->getValue(), ElementType, true,
Michael Kruse37d136e2016-02-26 16:08:24 +00004256 Subscripts, SizesSCEV, Val);
4257 return true;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004258}
4259
4260bool ScopInfo::buildAccessMultiDimParam(
4261 MemAccInst Inst, Loop *L, Region *R,
4262 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
Hongbin Zheng22623202016-02-15 00:20:58 +00004263 const InvariantLoadsSetTy &ScopRIL, const MapInsnToMemAcc &InsnToMemAcc) {
Michael Kruse37d136e2016-02-26 16:08:24 +00004264 if (!PollyDelinearize)
4265 return false;
4266
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004267 Value *Address = Inst.getPointerOperand();
4268 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004269 Type *ElementType = Val->getType();
4270 unsigned ElementSize = DL->getTypeAllocSize(ElementType);
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004271 enum MemoryAccess::AccessType AccType =
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004272 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004273
4274 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
4275 const SCEVUnknown *BasePointer =
4276 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
4277
4278 assert(BasePointer && "Could not find base pointer");
4279 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00004280
Michael Kruse7bf39442015-09-10 12:46:52 +00004281 auto AccItr = InsnToMemAcc.find(Inst);
Michael Kruse37d136e2016-02-26 16:08:24 +00004282 if (AccItr == InsnToMemAcc.end())
4283 return false;
Tobias Grosser5d51afe2016-02-02 16:46:45 +00004284
Michael Kruse37d136e2016-02-26 16:08:24 +00004285 std::vector<const SCEV *> Sizes(
4286 AccItr->second.Shape->DelinearizedSizes.begin(),
4287 AccItr->second.Shape->DelinearizedSizes.end());
4288 // Remove the element size. This information is already provided by the
4289 // ElementSize parameter. In case the element size of this access and the
4290 // element size used for delinearization differs the delinearization is
4291 // incorrect. Hence, we invalidate the scop.
4292 //
4293 // TODO: Handle delinearization with differing element sizes.
4294 auto DelinearizedSize =
4295 cast<SCEVConstant>(Sizes.back())->getAPInt().getSExtValue();
4296 Sizes.pop_back();
4297 if (ElementSize != DelinearizedSize)
4298 scop->invalidate(DELINEARIZATION, Inst->getDebugLoc());
4299
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004300 addArrayAccess(Inst, AccType, BasePointer->getValue(), ElementType, true,
Michael Kruse37d136e2016-02-26 16:08:24 +00004301 AccItr->second.DelinearizedSubscripts, Sizes, Val);
4302 return true;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004303}
4304
Johannes Doerfertcea61932016-02-21 19:13:19 +00004305bool ScopInfo::buildAccessMemIntrinsic(
4306 MemAccInst Inst, Loop *L, Region *R,
4307 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
4308 const InvariantLoadsSetTy &ScopRIL) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004309 auto *MemIntr = dyn_cast_or_null<MemIntrinsic>(Inst);
4310
4311 if (MemIntr == nullptr)
Johannes Doerfertcea61932016-02-21 19:13:19 +00004312 return false;
4313
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004314 auto *LengthVal = SE->getSCEVAtScope(MemIntr->getLength(), L);
Johannes Doerfertcea61932016-02-21 19:13:19 +00004315 assert(LengthVal);
4316
Johannes Doerferta7920982016-02-25 14:08:48 +00004317 // Check if the length val is actually affine or if we overapproximate it
4318 InvariantLoadsSetTy AccessILS;
Johannes Doerfertec8a2172016-04-25 13:32:36 +00004319 bool LengthIsAffine = isAffineExpr(R, L, LengthVal, *SE, &AccessILS);
Johannes Doerferta7920982016-02-25 14:08:48 +00004320 for (LoadInst *LInst : AccessILS)
4321 if (!ScopRIL.count(LInst))
4322 LengthIsAffine = false;
4323 if (!LengthIsAffine)
4324 LengthVal = nullptr;
4325
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004326 auto *DestPtrVal = MemIntr->getDest();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004327 assert(DestPtrVal);
Johannes Doerfert733ea342016-03-24 13:50:04 +00004328
Johannes Doerfertcea61932016-02-21 19:13:19 +00004329 auto *DestAccFunc = SE->getSCEVAtScope(DestPtrVal, L);
4330 assert(DestAccFunc);
Johannes Doerfert733ea342016-03-24 13:50:04 +00004331 // Ignore accesses to "NULL".
4332 // TODO: We could use this to optimize the region further, e.g., intersect
4333 // the context with
4334 // isl_set_complement(isl_set_params(getDomain()))
4335 // as we know it would be undefined to execute this instruction anyway.
4336 if (DestAccFunc->isZero())
4337 return true;
4338
Johannes Doerfertcea61932016-02-21 19:13:19 +00004339 auto *DestPtrSCEV = dyn_cast<SCEVUnknown>(SE->getPointerBase(DestAccFunc));
4340 assert(DestPtrSCEV);
4341 DestAccFunc = SE->getMinusSCEV(DestAccFunc, DestPtrSCEV);
4342 addArrayAccess(Inst, MemoryAccess::MUST_WRITE, DestPtrSCEV->getValue(),
4343 IntegerType::getInt8Ty(DestPtrVal->getContext()), false,
4344 {DestAccFunc, LengthVal}, {}, Inst.getValueOperand());
4345
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004346 auto *MemTrans = dyn_cast<MemTransferInst>(MemIntr);
4347 if (!MemTrans)
Johannes Doerfertcea61932016-02-21 19:13:19 +00004348 return true;
4349
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004350 auto *SrcPtrVal = MemTrans->getSource();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004351 assert(SrcPtrVal);
Johannes Doerfert733ea342016-03-24 13:50:04 +00004352
Johannes Doerfertcea61932016-02-21 19:13:19 +00004353 auto *SrcAccFunc = SE->getSCEVAtScope(SrcPtrVal, L);
4354 assert(SrcAccFunc);
Johannes Doerfert733ea342016-03-24 13:50:04 +00004355 // Ignore accesses to "NULL".
4356 // TODO: See above TODO
4357 if (SrcAccFunc->isZero())
4358 return true;
4359
Johannes Doerfertcea61932016-02-21 19:13:19 +00004360 auto *SrcPtrSCEV = dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccFunc));
4361 assert(SrcPtrSCEV);
4362 SrcAccFunc = SE->getMinusSCEV(SrcAccFunc, SrcPtrSCEV);
4363 addArrayAccess(Inst, MemoryAccess::READ, SrcPtrSCEV->getValue(),
4364 IntegerType::getInt8Ty(SrcPtrVal->getContext()), false,
4365 {SrcAccFunc, LengthVal}, {}, Inst.getValueOperand());
4366
4367 return true;
4368}
4369
Johannes Doerferta7920982016-02-25 14:08:48 +00004370bool ScopInfo::buildAccessCallInst(
4371 MemAccInst Inst, Loop *L, Region *R,
4372 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
4373 const InvariantLoadsSetTy &ScopRIL) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004374 auto *CI = dyn_cast_or_null<CallInst>(Inst);
4375
4376 if (CI == nullptr)
Johannes Doerferta7920982016-02-25 14:08:48 +00004377 return false;
4378
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004379 if (CI->doesNotAccessMemory() || isIgnoredIntrinsic(CI))
Johannes Doerferta7920982016-02-25 14:08:48 +00004380 return true;
4381
4382 bool ReadOnly = false;
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004383 auto *AF = SE->getConstant(IntegerType::getInt64Ty(CI->getContext()), 0);
4384 auto *CalledFunction = CI->getCalledFunction();
Johannes Doerferta7920982016-02-25 14:08:48 +00004385 switch (AA->getModRefBehavior(CalledFunction)) {
4386 case llvm::FMRB_UnknownModRefBehavior:
4387 llvm_unreachable("Unknown mod ref behaviour cannot be represented.");
4388 case llvm::FMRB_DoesNotAccessMemory:
4389 return true;
4390 case llvm::FMRB_OnlyReadsMemory:
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004391 GlobalReads.push_back(CI);
Johannes Doerferta7920982016-02-25 14:08:48 +00004392 return true;
4393 case llvm::FMRB_OnlyReadsArgumentPointees:
4394 ReadOnly = true;
4395 // Fall through
4396 case llvm::FMRB_OnlyAccessesArgumentPointees:
4397 auto AccType = ReadOnly ? MemoryAccess::READ : MemoryAccess::MAY_WRITE;
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004398 for (const auto &Arg : CI->arg_operands()) {
Johannes Doerferta7920982016-02-25 14:08:48 +00004399 if (!Arg->getType()->isPointerTy())
4400 continue;
4401
4402 auto *ArgSCEV = SE->getSCEVAtScope(Arg, L);
4403 if (ArgSCEV->isZero())
4404 continue;
4405
4406 auto *ArgBasePtr = cast<SCEVUnknown>(SE->getPointerBase(ArgSCEV));
4407 addArrayAccess(Inst, AccType, ArgBasePtr->getValue(),
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004408 ArgBasePtr->getType(), false, {AF}, {}, CI);
Johannes Doerferta7920982016-02-25 14:08:48 +00004409 }
4410 return true;
4411 }
4412
4413 return true;
4414}
4415
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004416void ScopInfo::buildAccessSingleDim(
4417 MemAccInst Inst, Loop *L, Region *R,
4418 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
4419 const InvariantLoadsSetTy &ScopRIL) {
4420 Value *Address = Inst.getPointerOperand();
4421 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004422 Type *ElementType = Val->getType();
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004423 enum MemoryAccess::AccessType AccType =
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004424 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004425
4426 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
4427 const SCEVUnknown *BasePointer =
4428 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
4429
4430 assert(BasePointer && "Could not find base pointer");
4431 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
Michael Kruse7bf39442015-09-10 12:46:52 +00004432
4433 // Check if the access depends on a loop contained in a non-affine subregion.
4434 bool isVariantInNonAffineLoop = false;
4435 if (BoxedLoops) {
4436 SetVector<const Loop *> Loops;
4437 findLoops(AccessFunction, Loops);
4438 for (const Loop *L : Loops)
4439 if (BoxedLoops->count(L))
4440 isVariantInNonAffineLoop = true;
4441 }
4442
Johannes Doerfert09e36972015-10-07 20:17:36 +00004443 InvariantLoadsSetTy AccessILS;
Michael Kruse09eb4452016-03-03 22:10:47 +00004444 bool IsAffine = !isVariantInNonAffineLoop &&
Johannes Doerfertec8a2172016-04-25 13:32:36 +00004445 isAffineExpr(R, L, AccessFunction, *SE, &AccessILS);
Johannes Doerfert09e36972015-10-07 20:17:36 +00004446
4447 for (LoadInst *LInst : AccessILS)
4448 if (!ScopRIL.count(LInst))
4449 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00004450
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004451 if (!IsAffine && AccType == MemoryAccess::MUST_WRITE)
4452 AccType = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00004453
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004454 addArrayAccess(Inst, AccType, BasePointer->getValue(), ElementType, IsAffine,
Tobias Grosser5d51afe2016-02-02 16:46:45 +00004455 {AccessFunction}, {}, Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00004456}
4457
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004458void ScopInfo::buildMemoryAccess(
4459 MemAccInst Inst, Loop *L, Region *R,
4460 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
Hongbin Zheng22623202016-02-15 00:20:58 +00004461 const InvariantLoadsSetTy &ScopRIL, const MapInsnToMemAcc &InsnToMemAcc) {
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004462
Johannes Doerfertcea61932016-02-21 19:13:19 +00004463 if (buildAccessMemIntrinsic(Inst, L, R, BoxedLoops, ScopRIL))
4464 return;
4465
Johannes Doerferta7920982016-02-25 14:08:48 +00004466 if (buildAccessCallInst(Inst, L, R, BoxedLoops, ScopRIL))
4467 return;
4468
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004469 if (buildAccessMultiDimFixed(Inst, L, R, BoxedLoops, ScopRIL))
4470 return;
4471
Hongbin Zheng22623202016-02-15 00:20:58 +00004472 if (buildAccessMultiDimParam(Inst, L, R, BoxedLoops, ScopRIL, InsnToMemAcc))
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004473 return;
4474
4475 buildAccessSingleDim(Inst, L, R, BoxedLoops, ScopRIL);
4476}
4477
Hongbin Zheng22623202016-02-15 00:20:58 +00004478void ScopInfo::buildAccessFunctions(Region &R, Region &SR,
4479 const MapInsnToMemAcc &InsnToMemAcc) {
Michael Kruse7bf39442015-09-10 12:46:52 +00004480
4481 if (SD->isNonAffineSubRegion(&SR, &R)) {
4482 for (BasicBlock *BB : SR.blocks())
Hongbin Zheng22623202016-02-15 00:20:58 +00004483 buildAccessFunctions(R, *BB, InsnToMemAcc, &SR);
Michael Kruse7bf39442015-09-10 12:46:52 +00004484 return;
4485 }
4486
4487 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
4488 if (I->isSubRegion())
Hongbin Zheng22623202016-02-15 00:20:58 +00004489 buildAccessFunctions(R, *I->getNodeAs<Region>(), InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00004490 else
Hongbin Zheng22623202016-02-15 00:20:58 +00004491 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>(), InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00004492}
4493
Johannes Doerferta8781032016-02-02 14:14:40 +00004494void ScopInfo::buildStmts(Region &R, Region &SR) {
Michael Krusecac948e2015-10-02 13:53:07 +00004495
Johannes Doerferta8781032016-02-02 14:14:40 +00004496 if (SD->isNonAffineSubRegion(&SR, &R)) {
Michael Krusecac948e2015-10-02 13:53:07 +00004497 scop->addScopStmt(nullptr, &SR);
4498 return;
4499 }
4500
4501 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
4502 if (I->isSubRegion())
Johannes Doerferta8781032016-02-02 14:14:40 +00004503 buildStmts(R, *I->getNodeAs<Region>());
Michael Krusecac948e2015-10-02 13:53:07 +00004504 else
4505 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
4506}
4507
Michael Krused868b5d2015-09-10 15:25:24 +00004508void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
Hongbin Zheng22623202016-02-15 00:20:58 +00004509 const MapInsnToMemAcc &InsnToMemAcc,
Michael Krused868b5d2015-09-10 15:25:24 +00004510 Region *NonAffineSubRegion,
4511 bool IsExitBlock) {
Tobias Grosser910cf262015-11-11 20:15:49 +00004512 // We do not build access functions for error blocks, as they may contain
4513 // instructions we can not model.
Johannes Doerfertc36d39b2016-02-02 14:14:20 +00004514 if (isErrorBlock(BB, R, *LI, *DT) && !IsExitBlock)
Tobias Grosser910cf262015-11-11 20:15:49 +00004515 return;
4516
Michael Kruse7bf39442015-09-10 12:46:52 +00004517 Loop *L = LI->getLoopFor(&BB);
4518
4519 // The set of loops contained in non-affine subregions that are part of R.
4520 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
4521
Johannes Doerfert09e36972015-10-07 20:17:36 +00004522 // The set of loads that are required to be invariant.
4523 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
4524
Michael Kruse2e02d562016-02-06 09:19:40 +00004525 for (Instruction &Inst : BB) {
4526 PHINode *PHI = dyn_cast<PHINode>(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00004527 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00004528 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00004529
4530 // For the exit block we stop modeling after the last PHI node.
4531 if (!PHI && IsExitBlock)
4532 break;
4533
Johannes Doerfert09e36972015-10-07 20:17:36 +00004534 // TODO: At this point we only know that elements of ScopRIL have to be
4535 // invariant and will be hoisted for the SCoP to be processed. Though,
4536 // there might be other invariant accesses that will be hoisted and
4537 // that would allow to make a non-affine access affine.
Michael Kruse70131d32016-01-27 17:09:17 +00004538 if (auto MemInst = MemAccInst::dyn_cast(Inst))
Hongbin Zheng22623202016-02-15 00:20:58 +00004539 buildMemoryAccess(MemInst, L, &R, BoxedLoops, ScopRIL, InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00004540
Michael Kruse2e02d562016-02-06 09:19:40 +00004541 if (isIgnoredIntrinsic(&Inst))
Michael Kruse7bf39442015-09-10 12:46:52 +00004542 continue;
4543
Tobias Grosser0904c692016-03-16 23:33:54 +00004544 // PHI nodes have already been modeled above and TerminatorInsts that are
4545 // not part of a non-affine subregion are fully modeled and regenerated
4546 // from the polyhedral domains. Hence, they do not need to be modeled as
4547 // explicit data dependences.
4548 if (!PHI && (!isa<TerminatorInst>(&Inst) || NonAffineSubRegion))
Michael Kruse2e02d562016-02-06 09:19:40 +00004549 buildScalarDependences(&Inst);
Tobias Grosser0904c692016-03-16 23:33:54 +00004550
Michael Kruse2e02d562016-02-06 09:19:40 +00004551 if (!IsExitBlock)
4552 buildEscapingDependences(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00004553 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00004554}
Michael Kruse7bf39442015-09-10 12:46:52 +00004555
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004556MemoryAccess *ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004557 MemoryAccess::AccessType AccType,
4558 Value *BaseAddress, Type *ElementType,
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004559 bool Affine, Value *AccessValue,
4560 ArrayRef<const SCEV *> Subscripts,
4561 ArrayRef<const SCEV *> Sizes,
4562 ScopArrayInfo::MemoryKind Kind) {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004563 ScopStmt *Stmt = scop->getStmtFor(BB);
Michael Krusecac948e2015-10-02 13:53:07 +00004564
4565 // Do not create a memory access for anything not in the SCoP. It would be
4566 // ignored anyway.
4567 if (!Stmt)
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004568 return nullptr;
Michael Krusecac948e2015-10-02 13:53:07 +00004569
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00004570 AccFuncSetType &AccList = scop->getOrCreateAccessFunctions(BB);
Michael Krusee2bccbb2015-09-18 19:59:43 +00004571 Value *BaseAddr = BaseAddress;
4572 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
4573
Tobias Grosserf4f68702015-12-14 15:05:37 +00004574 bool isKnownMustAccess = false;
4575
4576 // Accesses in single-basic block statements are always excuted.
4577 if (Stmt->isBlockStmt())
4578 isKnownMustAccess = true;
4579
4580 if (Stmt->isRegionStmt()) {
4581 // Accesses that dominate the exit block of a non-affine region are always
4582 // executed. In non-affine regions there may exist MK_Values that do not
4583 // dominate the exit. MK_Values will always dominate the exit and MK_PHIs
4584 // only if there is at most one PHI_WRITE in the non-affine region.
4585 if (DT->dominates(BB, Stmt->getRegion()->getExit()))
4586 isKnownMustAccess = true;
4587 }
4588
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004589 // Non-affine PHI writes do not "happen" at a particular instruction, but
4590 // after exiting the statement. Therefore they are guaranteed execute and
4591 // overwrite the old value.
4592 if (Kind == ScopArrayInfo::MK_PHI || Kind == ScopArrayInfo::MK_ExitPHI)
4593 isKnownMustAccess = true;
4594
Johannes Doerfertcea61932016-02-21 19:13:19 +00004595 if (!isKnownMustAccess && AccType == MemoryAccess::MUST_WRITE)
4596 AccType = MemoryAccess::MAY_WRITE;
Michael Krusecac948e2015-10-02 13:53:07 +00004597
Johannes Doerfertcea61932016-02-21 19:13:19 +00004598 AccList.emplace_back(Stmt, Inst, AccType, BaseAddress, ElementType, Affine,
Tobias Grossera535dff2015-12-13 19:59:01 +00004599 Subscripts, Sizes, AccessValue, Kind, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00004600 Stmt->addAccess(&AccList.back());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004601 return &AccList.back();
Michael Kruse7bf39442015-09-10 12:46:52 +00004602}
4603
Michael Kruse70131d32016-01-27 17:09:17 +00004604void ScopInfo::addArrayAccess(MemAccInst MemAccInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004605 MemoryAccess::AccessType AccType,
4606 Value *BaseAddress, Type *ElementType,
4607 bool IsAffine, ArrayRef<const SCEV *> Subscripts,
Tobias Grossera535dff2015-12-13 19:59:01 +00004608 ArrayRef<const SCEV *> Sizes,
4609 Value *AccessValue) {
Johannes Doerferta7920982016-02-25 14:08:48 +00004610 ArrayBasePointers.insert(BaseAddress);
Hongbin Zhengf3d66122016-02-26 09:47:11 +00004611 addMemoryAccess(MemAccInst->getParent(), MemAccInst, AccType, BaseAddress,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004612 ElementType, IsAffine, AccessValue, Subscripts, Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00004613 ScopArrayInfo::MK_Array);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004614}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004615
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004616void ScopInfo::ensureValueWrite(Instruction *Inst) {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004617 ScopStmt *Stmt = scop->getStmtFor(Inst);
Michael Kruse436db622016-01-26 13:33:10 +00004618
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004619 // Inst not defined within this SCoP.
Michael Kruse436db622016-01-26 13:33:10 +00004620 if (!Stmt)
4621 return;
4622
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004623 // Do not process further if the instruction is already written.
4624 if (Stmt->lookupValueWriteOf(Inst))
Michael Kruse436db622016-01-26 13:33:10 +00004625 return;
4626
Johannes Doerfertcea61932016-02-21 19:13:19 +00004627 addMemoryAccess(Inst->getParent(), Inst, MemoryAccess::MUST_WRITE, Inst,
4628 Inst->getType(), true, Inst, ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004629 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004630}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004631
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004632void ScopInfo::ensureValueRead(Value *V, BasicBlock *UserBB) {
Michael Krusefd463082016-01-27 22:51:56 +00004633
Michael Kruse2e02d562016-02-06 09:19:40 +00004634 // There cannot be an "access" for literal constants. BasicBlock references
4635 // (jump destinations) also never change.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004636 if ((isa<Constant>(V) && !isa<GlobalVariable>(V)) || isa<BasicBlock>(V))
Michael Kruse2e02d562016-02-06 09:19:40 +00004637 return;
4638
Michael Krusefd463082016-01-27 22:51:56 +00004639 // If the instruction can be synthesized and the user is in the region we do
4640 // not need to add a value dependences.
4641 Region &ScopRegion = scop->getRegion();
Michael Krusec7e0d9c2016-03-01 21:44:06 +00004642 auto *Scope = LI->getLoopFor(UserBB);
4643 if (canSynthesize(V, LI, SE, &ScopRegion, Scope))
Michael Krusefd463082016-01-27 22:51:56 +00004644 return;
4645
Michael Kruse2e02d562016-02-06 09:19:40 +00004646 // Do not build scalar dependences for required invariant loads as we will
4647 // hoist them later on anyway or drop the SCoP if we cannot.
Johannes Doerferta90943d2016-02-21 16:37:25 +00004648 auto *ScopRIL = SD->getRequiredInvariantLoads(&ScopRegion);
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004649 if (ScopRIL->count(dyn_cast<LoadInst>(V)))
Michael Kruse2e02d562016-02-06 09:19:40 +00004650 return;
4651
4652 // Determine the ScopStmt containing the value's definition and use. There is
4653 // no defining ScopStmt if the value is a function argument, a global value,
4654 // or defined outside the SCoP.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004655 Instruction *ValueInst = dyn_cast<Instruction>(V);
Michael Kruse6f7721f2016-02-24 22:08:19 +00004656 ScopStmt *ValueStmt = ValueInst ? scop->getStmtFor(ValueInst) : nullptr;
Michael Kruse2e02d562016-02-06 09:19:40 +00004657
Michael Kruse6f7721f2016-02-24 22:08:19 +00004658 ScopStmt *UserStmt = scop->getStmtFor(UserBB);
Michael Krusead28e5a2016-01-26 13:33:15 +00004659
4660 // We do not model uses outside the scop.
4661 if (!UserStmt)
4662 return;
4663
Michael Kruse2e02d562016-02-06 09:19:40 +00004664 // Add MemoryAccess for invariant values only if requested.
4665 if (!ModelReadOnlyScalars && !ValueStmt)
4666 return;
4667
4668 // Ignore use-def chains within the same ScopStmt.
4669 if (ValueStmt == UserStmt)
4670 return;
4671
Michael Krusead28e5a2016-01-26 13:33:15 +00004672 // Do not create another MemoryAccess for reloading the value if one already
4673 // exists.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004674 if (UserStmt->lookupValueReadOf(V))
Michael Krusead28e5a2016-01-26 13:33:15 +00004675 return;
4676
Johannes Doerfert2075b5d2016-04-03 11:16:00 +00004677 // For exit PHIs use the MK_ExitPHI MemoryKind not MK_Value.
4678 ScopArrayInfo::MemoryKind Kind = ScopArrayInfo::MK_Value;
4679 if (!ValueStmt && isa<PHINode>(V))
4680 Kind = ScopArrayInfo::MK_ExitPHI;
4681
Johannes Doerfertcea61932016-02-21 19:13:19 +00004682 addMemoryAccess(UserBB, nullptr, MemoryAccess::READ, V, V->getType(), true, V,
Johannes Doerfert2075b5d2016-04-03 11:16:00 +00004683 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(), Kind);
Michael Kruse2e02d562016-02-06 09:19:40 +00004684 if (ValueInst)
4685 ensureValueWrite(ValueInst);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004686}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004687
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004688void ScopInfo::ensurePHIWrite(PHINode *PHI, BasicBlock *IncomingBlock,
4689 Value *IncomingValue, bool IsExitBlock) {
Johannes Doerfert57c5f0b2016-04-05 13:44:21 +00004690 // As the incoming block might turn out to be an error statement ensure we
4691 // will create an exit PHI SAI object. It is needed during code generation
4692 // and would be created later anyway.
4693 if (IsExitBlock)
4694 scop->getOrCreateScopArrayInfo(PHI, PHI->getType(), {},
4695 ScopArrayInfo::MK_ExitPHI);
4696
Michael Kruse6f7721f2016-02-24 22:08:19 +00004697 ScopStmt *IncomingStmt = scop->getStmtFor(IncomingBlock);
Michael Kruse2e02d562016-02-06 09:19:40 +00004698 if (!IncomingStmt)
4699 return;
4700
4701 // Take care for the incoming value being available in the incoming block.
4702 // This must be done before the check for multiple PHI writes because multiple
4703 // exiting edges from subregion each can be the effective written value of the
4704 // subregion. As such, all of them must be made available in the subregion
4705 // statement.
4706 ensureValueRead(IncomingValue, IncomingBlock);
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004707
4708 // Do not add more than one MemoryAccess per PHINode and ScopStmt.
4709 if (MemoryAccess *Acc = IncomingStmt->lookupPHIWriteOf(PHI)) {
4710 assert(Acc->getAccessInstruction() == PHI);
4711 Acc->addIncoming(IncomingBlock, IncomingValue);
4712 return;
4713 }
4714
4715 MemoryAccess *Acc = addMemoryAccess(
Michael Kruse375cb5f2016-02-24 22:08:24 +00004716 IncomingStmt->getEntryBlock(), PHI, MemoryAccess::MUST_WRITE, PHI,
4717 PHI->getType(), true, PHI, ArrayRef<const SCEV *>(),
4718 ArrayRef<const SCEV *>(),
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004719 IsExitBlock ? ScopArrayInfo::MK_ExitPHI : ScopArrayInfo::MK_PHI);
4720 assert(Acc);
4721 Acc->addIncoming(IncomingBlock, IncomingValue);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004722}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004723
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004724void ScopInfo::addPHIReadAccess(PHINode *PHI) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00004725 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI,
4726 PHI->getType(), true, PHI, ArrayRef<const SCEV *>(),
4727 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004728}
4729
Michael Krusedaf66942015-12-13 22:10:37 +00004730void ScopInfo::buildScop(Region &R, AssumptionCache &AC) {
Michael Kruse9d080092015-09-11 21:41:48 +00004731 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Michael Kruse09eb4452016-03-03 22:10:47 +00004732 scop.reset(new Scop(R, *SE, *LI, MaxLoopDepth));
Michael Kruse7bf39442015-09-10 12:46:52 +00004733
Johannes Doerferta8781032016-02-02 14:14:40 +00004734 buildStmts(R, R);
Hongbin Zheng22623202016-02-15 00:20:58 +00004735 buildAccessFunctions(R, R, *SD->getInsnToMemAccMap(&R));
Michael Kruse7bf39442015-09-10 12:46:52 +00004736
4737 // In case the region does not have an exiting block we will later (during
4738 // code generation) split the exit block. This will move potential PHI nodes
4739 // from the current exit block into the new region exiting block. Hence, PHI
4740 // nodes that are at this point not part of the region will be.
4741 // To handle these PHI nodes later we will now model their operands as scalar
4742 // accesses. Note that we do not model anything in the exit block if we have
4743 // an exiting block in the region, as there will not be any splitting later.
4744 if (!R.getExitingBlock())
Hongbin Zheng22623202016-02-15 00:20:58 +00004745 buildAccessFunctions(R, *R.getExit(), *SD->getInsnToMemAccMap(&R), nullptr,
4746 /* IsExitBlock */ true);
Michael Kruse7bf39442015-09-10 12:46:52 +00004747
Johannes Doerferta7920982016-02-25 14:08:48 +00004748 // Create memory accesses for global reads since all arrays are now known.
4749 auto *AF = SE->getConstant(IntegerType::getInt64Ty(SE->getContext()), 0);
4750 for (auto *GlobalRead : GlobalReads)
4751 for (auto *BP : ArrayBasePointers)
4752 addArrayAccess(MemAccInst(GlobalRead), MemoryAccess::READ, BP,
4753 BP->getType(), false, {AF}, {}, GlobalRead);
4754
Hongbin Zheng192f69a2016-02-13 15:12:54 +00004755 scop->init(*AA, AC, *SD, *DT, *LI);
Michael Kruse7bf39442015-09-10 12:46:52 +00004756}
4757
Michael Krused868b5d2015-09-10 15:25:24 +00004758void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00004759 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00004760 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00004761 return;
4762 }
4763
Michael Kruse9d080092015-09-11 21:41:48 +00004764 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00004765}
4766
Hongbin Zhengfec32802016-02-13 15:13:02 +00004767void ScopInfo::clear() { scop.reset(); }
Michael Kruse7bf39442015-09-10 12:46:52 +00004768
4769//===----------------------------------------------------------------------===//
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004770ScopInfo::ScopInfo() : RegionPass(ID) {}
Tobias Grosserb76f38532011-08-20 11:11:25 +00004771
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004772ScopInfo::~ScopInfo() { clear(); }
Tobias Grosserb76f38532011-08-20 11:11:25 +00004773
Tobias Grosser75805372011-04-29 06:27:02 +00004774void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00004775 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00004776 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00004777 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00004778 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4779 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004780 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004781 AU.addRequired<AssumptionCacheTracker>();
Tobias Grosser75805372011-04-29 06:27:02 +00004782 AU.setPreservesAll();
4783}
4784
4785bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00004786 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00004787
Michael Krused868b5d2015-09-10 15:25:24 +00004788 if (!SD->isMaxRegionInScop(*R))
4789 return false;
4790
4791 Function *F = R->getEntry()->getParent();
4792 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4793 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4794 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Johannes Doerferta1f291e2016-02-02 14:15:13 +00004795 DL = &F->getParent()->getDataLayout();
Michael Krusedaf66942015-12-13 22:10:37 +00004796 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004797 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krused868b5d2015-09-10 15:25:24 +00004798
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004799 DebugLoc Beg, End;
4800 getDebugLocations(R, Beg, End);
4801 std::string Msg = "SCoP begins here.";
4802 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg);
4803
Michael Krusedaf66942015-12-13 22:10:37 +00004804 buildScop(*R, AC);
Tobias Grosser75805372011-04-29 06:27:02 +00004805
Tobias Grosserd6a50b32015-05-30 06:26:21 +00004806 DEBUG(scop->print(dbgs()));
4807
Michael Kruseafe06702015-10-02 16:33:27 +00004808 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004809 Msg = "SCoP ends here but was dismissed.";
Hongbin Zhengfec32802016-02-13 15:13:02 +00004810 scop.reset();
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004811 } else {
4812 Msg = "SCoP ends here.";
4813 ++ScopFound;
4814 if (scop->getMaxLoopDepth() > 0)
4815 ++RichScopFound;
Johannes Doerfert43788c52015-08-20 05:58:56 +00004816 }
4817
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004818 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg);
4819
Tobias Grosser75805372011-04-29 06:27:02 +00004820 return false;
4821}
4822
4823char ScopInfo::ID = 0;
4824
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004825Pass *polly::createScopInfoPass() { return new ScopInfo(); }
4826
Tobias Grosser73600b82011-10-08 00:30:40 +00004827INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
4828 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004829 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004830INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004831INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004832INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004833INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004834INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004835INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004836INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00004837INITIALIZE_PASS_END(ScopInfo, "polly-scops",
4838 "Polly - Create polyhedral description of Scops", false,
4839 false)