blob: ac3477d802ce8b81e20e3cd138e4c8ec74a9181f [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"
Tobias Grosserba0d0922015-05-09 09:13:42 +000035#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000036#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000037#include "llvm/Analysis/RegionIterator.h"
38#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Johannes Doerfert48fe86f2015-11-12 02:32:32 +000039#include "llvm/IR/DiagnosticInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000040#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000041#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000042#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000043#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000044#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000045#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000046#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000047#include "isl/schedule.h"
48#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000049#include "isl/set.h"
50#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000051#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000052#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000053#include <sstream>
54#include <string>
55#include <vector>
56
57using namespace llvm;
58using namespace polly;
59
Chandler Carruth95fef942014-04-22 03:30:19 +000060#define DEBUG_TYPE "polly-scops"
61
Tobias Grosser74394f02013-01-14 22:40:23 +000062STATISTIC(ScopFound, "Number of valid Scops");
63STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000064
Tobias Grosser75dc40c2015-12-20 13:31:48 +000065// The maximal number of basic sets we allow during domain construction to
66// be created. More complex scops will result in very high compile time and
67// are also unlikely to result in good code
68static int const MaxConjunctsInDomain = 20;
69
Michael Kruse7bf39442015-09-10 12:46:52 +000070static cl::opt<bool> ModelReadOnlyScalars(
71 "polly-analyze-read-only-scalars",
72 cl::desc("Model read-only scalar values in the scop description"),
73 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
74
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000075// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000076// operations can overflow easily. Additive reductions and bit operations
77// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000078static cl::opt<bool> DisableMultiplicativeReductions(
79 "polly-disable-multiplicative-reductions",
80 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
81 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000082
Johannes Doerfert9143d672014-09-27 11:02:39 +000083static cl::opt<unsigned> RunTimeChecksMaxParameters(
84 "polly-rtc-max-parameters",
85 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
86 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
87
Tobias Grosser71500722015-03-28 15:11:14 +000088static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
89 "polly-rtc-max-arrays-per-group",
90 cl::desc("The maximal number of arrays to compare in each alias group."),
91 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000092static cl::opt<std::string> UserContextStr(
93 "polly-context", cl::value_desc("isl parameter set"),
94 cl::desc("Provide additional constraints on the context parameters"),
95 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000096
Tobias Grosserd83b8a82015-08-20 19:08:11 +000097static cl::opt<bool> DetectReductions("polly-detect-reductions",
98 cl::desc("Detect and exploit reductions"),
99 cl::Hidden, cl::ZeroOrMore,
100 cl::init(true), cl::cat(PollyCategory));
101
Tobias Grosser20a4c0c2015-11-11 16:22:36 +0000102static cl::opt<int> MaxDisjunctsAssumed(
103 "polly-max-disjuncts-assumed",
104 cl::desc("The maximal number of disjuncts we allow in the assumption "
105 "context (this bounds compile time)"),
106 cl::Hidden, cl::ZeroOrMore, cl::init(150), cl::cat(PollyCategory));
107
Tobias Grosser4927c8e2015-11-24 12:50:02 +0000108static cl::opt<bool> IgnoreIntegerWrapping(
109 "polly-ignore-integer-wrapping",
110 cl::desc("Do not build run-time checks to proof absence of integer "
111 "wrapping"),
112 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
113
Michael Kruse7bf39442015-09-10 12:46:52 +0000114//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000115
Michael Kruse046dde42015-08-10 13:01:57 +0000116// Create a sequence of two schedules. Either argument may be null and is
117// interpreted as the empty schedule. Can also return null if both schedules are
118// empty.
119static __isl_give isl_schedule *
120combineInSequence(__isl_take isl_schedule *Prev,
121 __isl_take isl_schedule *Succ) {
122 if (!Prev)
123 return Succ;
124 if (!Succ)
125 return Prev;
126
127 return isl_schedule_sequence(Prev, Succ);
128}
129
Johannes Doerferte7044942015-02-24 11:58:30 +0000130static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
131 const ConstantRange &Range,
132 int dim,
133 enum isl_dim_type type) {
134 isl_val *V;
135 isl_ctx *ctx = isl_set_get_ctx(S);
136
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000137 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
138 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000139 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000140 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
141
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000142 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000143 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000144 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000145 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000146 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
147
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000148 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000149 return isl_set_union(SLB, SUB);
150 else
151 return isl_set_intersect(SLB, SUB);
152}
153
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000154static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
155 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
156 if (!BasePtrLI)
157 return nullptr;
158
159 if (!S->getRegion().contains(BasePtrLI))
160 return nullptr;
161
162 ScalarEvolution &SE = *S->getSE();
163
164 auto *OriginBaseSCEV =
165 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
166 if (!OriginBaseSCEV)
167 return nullptr;
168
169 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
170 if (!OriginBaseSCEVUnknown)
171 return nullptr;
172
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000173 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grossera535dff2015-12-13 19:59:01 +0000174 ScopArrayInfo::MK_Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000175}
176
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000177ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grossera535dff2015-12-13 19:59:01 +0000178 ArrayRef<const SCEV *> Sizes, enum MemoryKind Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000179 const DataLayout &DL, Scop *S)
180 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000181 std::string BasePtrName =
Tobias Grossera535dff2015-12-13 19:59:01 +0000182 getIslCompatibleName("MemRef_", BasePtr, Kind == MK_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000183 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000184
Tobias Grosserd840fc72016-02-04 13:18:42 +0000185 updateSizes(Sizes, ElementType);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000186 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
187 if (BasePtrOriginSAI)
188 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000189}
190
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000191__isl_give isl_space *ScopArrayInfo::getSpace() const {
192 auto Space =
193 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
194 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
195 return Space;
196}
197
Tobias Grosserd840fc72016-02-04 13:18:42 +0000198bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
199 Type *NewElementType) {
200 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
201 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
202
203 if (NewElementSize != OldElementSize) {
204 if (NewElementSize % OldElementSize == 0 &&
205 NewElementSize < OldElementSize) {
206 ElementType = NewElementType;
207 } else {
208 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
209 ElementType = IntegerType::get(ElementType->getContext(), GCD);
210 }
211 }
212
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000213 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
214 int ExtraDimsNew = NewSizes.size() - SharedDims;
215 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Tobias Grosser8286b832015-11-02 11:29:32 +0000216 for (int i = 0; i < SharedDims; i++)
217 if (NewSizes[i + ExtraDimsNew] != DimensionSizes[i + ExtraDimsOld])
218 return false;
219
220 if (DimensionSizes.size() >= NewSizes.size())
221 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000222
223 DimensionSizes.clear();
224 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
225 NewSizes.end());
226 for (isl_pw_aff *Size : DimensionSizesPw)
227 isl_pw_aff_free(Size);
228 DimensionSizesPw.clear();
229 for (const SCEV *Expr : DimensionSizes) {
230 isl_pw_aff *Size = S.getPwAff(Expr);
231 DimensionSizesPw.push_back(Size);
232 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000233 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000234}
235
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000236ScopArrayInfo::~ScopArrayInfo() {
237 isl_id_free(Id);
238 for (isl_pw_aff *Size : DimensionSizesPw)
239 isl_pw_aff_free(Size);
240}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000241
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000242std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
243
244int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000245 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000246}
247
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000248isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
249
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) {
260 auto Size = getDimensionSizePw(u);
261 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
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000292void MemoryAccess::updateDimensionality() {
293 auto ArraySpace = getScopArrayInfo()->getSpace();
294 auto AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
295
296 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
297 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
298 auto DimsMissing = DimsArray - DimsAccess;
299
Tobias Grosserd840fc72016-02-04 13:18:42 +0000300 auto Map = isl_map_from_domain_and_range(
301 isl_set_universe(AccessSpace),
302 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000303
304 for (unsigned i = 0; i < DimsMissing; i++)
305 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
306
307 for (unsigned i = DimsMissing; i < DimsArray; i++)
308 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
309
310 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000311
Tobias Grosserd840fc72016-02-04 13:18:42 +0000312 // Introduce multi-element accesses in case the type loaded by this memory
313 // access is larger than the canonical element type of the array.
314 //
315 // An access ((float *)A)[i] to an array char *A is modeled as
316 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
317 unsigned ArrayElemSize = getScopArrayInfo()->getElemSizeInBytes();
318 if (ElemBytes > ArrayElemSize) {
319 assert(ElemBytes % ArrayElemSize == 0 &&
320 "Loaded element size should be multiple of canonical element size");
321 auto Map = isl_map_from_domain_and_range(
322 isl_set_universe(isl_space_copy(ArraySpace)),
323 isl_set_universe(isl_space_copy(ArraySpace)));
324 for (unsigned i = 0; i < DimsArray - 1; i++)
325 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
326
327 isl_ctx *Ctx;
328 isl_constraint *C;
329 isl_local_space *LS;
330
331 LS = isl_local_space_from_space(isl_map_get_space(Map));
332 Ctx = isl_map_get_ctx(Map);
333 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
334
335 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
336 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
337 C = isl_constraint_set_coefficient_si(C, isl_dim_in,
338 DimsArray - 1 - DimsMissing, Num);
339 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
340 Map = isl_map_add_constraint(Map, C);
341
342 C = isl_constraint_alloc_inequality(LS);
343 C = isl_constraint_set_coefficient_si(C, isl_dim_in,
344 DimsArray - 1 - DimsMissing, -Num);
345 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
346 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
347 Map = isl_map_add_constraint(Map, C);
348 AccessRelation = isl_map_apply_range(AccessRelation, Map);
349 }
350
351 isl_space_free(ArraySpace);
352
Roman Gareev10595a12016-01-08 14:01:59 +0000353 assumeNoOutOfBound();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000354}
355
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000356const std::string
357MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
358 switch (RT) {
359 case MemoryAccess::RT_NONE:
360 llvm_unreachable("Requested a reduction operator string for a memory "
361 "access which isn't a reduction");
362 case MemoryAccess::RT_ADD:
363 return "+";
364 case MemoryAccess::RT_MUL:
365 return "*";
366 case MemoryAccess::RT_BOR:
367 return "|";
368 case MemoryAccess::RT_BXOR:
369 return "^";
370 case MemoryAccess::RT_BAND:
371 return "&";
372 }
373 llvm_unreachable("Unknown reduction type");
374 return "";
375}
376
Johannes Doerfertf6183392014-07-01 20:52:51 +0000377/// @brief Return the reduction type for a given binary operator
378static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
379 const Instruction *Load) {
380 if (!BinOp)
381 return MemoryAccess::RT_NONE;
382 switch (BinOp->getOpcode()) {
383 case Instruction::FAdd:
384 if (!BinOp->hasUnsafeAlgebra())
385 return MemoryAccess::RT_NONE;
386 // Fall through
387 case Instruction::Add:
388 return MemoryAccess::RT_ADD;
389 case Instruction::Or:
390 return MemoryAccess::RT_BOR;
391 case Instruction::Xor:
392 return MemoryAccess::RT_BXOR;
393 case Instruction::And:
394 return MemoryAccess::RT_BAND;
395 case Instruction::FMul:
396 if (!BinOp->hasUnsafeAlgebra())
397 return MemoryAccess::RT_NONE;
398 // Fall through
399 case Instruction::Mul:
400 if (DisableMultiplicativeReductions)
401 return MemoryAccess::RT_NONE;
402 return MemoryAccess::RT_MUL;
403 default:
404 return MemoryAccess::RT_NONE;
405 }
406}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000407
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000408/// @brief Derive the individual index expressions from a GEP instruction
409///
410/// This function optimistically assumes the GEP references into a fixed size
411/// array. If this is actually true, this function returns a list of array
412/// subscript expressions as SCEV as well as a list of integers describing
413/// the size of the individual array dimensions. Both lists have either equal
414/// length of the size list is one element shorter in case there is no known
415/// size available for the outermost array dimension.
416///
417/// @param GEP The GetElementPtr instruction to analyze.
418///
419/// @return A tuple with the subscript expressions and the dimension sizes.
420static std::tuple<std::vector<const SCEV *>, std::vector<int>>
421getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
422 std::vector<const SCEV *> Subscripts;
423 std::vector<int> Sizes;
424
425 Type *Ty = GEP->getPointerOperandType();
426
427 bool DroppedFirstDim = false;
428
Michael Kruse26ed65e2015-09-24 17:32:49 +0000429 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000430
431 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
432
433 if (i == 1) {
434 if (auto PtrTy = dyn_cast<PointerType>(Ty)) {
435 Ty = PtrTy->getElementType();
436 } else if (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
437 Ty = ArrayTy->getElementType();
438 } else {
439 Subscripts.clear();
440 Sizes.clear();
441 break;
442 }
443 if (auto Const = dyn_cast<SCEVConstant>(Expr))
444 if (Const->getValue()->isZero()) {
445 DroppedFirstDim = true;
446 continue;
447 }
448 Subscripts.push_back(Expr);
449 continue;
450 }
451
452 auto ArrayTy = dyn_cast<ArrayType>(Ty);
453 if (!ArrayTy) {
454 Subscripts.clear();
455 Sizes.clear();
456 break;
457 }
458
459 Subscripts.push_back(Expr);
460 if (!(DroppedFirstDim && i == 2))
461 Sizes.push_back(ArrayTy->getNumElements());
462
463 Ty = ArrayTy->getElementType();
464 }
465
466 return std::make_tuple(Subscripts, Sizes);
467}
468
Tobias Grosser75805372011-04-29 06:27:02 +0000469MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000470 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000471 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000472 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000473}
474
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000475const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
476 isl_id *ArrayId = getArrayId();
477 void *User = isl_id_get_user(ArrayId);
478 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
479 isl_id_free(ArrayId);
480 return SAI;
481}
482
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000483__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000484 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
485}
486
Tobias Grosserd840fc72016-02-04 13:18:42 +0000487__isl_give isl_map *MemoryAccess::getAddressFunction() const {
488 return isl_map_lexmin(getAccessRelation());
489}
490
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000491__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
492 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000493 isl_map *Schedule, *ScheduledAccRel;
494 isl_union_set *UDomain;
495
496 UDomain = isl_union_set_from_set(getStatement()->getDomain());
497 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
498 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000499 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000500 return isl_pw_multi_aff_from_map(ScheduledAccRel);
501}
502
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000503__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000504 return isl_map_copy(AccessRelation);
505}
506
Johannes Doerferta99130f2014-10-13 12:58:03 +0000507std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000508 return stringFromIslObj(AccessRelation);
509}
510
Johannes Doerferta99130f2014-10-13 12:58:03 +0000511__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000512 return isl_map_get_space(AccessRelation);
513}
514
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000515__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000516 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000517}
518
Tobias Grosser6f730082015-09-05 07:46:47 +0000519std::string MemoryAccess::getNewAccessRelationStr() const {
520 return stringFromIslObj(NewAccessRelation);
521}
522
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000523__isl_give isl_basic_map *
524MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000525 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000526 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000527
Tobias Grosser084d8f72012-05-29 09:29:44 +0000528 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000529 isl_basic_set_universe(Statement->getDomainSpace()),
530 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000531}
532
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000533// Formalize no out-of-bound access assumption
534//
535// When delinearizing array accesses we optimistically assume that the
536// delinearized accesses do not access out of bound locations (the subscript
537// expression of each array evaluates for each statement instance that is
538// executed to a value that is larger than zero and strictly smaller than the
539// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000540// dimension for which we do not need to assume any upper bound. At this point
541// we formalize this assumption to ensure that at code generation time the
542// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000543//
544// To find the set of constraints necessary to avoid out of bound accesses, we
545// first build the set of data locations that are not within array bounds. We
546// then apply the reverse access relation to obtain the set of iterations that
547// may contain invalid accesses and reduce this set of iterations to the ones
548// that are actually executed by intersecting them with the domain of the
549// statement. If we now project out all loop dimensions, we obtain a set of
550// parameters that may cause statement instances to be executed that may
551// possibly yield out of bound memory accesses. The complement of these
552// constraints is the set of constraints that needs to be assumed to ensure such
553// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000554void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000555 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000556 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000557 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000558 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000559 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
560 isl_pw_aff *Var =
561 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
562 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
563
564 isl_set *DimOutside;
565
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000566 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000567 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000568 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
569 isl_space_dim(Space, isl_dim_set));
570 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
571 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000572
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000573 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000574
575 Outside = isl_set_union(Outside, DimOutside);
576 }
577
578 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
579 Outside = isl_set_intersect(Outside, Statement->getDomain());
580 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000581
582 // Remove divs to avoid the construction of overly complicated assumptions.
583 // Doing so increases the set of parameter combinations that are assumed to
584 // not appear. This is always save, but may make the resulting run-time check
585 // bail out more often than strictly necessary.
586 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000587 Outside = isl_set_complement(Outside);
Michael Krusead28e5a2016-01-26 13:33:15 +0000588 Statement->getParent()->addAssumption(
589 INBOUNDS, Outside,
590 getAccessInstruction() ? getAccessInstruction()->getDebugLoc() : nullptr);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000591 isl_space_free(Space);
592}
593
Johannes Doerferte7044942015-02-24 11:58:30 +0000594void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
595 ScalarEvolution *SE = Statement->getParent()->getSE();
596
Michael Kruse70131d32016-01-27 17:09:17 +0000597 Value *Ptr = MemAccInst(getAccessInstruction()).getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000598 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
599 return;
600
601 auto *PtrSCEV = SE->getSCEV(Ptr);
602 if (isa<SCEVCouldNotCompute>(PtrSCEV))
603 return;
604
605 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
606 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
607 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
608
609 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
610 if (Range.isFullSet())
611 return;
612
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000613 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000614 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000615 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000616 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000617 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000618
619 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000620 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000621
622 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
623 AccessRange =
624 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
625 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
626}
627
Michael Krusee2bccbb2015-09-18 19:59:43 +0000628__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000629 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000630 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000631
632 for (int i = Size - 2; i >= 0; --i) {
633 isl_space *Space;
634 isl_map *MapOne, *MapTwo;
Michael Krusee2bccbb2015-09-18 19:59:43 +0000635 isl_pw_aff *DimSize = Statement->getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000636
637 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
638 isl_pw_aff_free(DimSize);
639 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
640
641 Space = isl_map_get_space(AccessRelation);
642 Space = isl_space_map_from_set(isl_space_range(Space));
643 Space = isl_space_align_params(Space, SpaceSize);
644
645 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
646 isl_id_free(ParamId);
647
648 MapOne = isl_map_universe(isl_space_copy(Space));
649 for (int j = 0; j < Size; ++j)
650 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
651 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
652
653 MapTwo = isl_map_universe(isl_space_copy(Space));
654 for (int j = 0; j < Size; ++j)
655 if (j < i || j > i + 1)
656 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
657
658 isl_local_space *LS = isl_local_space_from_space(Space);
659 isl_constraint *C;
660 C = isl_equality_alloc(isl_local_space_copy(LS));
661 C = isl_constraint_set_constant_si(C, -1);
662 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
663 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
664 MapTwo = isl_map_add_constraint(MapTwo, C);
665 C = isl_equality_alloc(LS);
666 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
667 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
668 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
669 MapTwo = isl_map_add_constraint(MapTwo, C);
670 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
671
672 MapOne = isl_map_union(MapOne, MapTwo);
673 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
674 }
675 return AccessRelation;
676}
677
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000678/// @brief Check if @p Expr is divisible by @p Size.
679static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
680
681 // Only one factor needs to be divisible.
682 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
683 for (auto *FactorExpr : MulExpr->operands())
684 if (isDivisible(FactorExpr, Size, SE))
685 return true;
686 return false;
687 }
688
689 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
690 // to be divisble.
691 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
692 for (auto *OpExpr : NAryExpr->operands())
693 if (!isDivisible(OpExpr, Size, SE))
694 return false;
695 return true;
696 }
697
698 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
699 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
700 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
701 return MulSCEV == Expr;
702}
703
Michael Krusee2bccbb2015-09-18 19:59:43 +0000704void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
705 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000706
Michael Krusee2bccbb2015-09-18 19:59:43 +0000707 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000708 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000709
Michael Krusee2bccbb2015-09-18 19:59:43 +0000710 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000711 // We overapproximate non-affine accesses with a possible access to the
712 // whole array. For read accesses it does not make a difference, if an
713 // access must or may happen. However, for write accesses it is important to
714 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000715 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000716 AccessRelation =
717 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000718
Michael Krusee2bccbb2015-09-18 19:59:43 +0000719 computeBoundsOnAccessRelation(getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000720 return;
721 }
722
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000723 Scop &S = *getStatement()->getParent();
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000724 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000725 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000726
Michael Krusee2bccbb2015-09-18 19:59:43 +0000727 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
728 isl_pw_aff *Affine = Statement->getPwAff(Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000729
Sebastian Pop422e33f2014-06-03 18:16:31 +0000730 if (Size == 1) {
731 // For the non delinearized arrays, divide the access function of the last
732 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000733 //
734 // A stride one array access in C expressed as A[i] is expressed in
735 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
736 // two subsequent values of 'i' index two values that are stored next to
737 // each other in memory. By this division we make this characteristic
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000738 // obvious again. However, if the index is not divisible by the element
739 // size we will bail out.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000740 isl_val *v = isl_val_int_from_si(Ctx, getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000741 Affine = isl_pw_aff_scale_down_val(Affine, v);
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000742
743 if (!isDivisible(Subscripts[0], getElemSizeInBytes(), *S.getSE()))
Tobias Grosser8d4f6262015-12-12 09:52:26 +0000744 S.invalidate(ALIGNMENT, AccessInstruction->getDebugLoc());
Sebastian Pop18016682014-04-08 21:20:44 +0000745 }
746
747 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
748
Tobias Grosser79baa212014-04-10 08:38:02 +0000749 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000750 }
751
Tobias Grosser5d51afe2016-02-02 16:46:45 +0000752 if (Sizes.size() >= 1 && !isa<SCEVConstant>(Sizes[0]))
Michael Krusee2bccbb2015-09-18 19:59:43 +0000753 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000754
Tobias Grosser79baa212014-04-10 08:38:02 +0000755 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000756 AccessRelation = isl_map_set_tuple_id(
757 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000758 AccessRelation =
759 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
760
Tobias Grosseraa660a92015-03-30 00:07:50 +0000761 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000762 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000763}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000764
Michael Krusecac948e2015-10-02 13:53:07 +0000765MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000766 AccessType Type, Value *BaseAddress,
767 unsigned ElemBytes, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000768 ArrayRef<const SCEV *> Subscripts,
769 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000770 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
771 : Kind(Kind), AccType(Type), RedType(RT_NONE), Statement(Stmt),
Michael Krusecac948e2015-10-02 13:53:07 +0000772 BaseAddr(BaseAddress), BaseName(BaseName), ElemBytes(ElemBytes),
773 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
774 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000775 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000776 NewAccessRelation(nullptr) {
777
778 std::string IdName = "__polly_array_ref";
779 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
780}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000781
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000782void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000783 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000784 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000785}
786
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000787const std::string MemoryAccess::getReductionOperatorStr() const {
788 return MemoryAccess::getReductionOperatorStr(getReductionType());
789}
790
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000791__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
792
Johannes Doerfertf6183392014-07-01 20:52:51 +0000793raw_ostream &polly::operator<<(raw_ostream &OS,
794 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000795 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000796 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000797 else
798 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000799 return OS;
800}
801
Tobias Grosser75805372011-04-29 06:27:02 +0000802void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000803 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000804 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000805 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000806 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000807 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000808 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000809 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000810 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000811 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000812 break;
813 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000814 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000815 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000816 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000817 if (hasNewAccessRelation())
818 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000819}
820
Tobias Grosser74394f02013-01-14 22:40:23 +0000821void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000822
823// Create a map in the size of the provided set domain, that maps from the
824// one element of the provided set domain to another element of the provided
825// set domain.
826// The mapping is limited to all points that are equal in all but the last
827// dimension and for which the last dimension of the input is strict smaller
828// than the last dimension of the output.
829//
830// getEqualAndLarger(set[i0, i1, ..., iX]):
831//
832// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
833// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
834//
Tobias Grosserf5338802011-10-06 00:03:35 +0000835static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000836 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000837 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000838 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000839
840 // Set all but the last dimension to be equal for the input and output
841 //
842 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
843 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000844 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000845 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000846
847 // Set the last dimension of the input to be strict smaller than the
848 // last dimension of the output.
849 //
850 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000851 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
852 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000853 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000854}
855
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000856__isl_give isl_set *
857MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000858 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000859 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000860 isl_space *Space = isl_space_range(isl_map_get_space(S));
861 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000862
Sebastian Popa00a0292012-12-18 07:46:06 +0000863 S = isl_map_reverse(S);
864 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000865
Sebastian Popa00a0292012-12-18 07:46:06 +0000866 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
867 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
868 NextScatt = isl_map_apply_domain(NextScatt, S);
869 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000870
Sebastian Popa00a0292012-12-18 07:46:06 +0000871 isl_set *Deltas = isl_map_deltas(NextScatt);
872 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000873}
874
Sebastian Popa00a0292012-12-18 07:46:06 +0000875bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000876 int StrideWidth) const {
877 isl_set *Stride, *StrideX;
878 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000879
Sebastian Popa00a0292012-12-18 07:46:06 +0000880 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000881 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000882 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
883 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
884 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
885 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000886 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000887
Tobias Grosser28dd4862012-01-24 16:42:16 +0000888 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000889 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000890
Tobias Grosser28dd4862012-01-24 16:42:16 +0000891 return IsStrideX;
892}
893
Sebastian Popa00a0292012-12-18 07:46:06 +0000894bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
895 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000896}
897
Sebastian Popa00a0292012-12-18 07:46:06 +0000898bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
899 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000900}
901
Tobias Grosser166c4222015-09-05 07:46:40 +0000902void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
903 isl_map_free(NewAccessRelation);
904 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000905}
Tobias Grosser75805372011-04-29 06:27:02 +0000906
907//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000908
Tobias Grosser808cd692015-07-14 09:33:13 +0000909isl_map *ScopStmt::getSchedule() const {
910 isl_set *Domain = getDomain();
911 if (isl_set_is_empty(Domain)) {
912 isl_set_free(Domain);
913 return isl_map_from_aff(
914 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
915 }
916 auto *Schedule = getParent()->getSchedule();
917 Schedule = isl_union_map_intersect_domain(
918 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
919 if (isl_union_map_is_empty(Schedule)) {
920 isl_set_free(Domain);
921 isl_union_map_free(Schedule);
922 return isl_map_from_aff(
923 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
924 }
925 auto *M = isl_map_from_union_map(Schedule);
926 M = isl_map_coalesce(M);
927 M = isl_map_gist_domain(M, Domain);
928 M = isl_map_coalesce(M);
929 return M;
930}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000931
Johannes Doerfert574182d2015-08-12 10:19:50 +0000932__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000933 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
934 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000935}
936
Tobias Grosser37eb4222014-02-20 21:43:54 +0000937void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
938 assert(isl_set_is_subset(NewDomain, Domain) &&
939 "New domain is not a subset of old domain!");
940 isl_set_free(Domain);
941 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000942}
943
Michael Krusecac948e2015-10-02 13:53:07 +0000944void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000945 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +0000946 for (MemoryAccess *Access : MemAccs) {
947 Type *ElementType = Access->getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000948
Tobias Grossera535dff2015-12-13 19:59:01 +0000949 ScopArrayInfo::MemoryKind Ty;
950 if (Access->isPHIKind())
951 Ty = ScopArrayInfo::MK_PHI;
952 else if (Access->isExitPHIKind())
953 Ty = ScopArrayInfo::MK_ExitPHI;
954 else if (Access->isValueKind())
955 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000956 else
Tobias Grossera535dff2015-12-13 19:59:01 +0000957 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000958
Johannes Doerfertadeab372016-02-07 13:57:32 +0000959 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
960 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +0000961 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +0000962 }
963}
964
Michael Krusecac948e2015-10-02 13:53:07 +0000965void ScopStmt::addAccess(MemoryAccess *Access) {
966 Instruction *AccessInst = Access->getAccessInstruction();
967
Michael Kruse58fa3bb2015-12-22 23:25:11 +0000968 if (Access->isArrayKind()) {
969 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
970 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +0000971 } else if (Access->isValueKind() && Access->isWrite()) {
972 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
973 assert(Parent.getStmtForBasicBlock(AccessVal->getParent()) == this);
974 assert(!ValueWrites.lookup(AccessVal));
975
976 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +0000977 } else if (Access->isValueKind() && Access->isRead()) {
978 Value *AccessVal = Access->getAccessValue();
979 assert(!ValueReads.lookup(AccessVal));
980
981 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +0000982 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
983 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
984 assert(!PHIWrites.lookup(PHI));
985
986 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +0000987 }
988
989 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +0000990}
991
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000992void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000993 for (MemoryAccess *MA : *this)
994 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000995
996 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000997}
998
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000999/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
1000static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1001 void *User) {
1002 isl_set **BoundedParts = static_cast<isl_set **>(User);
1003 if (isl_basic_set_is_bounded(BSet))
1004 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1005 else
1006 isl_basic_set_free(BSet);
1007 return isl_stat_ok;
1008}
1009
1010/// @brief Return the bounded parts of @p S.
1011static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1012 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1013 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1014 isl_set_free(S);
1015 return BoundedParts;
1016}
1017
1018/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
1019///
1020/// @returns A separation of @p S into first an unbounded then a bounded subset,
1021/// both with regards to the dimension @p Dim.
1022static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1023partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1024
1025 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001026 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001027
1028 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001029 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001030
1031 // Remove dimensions that are greater than Dim as they are not interesting.
1032 assert(NumDimsS >= Dim + 1);
1033 OnlyDimS =
1034 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1035
1036 // Create artificial parametric upper bounds for dimensions smaller than Dim
1037 // as we are not interested in them.
1038 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1039 for (unsigned u = 0; u < Dim; u++) {
1040 isl_constraint *C = isl_inequality_alloc(
1041 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1042 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1043 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1044 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1045 }
1046
1047 // Collect all bounded parts of OnlyDimS.
1048 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1049
1050 // Create the dimensions greater than Dim again.
1051 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1052 NumDimsS - Dim - 1);
1053
1054 // Remove the artificial upper bound parameters again.
1055 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1056
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001057 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001058 return std::make_pair(UnboundedParts, BoundedParts);
1059}
1060
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001061/// @brief Set the dimension Ids from @p From in @p To.
1062static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1063 __isl_take isl_set *To) {
1064 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1065 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1066 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1067 }
1068 return To;
1069}
1070
1071/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001072static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001073 __isl_take isl_pw_aff *L,
1074 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001075 switch (Pred) {
1076 case ICmpInst::ICMP_EQ:
1077 return isl_pw_aff_eq_set(L, R);
1078 case ICmpInst::ICMP_NE:
1079 return isl_pw_aff_ne_set(L, R);
1080 case ICmpInst::ICMP_SLT:
1081 return isl_pw_aff_lt_set(L, R);
1082 case ICmpInst::ICMP_SLE:
1083 return isl_pw_aff_le_set(L, R);
1084 case ICmpInst::ICMP_SGT:
1085 return isl_pw_aff_gt_set(L, R);
1086 case ICmpInst::ICMP_SGE:
1087 return isl_pw_aff_ge_set(L, R);
1088 case ICmpInst::ICMP_ULT:
1089 return isl_pw_aff_lt_set(L, R);
1090 case ICmpInst::ICMP_UGT:
1091 return isl_pw_aff_gt_set(L, R);
1092 case ICmpInst::ICMP_ULE:
1093 return isl_pw_aff_le_set(L, R);
1094 case ICmpInst::ICMP_UGE:
1095 return isl_pw_aff_ge_set(L, R);
1096 default:
1097 llvm_unreachable("Non integer predicate not supported");
1098 }
1099}
1100
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001101/// @brief Create the conditions under which @p L @p Pred @p R is true.
1102///
1103/// Helper function that will make sure the dimensions of the result have the
1104/// same isl_id's as the @p Domain.
1105static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1106 __isl_take isl_pw_aff *L,
1107 __isl_take isl_pw_aff *R,
1108 __isl_keep isl_set *Domain) {
1109 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1110 return setDimensionIds(Domain, ConsequenceCondSet);
1111}
1112
1113/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001114///
1115/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001116/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1117/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001118static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001119buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001120 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1121
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001122 Value *Condition = getConditionFromTerminator(SI);
1123 assert(Condition && "No condition for switch");
1124
1125 ScalarEvolution &SE = *S.getSE();
1126 BasicBlock *BB = SI->getParent();
1127 isl_pw_aff *LHS, *RHS;
1128 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
1129
1130 unsigned NumSuccessors = SI->getNumSuccessors();
1131 ConditionSets.resize(NumSuccessors);
1132 for (auto &Case : SI->cases()) {
1133 unsigned Idx = Case.getSuccessorIndex();
1134 ConstantInt *CaseValue = Case.getCaseValue();
1135
1136 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
1137 isl_set *CaseConditionSet =
1138 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1139 ConditionSets[Idx] = isl_set_coalesce(
1140 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1141 }
1142
1143 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1144 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1145 for (unsigned u = 2; u < NumSuccessors; u++)
1146 ConditionSetUnion =
1147 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1148 ConditionSets[0] = setDimensionIds(
1149 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1150
1151 S.markAsOptimized();
1152 isl_pw_aff_free(LHS);
1153}
1154
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001155/// @brief Build the conditions sets for the branch condition @p Condition in
1156/// the @p Domain.
1157///
1158/// This will fill @p ConditionSets with the conditions under which control
1159/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001160/// have as many elements as @p TI has successors. If @p TI is nullptr the
1161/// context under which @p Condition is true/false will be returned as the
1162/// new elements of @p ConditionSets.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001163static void
1164buildConditionSets(Scop &S, Value *Condition, TerminatorInst *TI, Loop *L,
1165 __isl_keep isl_set *Domain,
1166 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1167
1168 isl_set *ConsequenceCondSet = nullptr;
1169 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1170 if (CCond->isZero())
1171 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1172 else
1173 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1174 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1175 auto Opcode = BinOp->getOpcode();
1176 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1177
1178 buildConditionSets(S, BinOp->getOperand(0), TI, L, Domain, ConditionSets);
1179 buildConditionSets(S, BinOp->getOperand(1), TI, L, Domain, ConditionSets);
1180
1181 isl_set_free(ConditionSets.pop_back_val());
1182 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1183 isl_set_free(ConditionSets.pop_back_val());
1184 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1185
1186 if (Opcode == Instruction::And)
1187 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1188 else
1189 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1190 } else {
1191 auto *ICond = dyn_cast<ICmpInst>(Condition);
1192 assert(ICond &&
1193 "Condition of exiting branch was neither constant nor ICmp!");
1194
1195 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001196 BasicBlock *BB = TI ? TI->getParent() : nullptr;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001197 isl_pw_aff *LHS, *RHS;
1198 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1199 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
1200 ConsequenceCondSet =
1201 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1202 }
1203
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001204 // If no terminator was given we are only looking for parameter constraints
1205 // under which @p Condition is true/false.
1206 if (!TI)
1207 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
1208
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001209 assert(ConsequenceCondSet);
1210 isl_set *AlternativeCondSet =
1211 isl_set_complement(isl_set_copy(ConsequenceCondSet));
1212
1213 ConditionSets.push_back(isl_set_coalesce(
1214 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
1215 ConditionSets.push_back(isl_set_coalesce(
1216 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
1217}
1218
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001219/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1220///
1221/// This will fill @p ConditionSets with the conditions under which control
1222/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1223/// have as many elements as @p TI has successors.
1224static void
1225buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1226 __isl_keep isl_set *Domain,
1227 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1228
1229 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1230 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1231
1232 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1233
1234 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001235 ConditionSets.push_back(isl_set_copy(Domain));
1236 return;
1237 }
1238
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001239 Value *Condition = getConditionFromTerminator(TI);
1240 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001241
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001242 return buildConditionSets(S, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001243}
1244
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001245void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +00001246 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +00001247
Tobias Grosser084d8f72012-05-29 09:29:44 +00001248 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1249
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001250 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001251 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001252}
1253
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001254void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP,
1255 ScopDetection &SD) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001256 isl_ctx *Ctx = Parent.getIslCtx();
1257 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1258 Type *Ty = GEP->getPointerOperandType();
1259 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001260
1261 // The set of loads that are required to be invariant.
1262 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001263
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001264 std::vector<const SCEV *> Subscripts;
1265 std::vector<int> Sizes;
1266
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001267 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001268
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001269 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001270 Ty = PtrTy->getElementType();
1271 }
1272
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001273 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001274
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001275 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001276
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001277 for (size_t i = 0; i < Sizes.size(); i++) {
1278 auto Expr = Subscripts[i + IndexOffset];
1279 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001280
Johannes Doerfert09e36972015-10-07 20:17:36 +00001281 InvariantLoadsSetTy AccessILS;
1282 if (!isAffineExpr(&Parent.getRegion(), Expr, SE, nullptr, &AccessILS))
1283 continue;
1284
1285 bool NonAffine = false;
1286 for (LoadInst *LInst : AccessILS)
1287 if (!ScopRIL.count(LInst))
1288 NonAffine = true;
1289
1290 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001291 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001292
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001293 isl_pw_aff *AccessOffset = getPwAff(Expr);
1294 AccessOffset =
1295 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001296
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001297 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1298 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001299
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001300 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1301 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1302 OutOfBound = isl_set_params(OutOfBound);
1303 isl_set *InBound = isl_set_complement(OutOfBound);
1304 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001305
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001306 // A => B == !A or B
1307 isl_set *InBoundIfExecuted =
1308 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001309
Roman Gareev10595a12016-01-08 14:01:59 +00001310 InBoundIfExecuted = isl_set_coalesce(InBoundIfExecuted);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001311 Parent.addAssumption(INBOUNDS, InBoundIfExecuted, GEP->getDebugLoc());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001312 }
1313
1314 isl_local_space_free(LSpace);
1315}
1316
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001317void ScopStmt::deriveAssumptions(BasicBlock *Block, ScopDetection &SD) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001318 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001319 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001320 deriveAssumptionsFromGEP(GEP, SD);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001321}
1322
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001323void ScopStmt::collectSurroundingLoops() {
1324 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1325 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1326 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1327 isl_id_free(DimId);
1328 }
1329}
1330
Michael Kruse9d080092015-09-11 21:41:48 +00001331ScopStmt::ScopStmt(Scop &parent, Region &R)
Michael Krusecac948e2015-10-02 13:53:07 +00001332 : Parent(parent), Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001333
Tobias Grosser16c44032015-07-09 07:31:45 +00001334 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001335}
1336
Michael Kruse9d080092015-09-11 21:41:48 +00001337ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Michael Krusecac948e2015-10-02 13:53:07 +00001338 : Parent(parent), Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001339
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001340 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001341}
1342
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001343void ScopStmt::init(ScopDetection &SD) {
Michael Krusecac948e2015-10-02 13:53:07 +00001344 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001345
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001346 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001347 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001348 buildAccessRelations();
1349
1350 if (BB) {
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001351 deriveAssumptions(BB, SD);
Michael Krusecac948e2015-10-02 13:53:07 +00001352 } else {
1353 for (BasicBlock *Block : R->blocks()) {
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001354 deriveAssumptions(Block, SD);
Michael Krusecac948e2015-10-02 13:53:07 +00001355 }
1356 }
1357
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001358 if (DetectReductions)
1359 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001360}
1361
Johannes Doerferte58a0122014-06-27 20:31:28 +00001362/// @brief Collect loads which might form a reduction chain with @p StoreMA
1363///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001364/// Check if the stored value for @p StoreMA is a binary operator with one or
1365/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001366/// used only once (by @p StoreMA) and its load operands are also used only
1367/// once, we have found a possible reduction chain. It starts at an operand
1368/// load and includes the binary operator and @p StoreMA.
1369///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001370/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001371/// escape this block or into any other store except @p StoreMA.
1372void ScopStmt::collectCandiateReductionLoads(
1373 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1374 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1375 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001376 return;
1377
1378 // Skip if there is not one binary operator between the load and the store
1379 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001380 if (!BinOp)
1381 return;
1382
1383 // Skip if the binary operators has multiple uses
1384 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001385 return;
1386
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001387 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001388 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1389 return;
1390
Johannes Doerfert9890a052014-07-01 00:32:29 +00001391 // Skip if the binary operator is outside the current SCoP
1392 if (BinOp->getParent() != Store->getParent())
1393 return;
1394
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001395 // Skip if it is a multiplicative reduction and we disabled them
1396 if (DisableMultiplicativeReductions &&
1397 (BinOp->getOpcode() == Instruction::Mul ||
1398 BinOp->getOpcode() == Instruction::FMul))
1399 return;
1400
Johannes Doerferte58a0122014-06-27 20:31:28 +00001401 // Check the binary operator operands for a candidate load
1402 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1403 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1404 if (!PossibleLoad0 && !PossibleLoad1)
1405 return;
1406
1407 // A load is only a candidate if it cannot escape (thus has only this use)
1408 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001409 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001410 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001411 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001412 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001413 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001414}
1415
1416/// @brief Check for reductions in this ScopStmt
1417///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001418/// Iterate over all store memory accesses and check for valid binary reduction
1419/// like chains. For all candidates we check if they have the same base address
1420/// and there are no other accesses which overlap with them. The base address
1421/// check rules out impossible reductions candidates early. The overlap check,
1422/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001423/// guarantees that none of the intermediate results will escape during
1424/// execution of the loop nest. We basically check here that no other memory
1425/// access can access the same memory as the potential reduction.
1426void ScopStmt::checkForReductions() {
1427 SmallVector<MemoryAccess *, 2> Loads;
1428 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1429
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001430 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001431 // stores and collecting possible reduction loads.
1432 for (MemoryAccess *StoreMA : MemAccs) {
1433 if (StoreMA->isRead())
1434 continue;
1435
1436 Loads.clear();
1437 collectCandiateReductionLoads(StoreMA, Loads);
1438 for (MemoryAccess *LoadMA : Loads)
1439 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1440 }
1441
1442 // Then check each possible candidate pair.
1443 for (const auto &CandidatePair : Candidates) {
1444 bool Valid = true;
1445 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1446 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1447
1448 // Skip those with obviously unequal base addresses.
1449 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1450 isl_map_free(LoadAccs);
1451 isl_map_free(StoreAccs);
1452 continue;
1453 }
1454
1455 // And check if the remaining for overlap with other memory accesses.
1456 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1457 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1458 isl_set *AllAccs = isl_map_range(AllAccsRel);
1459
1460 for (MemoryAccess *MA : MemAccs) {
1461 if (MA == CandidatePair.first || MA == CandidatePair.second)
1462 continue;
1463
1464 isl_map *AccRel =
1465 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1466 isl_set *Accs = isl_map_range(AccRel);
1467
1468 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1469 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1470 Valid = Valid && isl_set_is_empty(OverlapAccs);
1471 isl_set_free(OverlapAccs);
1472 }
1473 }
1474
1475 isl_set_free(AllAccs);
1476 if (!Valid)
1477 continue;
1478
Johannes Doerfertf6183392014-07-01 20:52:51 +00001479 const LoadInst *Load =
1480 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1481 MemoryAccess::ReductionType RT =
1482 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1483
Johannes Doerferte58a0122014-06-27 20:31:28 +00001484 // If no overlapping access was found we mark the load and store as
1485 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001486 CandidatePair.first->markAsReductionLike(RT);
1487 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001488 }
Tobias Grosser75805372011-04-29 06:27:02 +00001489}
1490
Tobias Grosser74394f02013-01-14 22:40:23 +00001491std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001492
Tobias Grosser54839312015-04-21 11:37:25 +00001493std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001494 auto *S = getSchedule();
1495 auto Str = stringFromIslObj(S);
1496 isl_map_free(S);
1497 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001498}
1499
Tobias Grosser74394f02013-01-14 22:40:23 +00001500unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001501
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001502unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001503
Tobias Grosser75805372011-04-29 06:27:02 +00001504const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1505
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001506const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001507 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001508}
1509
Tobias Grosser74394f02013-01-14 22:40:23 +00001510isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001511
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001512__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001513
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001514__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001515 return isl_set_get_space(Domain);
1516}
1517
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001518__isl_give isl_id *ScopStmt::getDomainId() const {
1519 return isl_set_get_tuple_id(Domain);
1520}
Tobias Grossercd95b772012-08-30 11:49:38 +00001521
Tobias Grosser10120182015-12-16 16:14:03 +00001522ScopStmt::~ScopStmt() { isl_set_free(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001523
1524void ScopStmt::print(raw_ostream &OS) const {
1525 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001526 OS.indent(12) << "Domain :=\n";
1527
1528 if (Domain) {
1529 OS.indent(16) << getDomainStr() << ";\n";
1530 } else
1531 OS.indent(16) << "n/a\n";
1532
Tobias Grosser54839312015-04-21 11:37:25 +00001533 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001534
1535 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001536 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001537 } else
1538 OS.indent(16) << "n/a\n";
1539
Tobias Grosser083d3d32014-06-28 08:59:45 +00001540 for (MemoryAccess *Access : MemAccs)
1541 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001542}
1543
1544void ScopStmt::dump() const { print(dbgs()); }
1545
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001546void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001547 // Remove all memory accesses in @p InvMAs from this statement
1548 // together with all scalar accesses that were caused by them.
Michael Krusead28e5a2016-01-26 13:33:15 +00001549 // MK_Value READs have no access instruction, hence would not be removed by
1550 // this function. However, it is only used for invariant LoadInst accesses,
1551 // its arguments are always affine, hence synthesizable, and therefore there
1552 // are no MK_Value READ accesses to be removed.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001553 for (MemoryAccess *MA : InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001554 auto Predicate = [&](MemoryAccess *Acc) {
Tobias Grosser3a6ac9f2015-11-30 21:13:43 +00001555 return Acc->getAccessInstruction() == MA->getAccessInstruction();
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001556 };
1557 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1558 MemAccs.end());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001559 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001560 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001561}
1562
Tobias Grosser75805372011-04-29 06:27:02 +00001563//===----------------------------------------------------------------------===//
1564/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001565
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001566void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001567 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1568 isl_set_free(Context);
1569 Context = NewContext;
1570}
1571
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001572/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1573struct SCEVSensitiveParameterRewriter
1574 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1575 ValueToValueMap &VMap;
1576 ScalarEvolution &SE;
1577
1578public:
1579 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1580 : VMap(VMap), SE(SE) {}
1581
1582 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1583 ValueToValueMap &VMap) {
1584 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1585 return SSPR.visit(E);
1586 }
1587
1588 const SCEV *visit(const SCEV *E) {
1589 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1590 }
1591
1592 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1593
1594 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1595 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1596 }
1597
1598 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1599 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1600 }
1601
1602 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1603 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1604 }
1605
1606 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1607 SmallVector<const SCEV *, 4> Operands;
1608 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1609 Operands.push_back(visit(E->getOperand(i)));
1610 return SE.getAddExpr(Operands);
1611 }
1612
1613 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1614 SmallVector<const SCEV *, 4> Operands;
1615 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1616 Operands.push_back(visit(E->getOperand(i)));
1617 return SE.getMulExpr(Operands);
1618 }
1619
1620 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1621 SmallVector<const SCEV *, 4> Operands;
1622 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1623 Operands.push_back(visit(E->getOperand(i)));
1624 return SE.getSMaxExpr(Operands);
1625 }
1626
1627 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1628 SmallVector<const SCEV *, 4> Operands;
1629 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1630 Operands.push_back(visit(E->getOperand(i)));
1631 return SE.getUMaxExpr(Operands);
1632 }
1633
1634 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1635 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1636 }
1637
1638 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1639 auto *Start = visit(E->getStart());
1640 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1641 visit(E->getStepRecurrence(SE)),
1642 E->getLoop(), SCEV::FlagAnyWrap);
1643 return SE.getAddExpr(Start, AddRec);
1644 }
1645
1646 const SCEV *visitUnknown(const SCEVUnknown *E) {
1647 if (auto *NewValue = VMap.lookup(E->getValue()))
1648 return SE.getUnknown(NewValue);
1649 return E;
1650 }
1651};
1652
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001653const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001654 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001655}
1656
Tobias Grosserabfbe632013-02-05 12:09:06 +00001657void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001658 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001659 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001660
1661 // Normalize the SCEV to get the representing element for an invariant load.
1662 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1663
Tobias Grosser60b54f12011-11-08 15:41:28 +00001664 if (ParameterIds.find(Parameter) != ParameterIds.end())
1665 continue;
1666
1667 int dimension = Parameters.size();
1668
1669 Parameters.push_back(Parameter);
1670 ParameterIds[Parameter] = dimension;
1671 }
1672}
1673
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001674__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001675 // Normalize the SCEV to get the representing element for an invariant load.
1676 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1677
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001678 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001679
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001680 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001681 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001682
Tobias Grosser8f99c162011-11-15 11:38:55 +00001683 std::string ParameterName;
1684
Craig Topper7fb6e472016-01-31 20:36:20 +00001685 ParameterName = "p_" + utostr(IdIter->second);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001686
Tobias Grosser8f99c162011-11-15 11:38:55 +00001687 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1688 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001689
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001690 // If this parameter references a specific Value and this value has a name
1691 // we use this name as it is likely to be unique and more useful than just
1692 // a number.
1693 if (Val->hasName())
1694 ParameterName = Val->getName();
1695 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
1696 auto LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
1697 if (LoadOrigin->hasName()) {
1698 ParameterName += "_loaded_from_";
1699 ParameterName +=
1700 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1701 }
1702 }
1703 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001704
Tobias Grosser20532b82014-04-11 17:56:49 +00001705 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1706 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001707}
Tobias Grosser75805372011-04-29 06:27:02 +00001708
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001709isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1710 isl_set *DomainContext = isl_union_set_params(getDomains());
1711 return isl_set_intersect_params(C, DomainContext);
1712}
1713
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001714void Scop::buildBoundaryContext() {
Tobias Grosser4927c8e2015-11-24 12:50:02 +00001715 if (IgnoreIntegerWrapping) {
1716 BoundaryContext = isl_set_universe(getParamSpace());
1717 return;
1718 }
1719
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001720 BoundaryContext = Affinator.getWrappingContext();
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001721
1722 // The isl_set_complement operation used to create the boundary context
1723 // can possibly become very expensive. We bound the compile time of
1724 // this operation by setting a compute out.
1725 //
1726 // TODO: We can probably get around using isl_set_complement and directly
1727 // AST generate BoundaryContext.
1728 long MaxOpsOld = isl_ctx_get_max_operations(getIslCtx());
Tobias Grosserf920fb12015-11-13 16:56:13 +00001729 isl_ctx_reset_operations(getIslCtx());
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001730 isl_ctx_set_max_operations(getIslCtx(), 300000);
1731 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_CONTINUE);
1732
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001733 BoundaryContext = isl_set_complement(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001734
Tobias Grossera52b4da2015-11-11 17:59:53 +00001735 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
1736 isl_set_free(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001737 BoundaryContext = isl_set_empty(getParamSpace());
Tobias Grossera52b4da2015-11-11 17:59:53 +00001738 }
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001739
1740 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
1741 isl_ctx_reset_operations(getIslCtx());
1742 isl_ctx_set_max_operations(getIslCtx(), MaxOpsOld);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001743 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001744 trackAssumption(WRAPPING, BoundaryContext, DebugLoc());
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001745}
1746
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00001747void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001748 auto *R = &getRegion();
1749 auto &F = *R->getEntry()->getParent();
1750 for (auto &Assumption : AC.assumptions()) {
1751 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1752 if (!CI || CI->getNumArgOperands() != 1)
1753 continue;
1754 if (!DT.dominates(CI->getParent(), R->getEntry()))
1755 continue;
1756
1757 auto *Val = CI->getArgOperand(0);
1758 std::vector<const SCEV *> Params;
1759 if (!isAffineParamConstraint(Val, R, *SE, Params)) {
1760 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1761 CI->getDebugLoc(),
1762 "Non-affine user assumption ignored.");
1763 continue;
1764 }
1765
1766 addParams(Params);
1767
1768 auto *L = LI.getLoopFor(CI->getParent());
1769 SmallVector<isl_set *, 2> ConditionSets;
1770 buildConditionSets(*this, Val, nullptr, L, Context, ConditionSets);
1771 assert(ConditionSets.size() == 2);
1772 isl_set_free(ConditionSets[1]);
1773
1774 auto *AssumptionCtx = ConditionSets[0];
1775 emitOptimizationRemarkAnalysis(
1776 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1777 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1778 Context = isl_set_intersect(Context, AssumptionCtx);
1779 }
1780}
1781
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001782void Scop::addUserContext() {
1783 if (UserContextStr.empty())
1784 return;
1785
1786 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1787 isl_space *Space = getParamSpace();
1788 if (isl_space_dim(Space, isl_dim_param) !=
1789 isl_set_dim(UserContext, isl_dim_param)) {
1790 auto SpaceStr = isl_space_to_str(Space);
1791 errs() << "Error: the context provided in -polly-context has not the same "
1792 << "number of dimensions than the computed context. Due to this "
1793 << "mismatch, the -polly-context option is ignored. Please provide "
1794 << "the context in the parameter space: " << SpaceStr << ".\n";
1795 free(SpaceStr);
1796 isl_set_free(UserContext);
1797 isl_space_free(Space);
1798 return;
1799 }
1800
1801 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1802 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1803 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1804
1805 if (strcmp(NameContext, NameUserContext) != 0) {
1806 auto SpaceStr = isl_space_to_str(Space);
1807 errs() << "Error: the name of dimension " << i
1808 << " provided in -polly-context "
1809 << "is '" << NameUserContext << "', but the name in the computed "
1810 << "context is '" << NameContext
1811 << "'. Due to this name mismatch, "
1812 << "the -polly-context option is ignored. Please provide "
1813 << "the context in the parameter space: " << SpaceStr << ".\n";
1814 free(SpaceStr);
1815 isl_set_free(UserContext);
1816 isl_space_free(Space);
1817 return;
1818 }
1819
1820 UserContext =
1821 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1822 isl_space_get_dim_id(Space, isl_dim_param, i));
1823 }
1824
1825 Context = isl_set_intersect(Context, UserContext);
1826 isl_space_free(Space);
1827}
1828
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001829void Scop::buildInvariantEquivalenceClasses(ScopDetection &SD) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00001830 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001831
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001832 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001833 for (LoadInst *LInst : RIL) {
1834 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1835
Johannes Doerfert96e54712016-02-07 17:30:13 +00001836 Type *Ty = LInst->getType();
1837 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001838 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001839 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001840 continue;
1841 }
1842
1843 ClassRep = LInst;
Johannes Doerfert96e54712016-02-07 17:30:13 +00001844 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(), nullptr,
1845 Ty);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001846 }
1847}
1848
Tobias Grosser6be480c2011-11-08 15:41:13 +00001849void Scop::buildContext() {
1850 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001851 Context = isl_set_universe(isl_space_copy(Space));
1852 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001853}
1854
Tobias Grosser18daaca2012-05-22 10:47:27 +00001855void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001856 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001857 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001858
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001859 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001860
Johannes Doerferte7044942015-02-24 11:58:30 +00001861 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001862 }
1863}
1864
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001865void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001866 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001867 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001868
Tobias Grosser083d3d32014-06-28 08:59:45 +00001869 for (const auto &ParamID : ParameterIds) {
1870 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001871 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001872 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001873 }
1874
1875 // Align the parameters of all data structures to the model.
1876 Context = isl_set_align_params(Context, Space);
1877
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001878 for (ScopStmt &Stmt : *this)
1879 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001880}
1881
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001882static __isl_give isl_set *
1883simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1884 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001885 // If we modelt all blocks in the SCoP that have side effects we can simplify
1886 // the context with the constraints that are needed for anything to be
1887 // executed at all. However, if we have error blocks in the SCoP we already
1888 // assumed some parameter combinations cannot occure and removed them from the
1889 // domains, thus we cannot use the remaining domain to simplify the
1890 // assumptions.
1891 if (!S.hasErrorBlock()) {
1892 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1893 AssumptionContext =
1894 isl_set_gist_params(AssumptionContext, DomainParameters);
1895 }
1896
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001897 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1898 return AssumptionContext;
1899}
1900
1901void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001902 // The parameter constraints of the iteration domains give us a set of
1903 // constraints that need to hold for all cases where at least a single
1904 // statement iteration is executed in the whole scop. We now simplify the
1905 // assumed context under the assumption that such constraints hold and at
1906 // least a single statement iteration is executed. For cases where no
1907 // statement instances are executed, the assumptions we have taken about
1908 // the executed code do not matter and can be changed.
1909 //
1910 // WARNING: This only holds if the assumptions we have taken do not reduce
1911 // the set of statement instances that are executed. Otherwise we
1912 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001913 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001914 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001915 // performed. In such a case, modifying the run-time conditions and
1916 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001917 // to not be executed.
1918 //
1919 // Example:
1920 //
1921 // When delinearizing the following code:
1922 //
1923 // for (long i = 0; i < 100; i++)
1924 // for (long j = 0; j < m; j++)
1925 // A[i+p][j] = 1.0;
1926 //
1927 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001928 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001929 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001930 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1931 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001932}
1933
Johannes Doerfertb164c792014-09-18 11:17:17 +00001934/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001935static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001936 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1937 isl_pw_multi_aff *MinPMA, *MaxPMA;
1938 isl_pw_aff *LastDimAff;
1939 isl_aff *OneAff;
1940 unsigned Pos;
1941
Johannes Doerfert9143d672014-09-27 11:02:39 +00001942 // Restrict the number of parameters involved in the access as the lexmin/
1943 // lexmax computation will take too long if this number is high.
1944 //
1945 // Experiments with a simple test case using an i7 4800MQ:
1946 //
1947 // #Parameters involved | Time (in sec)
1948 // 6 | 0.01
1949 // 7 | 0.04
1950 // 8 | 0.12
1951 // 9 | 0.40
1952 // 10 | 1.54
1953 // 11 | 6.78
1954 // 12 | 30.38
1955 //
1956 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1957 unsigned InvolvedParams = 0;
1958 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1959 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1960 InvolvedParams++;
1961
1962 if (InvolvedParams > RunTimeChecksMaxParameters) {
1963 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001964 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001965 }
1966 }
1967
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001968 Set = isl_set_remove_divs(Set);
1969
Johannes Doerfertb164c792014-09-18 11:17:17 +00001970 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1971 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1972
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001973 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1974 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1975
Johannes Doerfertb164c792014-09-18 11:17:17 +00001976 // Adjust the last dimension of the maximal access by one as we want to
1977 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1978 // we test during code generation might now point after the end of the
1979 // allocated array but we will never dereference it anyway.
1980 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1981 "Assumed at least one output dimension");
1982 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1983 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1984 OneAff = isl_aff_zero_on_domain(
1985 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1986 OneAff = isl_aff_add_constant_si(OneAff, 1);
1987 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1988 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1989
1990 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1991
1992 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001993 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001994}
1995
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001996static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1997 isl_set *Domain = MA->getStatement()->getDomain();
1998 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1999 return isl_set_reset_tuple_id(Domain);
2000}
2001
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002002/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
2003static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00002004 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002005 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002006
2007 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2008 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002009 Locations = isl_union_set_coalesce(Locations);
2010 Locations = isl_union_set_detect_equalities(Locations);
2011 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002012 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002013 isl_union_set_free(Locations);
2014 return Valid;
2015}
2016
Johannes Doerfert96425c22015-08-30 21:13:53 +00002017/// @brief Helper to treat non-affine regions and basic blocks the same.
2018///
2019///{
2020
2021/// @brief Return the block that is the representing block for @p RN.
2022static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2023 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2024 : RN->getNodeAs<BasicBlock>();
2025}
2026
2027/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002028static inline BasicBlock *
2029getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002030 if (RN->isSubRegion()) {
2031 assert(idx == 0);
2032 return RN->getNodeAs<Region>()->getExit();
2033 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002034 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002035}
2036
2037/// @brief Return the smallest loop surrounding @p RN.
2038static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2039 if (!RN->isSubRegion())
2040 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2041
2042 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2043 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2044 while (L && NonAffineSubRegion->contains(L))
2045 L = L->getParentLoop();
2046 return L;
2047}
2048
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002049static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2050 if (!RN->isSubRegion())
2051 return 1;
2052
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002053 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002054 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002055}
2056
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002057static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2058 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002059 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002060 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002061 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002062 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002063 return true;
2064 return false;
2065}
2066
Johannes Doerfert96425c22015-08-30 21:13:53 +00002067///}
2068
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002069static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2070 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002071 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002072 isl_id *DimId =
2073 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2074 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2075}
2076
Johannes Doerfert96425c22015-08-30 21:13:53 +00002077isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
2078 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
2079 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002080 return getDomainConditions(BB);
2081}
2082
2083isl_set *Scop::getDomainConditions(BasicBlock *BB) {
2084 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002085 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002086}
2087
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002088void Scop::removeErrorBlockDomains(ScopDetection &SD, DominatorTree &DT) {
2089 auto removeDomains = [this, &DT](BasicBlock *Start) {
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002090 auto BBNode = DT.getNode(Start);
2091 for (auto ErrorChild : depth_first(BBNode)) {
2092 auto ErrorChildBlock = ErrorChild->getBlock();
2093 auto CurrentDomain = DomainMap[ErrorChildBlock];
2094 auto Empty = isl_set_empty(isl_set_get_space(CurrentDomain));
2095 DomainMap[ErrorChildBlock] = Empty;
2096 isl_set_free(CurrentDomain);
2097 }
2098 };
2099
Tobias Grosser5ef2bc32015-11-23 10:18:23 +00002100 SmallVector<Region *, 4> Todo = {&R};
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002101
2102 while (!Todo.empty()) {
2103 auto SubRegion = Todo.back();
2104 Todo.pop_back();
2105
2106 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
2107 for (auto &Child : *SubRegion)
2108 Todo.push_back(Child.get());
2109 continue;
2110 }
2111 if (containsErrorBlock(SubRegion->getNode(), getRegion(), LI, DT))
2112 removeDomains(SubRegion->getEntry());
2113 }
2114
2115 for (auto BB : R.blocks())
2116 if (isErrorBlock(*BB, R, LI, DT))
2117 removeDomains(BB);
2118}
2119
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002120void Scop::buildDomains(Region *R, ScopDetection &SD, DominatorTree &DT) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002121
Johannes Doerfert432658d2016-01-26 11:01:41 +00002122 bool IsOnlyNonAffineRegion = SD.isNonAffineSubRegion(R, R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002123 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002124 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2125 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002126 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002127
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002128 while (LD-- >= 0) {
2129 S = addDomainDimId(S, LD + 1, L);
2130 L = L->getParentLoop();
2131 }
2132
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002133 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002134
Johannes Doerfert432658d2016-01-26 11:01:41 +00002135 if (IsOnlyNonAffineRegion)
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002136 return;
2137
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002138 buildDomainsWithBranchConstraints(R, SD, DT);
2139 propagateDomainConstraints(R, SD, DT);
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002140
2141 // Error blocks and blocks dominated by them have been assumed to never be
2142 // executed. Representing them in the Scop does not add any value. In fact,
2143 // it is likely to cause issues during construction of the ScopStmts. The
2144 // contents of error blocks have not been verfied to be expressible and
2145 // will cause problems when building up a ScopStmt for them.
2146 // Furthermore, basic blocks dominated by error blocks may reference
2147 // instructions in the error block which, if the error block is not modeled,
2148 // can themselves not be constructed properly.
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002149 removeErrorBlockDomains(SD, DT);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002150}
2151
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002152void Scop::buildDomainsWithBranchConstraints(Region *R, ScopDetection &SD,
2153 DominatorTree &DT) {
Johannes Doerfert6f50c292016-01-26 11:03:25 +00002154 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002155
2156 // To create the domain for each block in R we iterate over all blocks and
2157 // subregions in R and propagate the conditions under which the current region
2158 // element is executed. To this end we iterate in reverse post order over R as
2159 // it ensures that we first visit all predecessors of a region node (either a
2160 // basic block or a subregion) before we visit the region node itself.
2161 // Initially, only the domain for the SCoP region entry block is set and from
2162 // there we propagate the current domain to all successors, however we add the
2163 // condition that the successor is actually executed next.
2164 // As we are only interested in non-loop carried constraints here we can
2165 // simply skip loop back edges.
2166
2167 ReversePostOrderTraversal<Region *> RTraversal(R);
2168 for (auto *RN : RTraversal) {
2169
2170 // Recurse for affine subregions but go on for basic blocks and non-affine
2171 // subregions.
2172 if (RN->isSubRegion()) {
2173 Region *SubRegion = RN->getNodeAs<Region>();
2174 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002175 buildDomainsWithBranchConstraints(SubRegion, SD, DT);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002176 continue;
2177 }
2178 }
2179
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002180 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002181 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002182
Johannes Doerfert96425c22015-08-30 21:13:53 +00002183 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002184 TerminatorInst *TI = BB->getTerminator();
2185
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002186 if (isa<UnreachableInst>(TI))
2187 continue;
2188
Johannes Doerfertf5673802015-10-01 23:48:18 +00002189 isl_set *Domain = DomainMap.lookup(BB);
2190 if (!Domain) {
2191 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2192 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002193 continue;
2194 }
2195
Johannes Doerfert96425c22015-08-30 21:13:53 +00002196 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002197
2198 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2199 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2200
2201 // Build the condition sets for the successor nodes of the current region
2202 // node. If it is a non-affine subregion we will always execute the single
2203 // exit node, hence the single entry node domain is the condition set. For
2204 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002205 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002206 if (RN->isSubRegion())
2207 ConditionSets.push_back(isl_set_copy(Domain));
2208 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002209 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002210
2211 // Now iterate over the successors and set their initial domain based on
2212 // their condition set. We skip back edges here and have to be careful when
2213 // we leave a loop not to keep constraints over a dimension that doesn't
2214 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002215 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002216 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002217 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002218 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002219
2220 // Skip back edges.
2221 if (DT.dominates(SuccBB, BB)) {
2222 isl_set_free(CondSet);
2223 continue;
2224 }
2225
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002226 // Do not adjust the number of dimensions if we enter a boxed loop or are
2227 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002228 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfert6f50c292016-01-26 11:03:25 +00002229 while (BoxedLoops.count(SuccBBLoop))
2230 SuccBBLoop = SuccBBLoop->getParentLoop();
Johannes Doerfert634909c2015-10-04 14:57:41 +00002231
2232 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002233
2234 // Check if the edge to SuccBB is a loop entry or exit edge. If so
2235 // adjust the dimensionality accordingly. Lastly, if we leave a loop
2236 // and enter a new one we need to drop the old constraints.
2237 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002238 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002239 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002240 CondSet = isl_set_project_out(CondSet, isl_dim_set,
2241 isl_set_n_dim(CondSet) - LoopDepthDiff,
2242 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002243 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002244 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002245 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002246 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002247 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002248 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002249 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
2250 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002251 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002252 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002253 }
2254
2255 // Set the domain for the successor or merge it with an existing domain in
2256 // case there are multiple paths (without loop back edges) to the
2257 // successor block.
2258 isl_set *&SuccDomain = DomainMap[SuccBB];
2259 if (!SuccDomain)
2260 SuccDomain = CondSet;
2261 else
2262 SuccDomain = isl_set_union(SuccDomain, CondSet);
2263
2264 SuccDomain = isl_set_coalesce(SuccDomain);
Tobias Grosser75dc40c2015-12-20 13:31:48 +00002265 if (isl_set_n_basic_set(SuccDomain) > MaxConjunctsInDomain) {
2266 auto *Empty = isl_set_empty(isl_set_get_space(SuccDomain));
2267 isl_set_free(SuccDomain);
2268 SuccDomain = Empty;
2269 invalidate(ERROR_DOMAINCONJUNCTS, DebugLoc());
2270 }
Johannes Doerfert634909c2015-10-04 14:57:41 +00002271 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
2272 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002273 }
2274 }
2275}
2276
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002277/// @brief Return the domain for @p BB wrt @p DomainMap.
2278///
2279/// This helper function will lookup @p BB in @p DomainMap but also handle the
2280/// case where @p BB is contained in a non-affine subregion using the region
2281/// tree obtained by @p RI.
2282static __isl_give isl_set *
2283getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
2284 RegionInfo &RI) {
2285 auto DIt = DomainMap.find(BB);
2286 if (DIt != DomainMap.end())
2287 return isl_set_copy(DIt->getSecond());
2288
2289 Region *R = RI.getRegionFor(BB);
2290 while (R->getEntry() == BB)
2291 R = R->getParent();
2292 return getDomainForBlock(R->getEntry(), DomainMap, RI);
2293}
2294
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002295void Scop::propagateDomainConstraints(Region *R, ScopDetection &SD,
2296 DominatorTree &DT) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002297 // Iterate over the region R and propagate the domain constrains from the
2298 // predecessors to the current node. In contrast to the
2299 // buildDomainsWithBranchConstraints function, this one will pull the domain
2300 // information from the predecessors instead of pushing it to the successors.
2301 // Additionally, we assume the domains to be already present in the domain
2302 // map here. However, we iterate again in reverse post order so we know all
2303 // predecessors have been visited before a block or non-affine subregion is
2304 // visited.
2305
2306 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2307 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2308
2309 ReversePostOrderTraversal<Region *> RTraversal(R);
2310 for (auto *RN : RTraversal) {
2311
2312 // Recurse for affine subregions but go on for basic blocks and non-affine
2313 // subregions.
2314 if (RN->isSubRegion()) {
2315 Region *SubRegion = RN->getNodeAs<Region>();
2316 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002317 propagateDomainConstraints(SubRegion, SD, DT);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002318 continue;
2319 }
2320 }
2321
Johannes Doerfertf5673802015-10-01 23:48:18 +00002322 // Get the domain for the current block and check if it was initialized or
2323 // not. The only way it was not is if this block is only reachable via error
2324 // blocks, thus will not be executed under the assumptions we make. Such
2325 // blocks have to be skipped as their predecessors might not have domains
2326 // either. It would not benefit us to compute the domain anyway, only the
2327 // domains of the error blocks that are reachable from non-error blocks
2328 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002329 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002330 isl_set *&Domain = DomainMap[BB];
2331 if (!Domain) {
2332 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2333 << ", it is only reachable from error blocks.\n");
2334 DomainMap.erase(BB);
2335 continue;
2336 }
2337 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
2338
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002339 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2340 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2341
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002342 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2343 for (auto *PredBB : predecessors(BB)) {
2344
2345 // Skip backedges
2346 if (DT.dominates(BB, PredBB))
2347 continue;
2348
2349 isl_set *PredBBDom = nullptr;
2350
2351 // Handle the SCoP entry block with its outside predecessors.
2352 if (!getRegion().contains(PredBB))
2353 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
2354
2355 if (!PredBBDom) {
2356 // Determine the loop depth of the predecessor and adjust its domain to
2357 // the domain of the current block. This can mean we have to:
2358 // o) Drop a dimension if this block is the exit of a loop, not the
2359 // header of a new loop and the predecessor was part of the loop.
2360 // o) Add an unconstrainted new dimension if this block is the header
2361 // of a loop and the predecessor is not part of it.
2362 // o) Drop the information about the innermost loop dimension when the
2363 // predecessor and the current block are surrounded by different
2364 // loops in the same depth.
2365 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2366 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2367 while (BoxedLoops.count(PredBBLoop))
2368 PredBBLoop = PredBBLoop->getParentLoop();
2369
2370 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002371 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002372 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002373 PredBBDom = isl_set_project_out(
2374 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2375 LoopDepthDiff);
2376 else if (PredBBLoopDepth < BBLoopDepth) {
2377 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002378 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002379 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2380 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002381 PredBBDom = isl_set_drop_constraints_involving_dims(
2382 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002383 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002384 }
2385
2386 PredDom = isl_set_union(PredDom, PredBBDom);
2387 }
2388
2389 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002390 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002391
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002392 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002393 addLoopBoundsToHeaderDomain(BBLoop);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002394
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002395 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002396 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002397 IsOptimized = true;
2398 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002399 addAssumption(ERRORBLOCK, isl_set_complement(DomPar),
2400 BB->getTerminator()->getDebugLoc());
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002401 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002402 }
2403}
2404
2405/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2406/// is incremented by one and all other dimensions are equal, e.g.,
2407/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2408/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2409static __isl_give isl_map *
2410createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2411 auto *MapSpace = isl_space_map_from_set(SetSpace);
2412 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2413 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2414 if (u != Dim)
2415 NextIterationMap =
2416 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2417 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2418 C = isl_constraint_set_constant_si(C, 1);
2419 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2420 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2421 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2422 return NextIterationMap;
2423}
2424
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002425void Scop::addLoopBoundsToHeaderDomain(Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002426 int LoopDepth = getRelativeLoopDepth(L);
2427 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002428
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002429 BasicBlock *HeaderBB = L->getHeader();
2430 assert(DomainMap.count(HeaderBB));
2431 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002432
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002433 isl_map *NextIterationMap =
2434 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002435
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002436 isl_set *UnionBackedgeCondition =
2437 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002438
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002439 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2440 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002441
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002442 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002443
2444 // If the latch is only reachable via error statements we skip it.
2445 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2446 if (!LatchBBDom)
2447 continue;
2448
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002449 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002450
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002451 TerminatorInst *TI = LatchBB->getTerminator();
2452 BranchInst *BI = dyn_cast<BranchInst>(TI);
2453 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002454 BackedgeCondition = isl_set_copy(LatchBBDom);
2455 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002456 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002457 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002458 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002459
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002460 // Free the non back edge condition set as we do not need it.
2461 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002462
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002463 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002464 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002465
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002466 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2467 assert(LatchLoopDepth >= LoopDepth);
2468 BackedgeCondition =
2469 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2470 LatchLoopDepth - LoopDepth);
2471 UnionBackedgeCondition =
2472 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002473 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002474
2475 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2476 for (int i = 0; i < LoopDepth; i++)
2477 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2478
2479 isl_set *UnionBackedgeConditionComplement =
2480 isl_set_complement(UnionBackedgeCondition);
2481 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2482 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2483 UnionBackedgeConditionComplement =
2484 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2485 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2486 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2487
2488 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2489 HeaderBBDom = Parts.second;
2490
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002491 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2492 // the bounded assumptions to the context as they are already implied by the
2493 // <nsw> tag.
2494 if (Affinator.hasNSWAddRecForLoop(L)) {
2495 isl_set_free(Parts.first);
2496 return;
2497 }
2498
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002499 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2500 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002501 addAssumption(INFINITELOOP, BoundedCtx,
2502 HeaderBB->getTerminator()->getDebugLoc());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002503}
2504
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002505void Scop::buildAliasChecks(AliasAnalysis &AA) {
2506 if (!PollyUseRuntimeAliasChecks)
2507 return;
2508
2509 if (buildAliasGroups(AA))
2510 return;
2511
2512 // If a problem occurs while building the alias groups we need to delete
2513 // this SCoP and pretend it wasn't valid in the first place. To this end
2514 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002515 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002516
2517 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2518 << " could not be created as the number of parameters involved "
2519 "is too high. The SCoP will be "
2520 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2521 "the maximal number of parameters but be advised that the "
2522 "compile time might increase exponentially.\n\n");
2523}
2524
Johannes Doerfert9143d672014-09-27 11:02:39 +00002525bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002526 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002527 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002528 // for all memory accesses inside the SCoP.
2529 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002530 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002531 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002532 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002533 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002534 // if their access domains intersect, otherwise they are in different
2535 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002536 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002537 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002538 // and maximal accesses to each array of a group in read only and non
2539 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002540 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2541
2542 AliasSetTracker AST(AA);
2543
2544 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002545 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002546 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002547
2548 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002549 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002550 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2551 isl_set_free(StmtDomain);
2552 if (StmtDomainEmpty)
2553 continue;
2554
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002555 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002556 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002557 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002558 if (!MA->isRead())
2559 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002560 MemAccInst Acc(MA->getAccessInstruction());
2561 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002562 AST.add(Acc);
2563 }
2564 }
2565
2566 SmallVector<AliasGroupTy, 4> AliasGroups;
2567 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002568 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002569 continue;
2570 AliasGroupTy AG;
2571 for (auto PR : AS)
2572 AG.push_back(PtrToAcc[PR.getValue()]);
2573 assert(AG.size() > 1 &&
2574 "Alias groups should contain at least two accesses");
2575 AliasGroups.push_back(std::move(AG));
2576 }
2577
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002578 // Split the alias groups based on their domain.
2579 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2580 AliasGroupTy NewAG;
2581 AliasGroupTy &AG = AliasGroups[u];
2582 AliasGroupTy::iterator AGI = AG.begin();
2583 isl_set *AGDomain = getAccessDomain(*AGI);
2584 while (AGI != AG.end()) {
2585 MemoryAccess *MA = *AGI;
2586 isl_set *MADomain = getAccessDomain(MA);
2587 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2588 NewAG.push_back(MA);
2589 AGI = AG.erase(AGI);
2590 isl_set_free(MADomain);
2591 } else {
2592 AGDomain = isl_set_union(AGDomain, MADomain);
2593 AGI++;
2594 }
2595 }
2596 if (NewAG.size() > 1)
2597 AliasGroups.push_back(std::move(NewAG));
2598 isl_set_free(AGDomain);
2599 }
2600
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002601 auto &F = *getRegion().getEntry()->getParent();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002602 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002603 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2604 for (AliasGroupTy &AG : AliasGroups) {
2605 NonReadOnlyBaseValues.clear();
2606 ReadOnlyPairs.clear();
2607
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002608 if (AG.size() < 2) {
2609 AG.clear();
2610 continue;
2611 }
2612
Johannes Doerfert13771732014-10-01 12:40:46 +00002613 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002614 emitOptimizationRemarkAnalysis(
2615 F.getContext(), DEBUG_TYPE, F,
2616 (*II)->getAccessInstruction()->getDebugLoc(),
2617 "Possibly aliasing pointer, use restrict keyword.");
2618
Johannes Doerfert13771732014-10-01 12:40:46 +00002619 Value *BaseAddr = (*II)->getBaseAddr();
2620 if (HasWriteAccess.count(BaseAddr)) {
2621 NonReadOnlyBaseValues.insert(BaseAddr);
2622 II++;
2623 } else {
2624 ReadOnlyPairs[BaseAddr].insert(*II);
2625 II = AG.erase(II);
2626 }
2627 }
2628
2629 // If we don't have read only pointers check if there are at least two
2630 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002631 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002632 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002633 continue;
2634 }
2635
2636 // If we don't have non read only pointers clear the alias group.
2637 if (NonReadOnlyBaseValues.empty()) {
2638 AG.clear();
2639 continue;
2640 }
2641
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002642 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002643 MinMaxAliasGroups.emplace_back();
2644 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2645 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2646 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2647 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002648
2649 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002650
2651 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002652 for (MemoryAccess *MA : AG)
2653 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002654
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002655 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2656 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002657
2658 // Bail out if the number of values we need to compare is too large.
2659 // This is important as the number of comparisions grows quadratically with
2660 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002661 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2662 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002663 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002664
2665 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002666 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002667 Accesses = isl_union_map_empty(getParamSpace());
2668
2669 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2670 for (MemoryAccess *MA : ReadOnlyPair.second)
2671 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2672
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002673 Valid =
2674 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002675
2676 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002677 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002678 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002679
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002680 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002681}
2682
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002683/// @brief Get the smallest loop that contains @p R but is not in @p R.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002684static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002685 // Start with the smallest loop containing the entry and expand that
2686 // loop until it contains all blocks in the region. If there is a loop
2687 // containing all blocks in the region check if it is itself contained
2688 // and if so take the parent loop as it will be the smallest containing
2689 // the region but not contained by it.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002690 Loop *L = LI.getLoopFor(R.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002691 while (L) {
2692 bool AllContained = true;
2693 for (auto *BB : R.blocks())
2694 AllContained &= L->contains(BB);
2695 if (AllContained)
2696 break;
2697 L = L->getParentLoop();
2698 }
2699
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002700 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2701}
2702
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002703static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2704 ScopDetection &SD) {
2705
2706 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2707
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002708 unsigned MinLD = INT_MAX, MaxLD = 0;
2709 for (BasicBlock *BB : R.blocks()) {
2710 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002711 if (!R.contains(L))
2712 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002713 if (BoxedLoops && BoxedLoops->count(L))
2714 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002715 unsigned LD = L->getLoopDepth();
2716 MinLD = std::min(MinLD, LD);
2717 MaxLD = std::max(MaxLD, LD);
2718 }
2719 }
2720
2721 // Handle the case that there is no loop in the SCoP first.
2722 if (MaxLD == 0)
2723 return 1;
2724
2725 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2726 assert(MaxLD >= MinLD &&
2727 "Maximal loop depth was smaller than mininaml loop depth?");
2728 return MaxLD - MinLD + 1;
2729}
2730
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002731Scop::Scop(Region &R, AccFuncMapType &AccFuncMap,
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002732 ScalarEvolution &ScalarEvolution, LoopInfo &LI, isl_ctx *Context,
2733 unsigned MaxLoopDepth)
2734 : LI(LI), SE(&ScalarEvolution), R(R), AccFuncMap(AccFuncMap),
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002735 IsOptimized(false), HasSingleExitEdge(R.getExitingBlock()),
2736 HasErrorBlock(false), MaxLoopDepth(MaxLoopDepth), IslCtx(Context),
2737 Context(nullptr), Affinator(this), AssumedContext(nullptr),
2738 BoundaryContext(nullptr), Schedule(nullptr) {
Tobias Grosserd840fc72016-02-04 13:18:42 +00002739 buildContext();
2740}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002741
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002742void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, ScopDetection &SD,
2743 DominatorTree &DT) {
2744 addUserAssumptions(AC, DT);
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002745 buildInvariantEquivalenceClasses(SD);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002746
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002747 buildDomains(&R, SD, DT);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002748
Michael Krusecac948e2015-10-02 13:53:07 +00002749 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002750 // Exit early in case there are no executable statements left in this scop.
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002751 simplifySCoP(true, DT);
Michael Kruseafe06702015-10-02 16:33:27 +00002752 if (Stmts.empty())
2753 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002754
Michael Krusecac948e2015-10-02 13:53:07 +00002755 // The ScopStmts now have enough information to initialize themselves.
2756 for (ScopStmt &Stmt : Stmts)
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002757 Stmt.init(SD);
Michael Krusecac948e2015-10-02 13:53:07 +00002758
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002759 buildSchedule(SD);
Tobias Grosser75805372011-04-29 06:27:02 +00002760
Tobias Grosser8286b832015-11-02 11:29:32 +00002761 if (isl_set_is_empty(AssumedContext))
2762 return;
2763
2764 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002765 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002766 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002767 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002768 buildBoundaryContext();
2769 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002770 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002771
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002772 hoistInvariantLoads(SD);
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002773 simplifySCoP(false, DT);
Tobias Grosser75805372011-04-29 06:27:02 +00002774}
2775
2776Scop::~Scop() {
2777 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002778 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002779 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002780 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002781
Johannes Doerfert96425c22015-08-30 21:13:53 +00002782 for (auto It : DomainMap)
2783 isl_set_free(It.second);
2784
Johannes Doerfertb164c792014-09-18 11:17:17 +00002785 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002786 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002787 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002788 isl_pw_multi_aff_free(MMA.first);
2789 isl_pw_multi_aff_free(MMA.second);
2790 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002791 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002792 isl_pw_multi_aff_free(MMA.first);
2793 isl_pw_multi_aff_free(MMA.second);
2794 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002795 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002796
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002797 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002798 isl_set_free(std::get<2>(IAClass));
Tobias Grosser75805372011-04-29 06:27:02 +00002799}
2800
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002801void Scop::updateAccessDimensionality() {
2802 for (auto &Stmt : *this)
2803 for (auto &Access : Stmt)
2804 Access->updateDimensionality();
2805}
2806
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002807void Scop::simplifySCoP(bool RemoveIgnoredStmts, DominatorTree &DT) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002808 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2809 ScopStmt &Stmt = *StmtIt;
Michael Krusecac948e2015-10-02 13:53:07 +00002810 RegionNode *RN = Stmt.isRegionStmt()
2811 ? Stmt.getRegion()->getNode()
2812 : getRegion().getBBNode(Stmt.getBasicBlock());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002813
Johannes Doerferteca9e892015-11-03 16:54:49 +00002814 bool RemoveStmt = StmtIt->isEmpty();
2815 if (!RemoveStmt)
2816 RemoveStmt = isl_set_is_empty(DomainMap[getRegionNodeBasicBlock(RN)]);
2817 if (!RemoveStmt)
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002818 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN, DT));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002819
Johannes Doerferteca9e892015-11-03 16:54:49 +00002820 // Remove read only statements only after invariant loop hoisting.
2821 if (!RemoveStmt && !RemoveIgnoredStmts) {
2822 bool OnlyRead = true;
2823 for (MemoryAccess *MA : Stmt) {
2824 if (MA->isRead())
2825 continue;
2826
2827 OnlyRead = false;
2828 break;
2829 }
2830
2831 RemoveStmt = OnlyRead;
2832 }
2833
2834 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00002835 // Remove the statement because it is unnecessary.
2836 if (Stmt.isRegionStmt())
2837 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2838 StmtMap.erase(BB);
2839 else
2840 StmtMap.erase(Stmt.getBasicBlock());
2841
2842 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002843 continue;
2844 }
2845
Michael Krusecac948e2015-10-02 13:53:07 +00002846 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002847 }
2848}
2849
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002850const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2851 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2852 if (!LInst)
2853 return nullptr;
2854
2855 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2856 LInst = cast<LoadInst>(Rep);
2857
Johannes Doerfert96e54712016-02-07 17:30:13 +00002858 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002859 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2860 for (auto &IAClass : InvariantEquivClasses)
Johannes Doerfert96e54712016-02-07 17:30:13 +00002861 if (PointerSCEV == std::get<0>(IAClass) && Ty == std::get<3>(IAClass))
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002862 return &IAClass;
2863
2864 return nullptr;
2865}
2866
2867void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2868
2869 // Get the context under which the statement is executed.
2870 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2871 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2872 DomainCtx = isl_set_detect_equalities(DomainCtx);
2873 DomainCtx = isl_set_coalesce(DomainCtx);
2874
2875 // Project out all parameters that relate to loads in the statement. Otherwise
2876 // we could have cyclic dependences on the constraints under which the
2877 // hoisted loads are executed and we could not determine an order in which to
2878 // pre-load them. This happens because not only lower bounds are part of the
2879 // domain but also upper bounds.
2880 for (MemoryAccess *MA : InvMAs) {
2881 Instruction *AccInst = MA->getAccessInstruction();
2882 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00002883 SetVector<Value *> Values;
2884 for (const SCEV *Parameter : Parameters) {
2885 Values.clear();
2886 findValues(Parameter, Values);
2887 if (!Values.count(AccInst))
2888 continue;
2889
2890 if (isl_id *ParamId = getIdForParam(Parameter)) {
2891 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2892 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2893 isl_id_free(ParamId);
2894 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002895 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002896 }
2897 }
2898
2899 for (MemoryAccess *MA : InvMAs) {
2900 // Check for another invariant access that accesses the same location as
2901 // MA and if found consolidate them. Otherwise create a new equivalence
2902 // class at the end of InvariantEquivClasses.
2903 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00002904 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002905 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2906
2907 bool Consolidated = false;
2908 for (auto &IAClass : InvariantEquivClasses) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002909 if (PointerSCEV != std::get<0>(IAClass) || Ty != std::get<3>(IAClass))
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002910 continue;
2911
2912 Consolidated = true;
2913
2914 // Add MA to the list of accesses that are in this class.
2915 auto &MAs = std::get<1>(IAClass);
2916 MAs.push_front(MA);
2917
2918 // Unify the execution context of the class and this statement.
2919 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002920 if (IAClassDomainCtx)
2921 IAClassDomainCtx = isl_set_coalesce(
2922 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
2923 else
2924 IAClassDomainCtx = isl_set_copy(DomainCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002925 break;
2926 }
2927
2928 if (Consolidated)
2929 continue;
2930
2931 // If we did not consolidate MA, thus did not find an equivalence class
2932 // for it, we create a new one.
2933 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
Johannes Doerfert96e54712016-02-07 17:30:13 +00002934 isl_set_copy(DomainCtx), Ty);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002935 }
2936
2937 isl_set_free(DomainCtx);
2938}
2939
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002940bool Scop::isHoistableAccess(MemoryAccess *Access,
2941 __isl_keep isl_union_map *Writes) {
2942 // TODO: Loads that are not loop carried, hence are in a statement with
2943 // zero iterators, are by construction invariant, though we
2944 // currently "hoist" them anyway. This is necessary because we allow
2945 // them to be treated as parameters (e.g., in conditions) and our code
2946 // generation would otherwise use the old value.
2947
2948 auto &Stmt = *Access->getStatement();
2949 BasicBlock *BB =
2950 Stmt.isBlockStmt() ? Stmt.getBasicBlock() : Stmt.getRegion()->getEntry();
2951
2952 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
2953 return false;
2954
2955 // Skip accesses that have an invariant base pointer which is defined but
2956 // not loaded inside the SCoP. This can happened e.g., if a readnone call
2957 // returns a pointer that is used as a base address. However, as we want
2958 // to hoist indirect pointers, we allow the base pointer to be defined in
2959 // the region if it is also a memory access. Each ScopArrayInfo object
2960 // that has a base pointer origin has a base pointer that is loaded and
2961 // that it is invariant, thus it will be hoisted too. However, if there is
2962 // no base pointer origin we check that the base pointer is defined
2963 // outside the region.
2964 const ScopArrayInfo *SAI = Access->getScopArrayInfo();
2965 while (auto *BasePtrOriginSAI = SAI->getBasePtrOriginSAI())
2966 SAI = BasePtrOriginSAI;
2967
2968 if (auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr()))
2969 if (R.contains(BasePtrInst))
2970 return false;
2971
2972 // Skip accesses in non-affine subregions as they might not be executed
2973 // under the same condition as the entry of the non-affine subregion.
2974 if (BB != Access->getAccessInstruction()->getParent())
2975 return false;
2976
2977 isl_map *AccessRelation = Access->getAccessRelation();
2978
2979 // Skip accesses that have an empty access relation. These can be caused
2980 // by multiple offsets with a type cast in-between that cause the overall
2981 // byte offset to be not divisible by the new types sizes.
2982 if (isl_map_is_empty(AccessRelation)) {
2983 isl_map_free(AccessRelation);
2984 return false;
2985 }
2986
2987 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
2988 Stmt.getNumIterators())) {
2989 isl_map_free(AccessRelation);
2990 return false;
2991 }
2992
2993 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
2994 isl_set *AccessRange = isl_map_range(AccessRelation);
2995
2996 isl_union_map *Written = isl_union_map_intersect_range(
2997 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
2998 bool IsWritten = !isl_union_map_is_empty(Written);
2999 isl_union_map_free(Written);
3000
3001 if (IsWritten)
3002 return false;
3003
3004 return true;
3005}
3006
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003007void Scop::verifyInvariantLoads(ScopDetection &SD) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003008 auto &RIL = *SD.getRequiredInvariantLoads(&getRegion());
3009 for (LoadInst *LI : RIL) {
3010 assert(LI && getRegion().contains(LI));
3011 ScopStmt *Stmt = getStmtForBasicBlock(LI->getParent());
Tobias Grosser949e8c62015-12-21 07:10:39 +00003012 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003013 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3014 return;
3015 }
3016 }
3017}
3018
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003019void Scop::hoistInvariantLoads(ScopDetection &SD) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003020 isl_union_map *Writes = getWrites();
3021 for (ScopStmt &Stmt : *this) {
3022
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003023 MemoryAccessList InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003024
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003025 for (MemoryAccess *Access : Stmt)
3026 if (isHoistableAccess(Access, Writes))
3027 InvariantAccesses.push_front(Access);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003028
3029 // We inserted invariant accesses always in the front but need them to be
3030 // sorted in a "natural order". The statements are already sorted in reverse
3031 // post order and that suffices for the accesses too. The reason we require
3032 // an order in the first place is the dependences between invariant loads
3033 // that can be caused by indirect loads.
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003034 InvariantAccesses.reverse();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003035
3036 // Transfer the memory access from the statement to the SCoP.
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003037 Stmt.removeMemoryAccesses(InvariantAccesses);
3038 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003039 }
3040 isl_union_map_free(Writes);
3041
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003042 verifyInvariantLoads(SD);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003043}
3044
Johannes Doerfert80ef1102014-11-07 08:31:31 +00003045const ScopArrayInfo *
Tobias Grossercc779502016-02-02 13:22:54 +00003046Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003047 ArrayRef<const SCEV *> Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00003048 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003049 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003050 if (!SAI) {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003051 auto &DL = getRegion().getEntry()->getModule()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003052 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003053 DL, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003054 } else {
Tobias Grosser8286b832015-11-02 11:29:32 +00003055 // In case of mismatching array sizes, we bail out by setting the run-time
3056 // context to false.
Tobias Grosserd840fc72016-02-04 13:18:42 +00003057 if (!SAI->updateSizes(Sizes, ElementType))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003058 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003059 }
Tobias Grosserab671442015-05-23 05:58:27 +00003060 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003061}
3062
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003063const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00003064 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003065 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003066 assert(SAI && "No ScopArrayInfo available for this base pointer");
3067 return SAI;
3068}
3069
Tobias Grosser74394f02013-01-14 22:40:23 +00003070std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003071std::string Scop::getAssumedContextStr() const {
3072 return stringFromIslObj(AssumedContext);
3073}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003074std::string Scop::getBoundaryContextStr() const {
3075 return stringFromIslObj(BoundaryContext);
3076}
Tobias Grosser75805372011-04-29 06:27:02 +00003077
3078std::string Scop::getNameStr() const {
3079 std::string ExitName, EntryName;
3080 raw_string_ostream ExitStr(ExitName);
3081 raw_string_ostream EntryStr(EntryName);
3082
Tobias Grosserf240b482014-01-09 10:42:15 +00003083 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003084 EntryStr.str();
3085
3086 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003087 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003088 ExitStr.str();
3089 } else
3090 ExitName = "FunctionExit";
3091
3092 return EntryName + "---" + ExitName;
3093}
3094
Tobias Grosser74394f02013-01-14 22:40:23 +00003095__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003096__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003097 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003098}
3099
Tobias Grossere86109f2013-10-29 21:05:49 +00003100__isl_give isl_set *Scop::getAssumedContext() const {
3101 return isl_set_copy(AssumedContext);
3102}
3103
Johannes Doerfert43788c52015-08-20 05:58:56 +00003104__isl_give isl_set *Scop::getRuntimeCheckContext() const {
3105 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003106 RuntimeCheckContext =
3107 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
3108 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00003109 return RuntimeCheckContext;
3110}
3111
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003112bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003113 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003114 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00003115 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
3116 isl_set_free(RuntimeCheckContext);
3117 return IsFeasible;
3118}
3119
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003120static std::string toString(AssumptionKind Kind) {
3121 switch (Kind) {
3122 case ALIASING:
3123 return "No-aliasing";
3124 case INBOUNDS:
3125 return "Inbounds";
3126 case WRAPPING:
3127 return "No-overflows";
Johannes Doerferta4b77c02015-11-12 20:15:32 +00003128 case ALIGNMENT:
3129 return "Alignment";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003130 case ERRORBLOCK:
3131 return "No-error";
3132 case INFINITELOOP:
3133 return "Finite loop";
3134 case INVARIANTLOAD:
3135 return "Invariant load";
3136 case DELINEARIZATION:
3137 return "Delinearization";
Tobias Grosser75dc40c2015-12-20 13:31:48 +00003138 case ERROR_DOMAINCONJUNCTS:
3139 return "Low number of domain conjuncts";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003140 }
3141 llvm_unreachable("Unknown AssumptionKind!");
3142}
3143
3144void Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3145 DebugLoc Loc) {
3146 if (isl_set_is_subset(Context, Set))
3147 return;
3148
3149 if (isl_set_is_subset(AssumedContext, Set))
3150 return;
3151
3152 auto &F = *getRegion().getEntry()->getParent();
3153 std::string Msg = toString(Kind) + " assumption:\t" + stringFromIslObj(Set);
3154 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
3155}
3156
3157void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
3158 DebugLoc Loc) {
3159 trackAssumption(Kind, Set, Loc);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003160 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003161
Johannes Doerfert9d7899e2015-11-11 20:01:31 +00003162 int NSets = isl_set_n_basic_set(AssumedContext);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003163 if (NSets >= MaxDisjunctsAssumed) {
3164 isl_space *Space = isl_set_get_space(AssumedContext);
3165 isl_set_free(AssumedContext);
Tobias Grossere19fca42015-11-11 20:21:39 +00003166 AssumedContext = isl_set_empty(Space);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003167 }
3168
Tobias Grosser7b50bee2014-11-25 10:51:12 +00003169 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003170}
3171
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003172void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
3173 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc);
3174}
3175
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003176__isl_give isl_set *Scop::getBoundaryContext() const {
3177 return isl_set_copy(BoundaryContext);
3178}
3179
Tobias Grosser75805372011-04-29 06:27:02 +00003180void Scop::printContext(raw_ostream &OS) const {
3181 OS << "Context:\n";
3182
3183 if (!Context) {
3184 OS.indent(4) << "n/a\n\n";
3185 return;
3186 }
3187
3188 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003189
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003190 OS.indent(4) << "Assumed Context:\n";
3191 if (!AssumedContext) {
3192 OS.indent(4) << "n/a\n\n";
3193 return;
3194 }
3195
3196 OS.indent(4) << getAssumedContextStr() << "\n";
3197
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003198 OS.indent(4) << "Boundary Context:\n";
3199 if (!BoundaryContext) {
3200 OS.indent(4) << "n/a\n\n";
3201 return;
3202 }
3203
3204 OS.indent(4) << getBoundaryContextStr() << "\n";
3205
Tobias Grosser083d3d32014-06-28 08:59:45 +00003206 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00003207 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00003208 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
3209 }
Tobias Grosser75805372011-04-29 06:27:02 +00003210}
3211
Johannes Doerfertb164c792014-09-18 11:17:17 +00003212void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003213 int noOfGroups = 0;
3214 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003215 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003216 noOfGroups += 1;
3217 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003218 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003219 }
3220
Tobias Grosserbb853c22015-07-25 12:31:03 +00003221 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003222 if (MinMaxAliasGroups.empty()) {
3223 OS.indent(8) << "n/a\n";
3224 return;
3225 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003226
Tobias Grosserbb853c22015-07-25 12:31:03 +00003227 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003228
3229 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003230 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003231 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003232 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003233 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3234 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003235 }
3236 OS << " ]]\n";
3237 }
3238
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003239 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003240 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003241 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003242 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003243 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3244 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003245 }
3246 OS << " ]]\n";
3247 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003248 }
3249}
3250
Tobias Grosser75805372011-04-29 06:27:02 +00003251void Scop::printStatements(raw_ostream &OS) const {
3252 OS << "Statements {\n";
3253
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003254 for (const ScopStmt &Stmt : *this)
3255 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003256
3257 OS.indent(4) << "}\n";
3258}
3259
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003260void Scop::printArrayInfo(raw_ostream &OS) const {
3261 OS << "Arrays {\n";
3262
Tobias Grosserab671442015-05-23 05:58:27 +00003263 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003264 Array.second->print(OS);
3265
3266 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003267
3268 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3269
3270 for (auto &Array : arrays())
3271 Array.second->print(OS, /* SizeAsPwAff */ true);
3272
3273 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003274}
3275
Tobias Grosser75805372011-04-29 06:27:02 +00003276void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00003277 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
3278 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003279 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003280 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003281 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003282 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003283 const auto &MAs = std::get<1>(IAClass);
3284 if (MAs.empty()) {
3285 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003286 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003287 MAs.front()->print(OS);
3288 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003289 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003290 }
3291 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003292 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003293 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003294 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003295 printStatements(OS.indent(4));
3296}
3297
3298void Scop::dump() const { print(dbgs()); }
3299
Tobias Grosser9a38ab82011-11-08 15:41:03 +00003300isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00003301
Johannes Doerfertcef616f2015-09-15 22:49:04 +00003302__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
3303 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003304}
3305
Tobias Grosser808cd692015-07-14 09:33:13 +00003306__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003307 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003308
Tobias Grosser808cd692015-07-14 09:33:13 +00003309 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003310 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003311
3312 return Domain;
3313}
3314
Tobias Grossere5a35142015-11-12 14:07:09 +00003315__isl_give isl_union_map *
3316Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3317 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003318
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003319 for (ScopStmt &Stmt : *this) {
3320 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003321 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003322 continue;
3323
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003324 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003325 isl_map *AccessDomain = MA->getAccessRelation();
3326 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003327 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003328 }
3329 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003330 return isl_union_map_coalesce(Accesses);
3331}
3332
3333__isl_give isl_union_map *Scop::getMustWrites() {
3334 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003335}
3336
3337__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003338 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003339}
3340
Tobias Grosser37eb4222014-02-20 21:43:54 +00003341__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003342 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003343}
3344
3345__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003346 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003347}
3348
Tobias Grosser2ac23382015-11-12 14:07:13 +00003349__isl_give isl_union_map *Scop::getAccesses() {
3350 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3351}
3352
Tobias Grosser808cd692015-07-14 09:33:13 +00003353__isl_give isl_union_map *Scop::getSchedule() const {
3354 auto Tree = getScheduleTree();
3355 auto S = isl_schedule_get_map(Tree);
3356 isl_schedule_free(Tree);
3357 return S;
3358}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003359
Tobias Grosser808cd692015-07-14 09:33:13 +00003360__isl_give isl_schedule *Scop::getScheduleTree() const {
3361 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3362 getDomains());
3363}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003364
Tobias Grosser808cd692015-07-14 09:33:13 +00003365void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3366 auto *S = isl_schedule_from_domain(getDomains());
3367 S = isl_schedule_insert_partial_schedule(
3368 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3369 isl_schedule_free(Schedule);
3370 Schedule = S;
3371}
3372
3373void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3374 isl_schedule_free(Schedule);
3375 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003376}
3377
3378bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3379 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003380 for (ScopStmt &Stmt : *this) {
3381 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003382 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3383 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3384
3385 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3386 isl_union_set_free(StmtDomain);
3387 isl_union_set_free(NewStmtDomain);
3388 continue;
3389 }
3390
3391 Changed = true;
3392
3393 isl_union_set_free(StmtDomain);
3394 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3395
3396 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003397 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003398 isl_union_set_free(NewStmtDomain);
3399 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003400 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003401 }
3402 isl_union_set_free(Domain);
3403 return Changed;
3404}
3405
Tobias Grosser75805372011-04-29 06:27:02 +00003406ScalarEvolution *Scop::getSE() const { return SE; }
3407
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00003408bool Scop::isIgnored(RegionNode *RN, DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003409 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Michael Krusea902ba62015-12-13 19:21:45 +00003410 ScopStmt *Stmt = getStmtForRegionNode(RN);
3411
3412 // If there is no stmt, then it already has been removed.
3413 if (!Stmt)
3414 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00003415
Johannes Doerfertf5673802015-10-01 23:48:18 +00003416 // Check if there are accesses contained.
Michael Krusea902ba62015-12-13 19:21:45 +00003417 if (Stmt->isEmpty())
Johannes Doerfertf5673802015-10-01 23:48:18 +00003418 return true;
3419
3420 // Check for reachability via non-error blocks.
3421 if (!DomainMap.count(BB))
3422 return true;
3423
3424 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003425 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003426 return true;
3427
3428 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003429}
3430
Tobias Grosser808cd692015-07-14 09:33:13 +00003431struct MapToDimensionDataTy {
3432 int N;
3433 isl_union_pw_multi_aff *Res;
3434};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003435
Tobias Grosser808cd692015-07-14 09:33:13 +00003436// @brief Create a function that maps the elements of 'Set' to its N-th
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003437// dimension and add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00003438//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003439// @param Set The input set.
3440// @param User->N The dimension to map to.
3441// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00003442//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003443// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00003444static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3445 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3446 int Dim;
3447 isl_space *Space;
3448 isl_pw_multi_aff *PMA;
3449
3450 Dim = isl_set_dim(Set, isl_dim_set);
3451 Space = isl_set_get_space(Set);
3452 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3453 Dim - Data->N);
3454 if (Data->N > 1)
3455 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3456 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3457
3458 isl_set_free(Set);
3459
3460 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003461}
3462
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003463// @brief Create an isl_multi_union_aff that defines an identity mapping
3464// from the elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003465//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003466// # Example:
3467//
3468// Domain: { A[i,j]; B[i,j,k] }
3469// N: 1
3470//
3471// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
3472//
3473// @param USet A union set describing the elements for which to generate a
3474// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00003475// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003476// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003477static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003478mapToDimension(__isl_take isl_union_set *USet, int N) {
3479 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00003480 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003481 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003482
Tobias Grosser808cd692015-07-14 09:33:13 +00003483 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00003484
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003485 auto *Space = isl_union_set_get_space(USet);
3486 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00003487
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003488 Data = {N, PwAff};
3489
3490 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
3491
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00003492 (void)Res;
3493
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003494 assert(Res == isl_stat_ok);
3495
3496 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00003497 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3498}
3499
Tobias Grosser316b5b22015-11-11 19:28:14 +00003500void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003501 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003502 Stmts.emplace_back(*this, *BB);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003503 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003504 StmtMap[BB] = Stmt;
3505 } else {
3506 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003507 Stmts.emplace_back(*this, *R);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003508 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003509 for (BasicBlock *BB : R->blocks())
3510 StmtMap[BB] = Stmt;
3511 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003512}
3513
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003514void Scop::buildSchedule(ScopDetection &SD) {
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003515 Loop *L = getLoopSurroundingRegion(getRegion(), LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003516 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003517 buildSchedule(getRegion().getNode(), LoopStack, SD);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003518 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
3519 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003520}
3521
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003522/// To generate a schedule for the elements in a Region we traverse the Region
3523/// in reverse-post-order and add the contained RegionNodes in traversal order
3524/// to the schedule of the loop that is currently at the top of the LoopStack.
3525/// For loop-free codes, this results in a correct sequential ordering.
3526///
3527/// Example:
3528/// bb1(0)
3529/// / \.
3530/// bb2(1) bb3(2)
3531/// \ / \.
3532/// bb4(3) bb5(4)
3533/// \ /
3534/// bb6(5)
3535///
3536/// Including loops requires additional processing. Whenever a loop header is
3537/// encountered, the corresponding loop is added to the @p LoopStack. Starting
3538/// from an empty schedule, we first process all RegionNodes that are within
3539/// this loop and complete the sequential schedule at this loop-level before
3540/// processing about any other nodes. To implement this
3541/// loop-nodes-first-processing, the reverse post-order traversal is
3542/// insufficient. Hence, we additionally check if the traversal yields
3543/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
3544/// These region-nodes are then queue and only traverse after the all nodes
3545/// within the current loop have been processed.
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003546void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, ScopDetection &SD) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003547 Loop *OuterScopLoop = getLoopSurroundingRegion(getRegion(), LI);
3548
3549 ReversePostOrderTraversal<Region *> RTraversal(R);
3550 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
3551 std::deque<RegionNode *> DelayList;
3552 bool LastRNWaiting = false;
3553
3554 // Iterate over the region @p R in reverse post-order but queue
3555 // sub-regions/blocks iff they are not part of the last encountered but not
3556 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
3557 // that we queued the last sub-region/block from the reverse post-order
3558 // iterator. If it is set we have to explore the next sub-region/block from
3559 // the iterator (if any) to guarantee progress. If it is not set we first try
3560 // the next queued sub-region/blocks.
3561 while (!WorkList.empty() || !DelayList.empty()) {
3562 RegionNode *RN;
3563
3564 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
3565 RN = WorkList.front();
3566 WorkList.pop_front();
3567 LastRNWaiting = false;
3568 } else {
3569 RN = DelayList.front();
3570 DelayList.pop_front();
3571 }
3572
3573 Loop *L = getRegionNodeLoop(RN, LI);
3574 if (!getRegion().contains(L))
3575 L = OuterScopLoop;
3576
3577 Loop *LastLoop = LoopStack.back().L;
3578 if (LastLoop != L) {
3579 if (!LastLoop->contains(L)) {
3580 LastRNWaiting = true;
3581 DelayList.push_back(RN);
3582 continue;
3583 }
3584 LoopStack.push_back({L, nullptr, 0});
3585 }
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003586 buildSchedule(RN, LoopStack, SD);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003587 }
3588
3589 return;
3590}
3591
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003592void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack,
3593 ScopDetection &SD) {
Michael Kruse046dde42015-08-10 13:01:57 +00003594
Tobias Grosser8362c262016-01-06 15:30:06 +00003595 if (RN->isSubRegion()) {
3596 auto *LocalRegion = RN->getNodeAs<Region>();
3597 if (!SD.isNonAffineSubRegion(LocalRegion, &getRegion())) {
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003598 buildSchedule(LocalRegion, LoopStack, SD);
Tobias Grosser8362c262016-01-06 15:30:06 +00003599 return;
3600 }
3601 }
Michael Kruse046dde42015-08-10 13:01:57 +00003602
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003603 auto &LoopData = LoopStack.back();
3604 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00003605
Tobias Grosserc9abde82016-01-23 20:23:06 +00003606 if (auto *Stmt = getStmtForRegionNode(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00003607 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3608 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003609 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00003610 }
3611
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003612 // Check if we just processed the last node in this loop. If we did, finalize
3613 // the loop by:
3614 //
3615 // - adding new schedule dimensions
3616 // - folding the resulting schedule into the parent loop schedule
3617 // - dropping the loop schedule from the LoopStack.
3618 //
3619 // Then continue to check surrounding loops, which might also have been
3620 // completed by this node.
3621 while (LoopData.L &&
3622 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
3623 auto Schedule = LoopData.Schedule;
3624 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00003625
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003626 LoopStack.pop_back();
3627 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00003628
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003629 if (Schedule) {
3630 auto *Domain = isl_schedule_get_domain(Schedule);
3631 auto *MUPA = mapToDimension(Domain, LoopStack.size());
3632 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
3633 NextLoopData.Schedule =
3634 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003635 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003636
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003637 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
3638 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00003639 }
Tobias Grosser75805372011-04-29 06:27:02 +00003640}
3641
Johannes Doerfert7c494212014-10-31 23:13:39 +00003642ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003643 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003644 if (StmtMapIt == StmtMap.end())
3645 return nullptr;
3646 return StmtMapIt->second;
3647}
3648
Michael Krusea902ba62015-12-13 19:21:45 +00003649ScopStmt *Scop::getStmtForRegionNode(RegionNode *RN) const {
3650 return getStmtForBasicBlock(getRegionNodeBasicBlock(RN));
3651}
3652
Johannes Doerfert96425c22015-08-30 21:13:53 +00003653int Scop::getRelativeLoopDepth(const Loop *L) const {
3654 Loop *OuterLoop =
3655 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3656 if (!OuterLoop)
3657 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003658 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3659}
3660
Michael Krused868b5d2015-09-10 15:25:24 +00003661void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003662 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003663
3664 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3665 // true, are not modeled as ordinary PHI nodes as they are not part of the
3666 // region. However, we model the operands in the predecessor blocks that are
3667 // part of the region as regular scalar accesses.
3668
3669 // If we can synthesize a PHI we can skip it, however only if it is in
3670 // the region. If it is not it can only be in the exit block of the region.
3671 // In this case we model the operands but not the PHI itself.
3672 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3673 return;
3674
3675 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3676 // detection. Hence, the PHI is a load of a new memory location in which the
3677 // incoming value was written at the end of the incoming basic block.
3678 bool OnlyNonAffineSubRegionOperands = true;
3679 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3680 Value *Op = PHI->getIncomingValue(u);
3681 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3682
3683 // Do not build scalar dependences inside a non-affine subregion.
3684 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3685 continue;
3686
3687 OnlyNonAffineSubRegionOperands = false;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00003688 ensurePHIWrite(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003689 }
3690
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003691 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3692 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003693 }
3694}
3695
Michael Kruse2e02d562016-02-06 09:19:40 +00003696void ScopInfo::buildScalarDependences(Instruction *Inst) {
3697 assert(!isa<PHINode>(Inst));
Michael Kruse7bf39442015-09-10 12:46:52 +00003698
Michael Kruse2e02d562016-02-06 09:19:40 +00003699 // Pull-in required operands.
3700 for (Use &Op : Inst->operands())
3701 ensureValueRead(Op.get(), Inst->getParent());
3702}
Michael Kruse7bf39442015-09-10 12:46:52 +00003703
Michael Kruse2e02d562016-02-06 09:19:40 +00003704void ScopInfo::buildEscapingDependences(Instruction *Inst) {
3705 Region *R = &scop->getRegion();
Michael Kruse7bf39442015-09-10 12:46:52 +00003706
Michael Kruse2e02d562016-02-06 09:19:40 +00003707 // Check for uses of this instruction outside the scop. Because we do not
3708 // iterate over such instructions and therefore did not "ensure" the existence
3709 // of a write, we must determine such use here.
3710 for (Use &U : Inst->uses()) {
3711 Instruction *UI = dyn_cast<Instruction>(U.getUser());
3712 if (!UI)
Michael Kruse7bf39442015-09-10 12:46:52 +00003713 continue;
3714
Michael Kruse2e02d562016-02-06 09:19:40 +00003715 BasicBlock *UseParent = getUseBlock(U);
3716 BasicBlock *UserParent = UI->getParent();
Michael Kruse7bf39442015-09-10 12:46:52 +00003717
Michael Kruse2e02d562016-02-06 09:19:40 +00003718 // An escaping value is either used by an instruction not within the scop,
3719 // or (when the scop region's exit needs to be simplified) by a PHI in the
3720 // scop's exit block. This is because region simplification before code
3721 // generation inserts new basic blocks before the PHI such that its incoming
3722 // blocks are not in the scop anymore.
3723 if (!R->contains(UseParent) ||
3724 (isa<PHINode>(UI) && UserParent == R->getExit() &&
3725 R->getExitingBlock())) {
3726 // At least one escaping use found.
3727 ensureValueWrite(Inst);
3728 break;
Michael Kruse7bf39442015-09-10 12:46:52 +00003729 }
3730 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003731}
3732
3733extern MapInsnToMemAcc InsnToMemAcc;
3734
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003735bool ScopInfo::buildAccessMultiDimFixed(
Michael Kruse70131d32016-01-27 17:09:17 +00003736 MemAccInst Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003737 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3738 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse70131d32016-01-27 17:09:17 +00003739 Value *Val = Inst.getValueOperand();
3740 Type *SizeType = Val->getType();
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003741 unsigned ElementSize = DL->getTypeAllocSize(SizeType);
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003742 Value *Address = Inst.getPointerOperand();
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003743 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003744 const SCEVUnknown *BasePointer =
3745 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003746 enum MemoryAccess::AccessType Type =
3747 Inst.isLoad() ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003748
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003749 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3750 auto NewAddress = Address;
3751 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3752 auto Src = BitCast->getOperand(0);
3753 auto SrcTy = Src->getType();
3754 auto DstTy = BitCast->getType();
3755 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3756 NewAddress = Src;
3757 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003758
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003759 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3760 std::vector<const SCEV *> Subscripts;
3761 std::vector<int> Sizes;
3762 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3763 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003764
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003765 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003766
Johannes Doerfert09e36972015-10-07 20:17:36 +00003767 for (auto Subscript : Subscripts) {
3768 InvariantLoadsSetTy AccessILS;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003769 if (!isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS))
3770 return false;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003771
3772 for (LoadInst *LInst : AccessILS)
3773 if (!ScopRIL.count(LInst))
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003774 return false;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003775 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003776
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003777 if (Sizes.size() > 0) {
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003778 for (auto V : Sizes)
3779 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3780 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003781
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003782 addArrayAccess(Inst, Type, BasePointer->getValue(), ElementSize, true,
Tobias Grossera535dff2015-12-13 19:59:01 +00003783 Subscripts, SizesSCEV, Val);
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003784 return true;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003785 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003786 }
3787 }
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003788 return false;
3789}
3790
3791bool ScopInfo::buildAccessMultiDimParam(
3792 MemAccInst Inst, Loop *L, Region *R,
3793 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3794 const InvariantLoadsSetTy &ScopRIL) {
3795 Value *Address = Inst.getPointerOperand();
3796 Value *Val = Inst.getValueOperand();
3797 Type *SizeType = Val->getType();
3798 unsigned ElementSize = DL->getTypeAllocSize(SizeType);
3799 enum MemoryAccess::AccessType Type =
3800 Inst.isLoad() ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
3801
3802 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
3803 const SCEVUnknown *BasePointer =
3804 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3805
3806 assert(BasePointer && "Could not find base pointer");
3807 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003808
Michael Kruse7bf39442015-09-10 12:46:52 +00003809 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003810 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003811 std::vector<const SCEV *> Sizes(
3812 AccItr->second.Shape->DelinearizedSizes.begin(),
3813 AccItr->second.Shape->DelinearizedSizes.end());
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003814 // Remove the element size. This information is already provided by the
Tobias Grosserd840fc72016-02-04 13:18:42 +00003815 // ElementSize parameter. In case the element size of this access and the
3816 // element size used for delinearization differs the delinearization is
3817 // incorrect. Hence, we invalidate the scop.
3818 //
3819 // TODO: Handle delinearization with differing element sizes.
3820 auto DelinearizedSize =
3821 cast<SCEVConstant>(Sizes.back())->getAPInt().getSExtValue();
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003822 Sizes.pop_back();
Tobias Grosserd840fc72016-02-04 13:18:42 +00003823 if (ElementSize != DelinearizedSize)
3824 scop->invalidate(DELINEARIZATION, Inst.getDebugLoc());
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003825
3826 addArrayAccess(Inst, Type, BasePointer->getValue(), ElementSize, true,
3827 AccItr->second.DelinearizedSubscripts, Sizes, Val);
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003828 return true;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003829 }
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003830 return false;
3831}
3832
3833void ScopInfo::buildAccessSingleDim(
3834 MemAccInst Inst, Loop *L, Region *R,
3835 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3836 const InvariantLoadsSetTy &ScopRIL) {
3837 Value *Address = Inst.getPointerOperand();
3838 Value *Val = Inst.getValueOperand();
3839 Type *SizeType = Val->getType();
3840 unsigned ElementSize = DL->getTypeAllocSize(SizeType);
3841 enum MemoryAccess::AccessType Type =
3842 Inst.isLoad() ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
3843
3844 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
3845 const SCEVUnknown *BasePointer =
3846 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3847
3848 assert(BasePointer && "Could not find base pointer");
3849 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
Michael Kruse7bf39442015-09-10 12:46:52 +00003850
3851 // Check if the access depends on a loop contained in a non-affine subregion.
3852 bool isVariantInNonAffineLoop = false;
3853 if (BoxedLoops) {
3854 SetVector<const Loop *> Loops;
3855 findLoops(AccessFunction, Loops);
3856 for (const Loop *L : Loops)
3857 if (BoxedLoops->count(L))
3858 isVariantInNonAffineLoop = true;
3859 }
3860
Johannes Doerfert09e36972015-10-07 20:17:36 +00003861 InvariantLoadsSetTy AccessILS;
3862 bool IsAffine =
3863 !isVariantInNonAffineLoop &&
3864 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3865
3866 for (LoadInst *LInst : AccessILS)
3867 if (!ScopRIL.count(LInst))
3868 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003869
Michael Krusee2bccbb2015-09-18 19:59:43 +00003870 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3871 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003872
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003873 addArrayAccess(Inst, Type, BasePointer->getValue(), ElementSize, IsAffine,
3874 {AccessFunction}, {}, Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003875}
3876
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003877void ScopInfo::buildMemoryAccess(
3878 MemAccInst Inst, Loop *L, Region *R,
3879 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3880 const InvariantLoadsSetTy &ScopRIL) {
3881
3882 if (buildAccessMultiDimFixed(Inst, L, R, BoxedLoops, ScopRIL))
3883 return;
3884
3885 if (buildAccessMultiDimParam(Inst, L, R, BoxedLoops, ScopRIL))
3886 return;
3887
3888 buildAccessSingleDim(Inst, L, R, BoxedLoops, ScopRIL);
3889}
3890
Michael Krused868b5d2015-09-10 15:25:24 +00003891void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003892
3893 if (SD->isNonAffineSubRegion(&SR, &R)) {
3894 for (BasicBlock *BB : SR.blocks())
3895 buildAccessFunctions(R, *BB, &SR);
3896 return;
3897 }
3898
3899 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3900 if (I->isSubRegion())
3901 buildAccessFunctions(R, *I->getNodeAs<Region>());
3902 else
3903 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
3904}
3905
Johannes Doerferta8781032016-02-02 14:14:40 +00003906void ScopInfo::buildStmts(Region &R, Region &SR) {
Michael Krusecac948e2015-10-02 13:53:07 +00003907
Johannes Doerferta8781032016-02-02 14:14:40 +00003908 if (SD->isNonAffineSubRegion(&SR, &R)) {
Michael Krusecac948e2015-10-02 13:53:07 +00003909 scop->addScopStmt(nullptr, &SR);
3910 return;
3911 }
3912
3913 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3914 if (I->isSubRegion())
Johannes Doerferta8781032016-02-02 14:14:40 +00003915 buildStmts(R, *I->getNodeAs<Region>());
Michael Krusecac948e2015-10-02 13:53:07 +00003916 else
3917 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
3918}
3919
Michael Krused868b5d2015-09-10 15:25:24 +00003920void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
3921 Region *NonAffineSubRegion,
3922 bool IsExitBlock) {
Tobias Grosser910cf262015-11-11 20:15:49 +00003923 // We do not build access functions for error blocks, as they may contain
3924 // instructions we can not model.
Johannes Doerfertc36d39b2016-02-02 14:14:20 +00003925 if (isErrorBlock(BB, R, *LI, *DT) && !IsExitBlock)
Tobias Grosser910cf262015-11-11 20:15:49 +00003926 return;
3927
Michael Kruse7bf39442015-09-10 12:46:52 +00003928 Loop *L = LI->getLoopFor(&BB);
3929
3930 // The set of loops contained in non-affine subregions that are part of R.
3931 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3932
Johannes Doerfert09e36972015-10-07 20:17:36 +00003933 // The set of loads that are required to be invariant.
3934 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
3935
Michael Kruse2e02d562016-02-06 09:19:40 +00003936 for (Instruction &Inst : BB) {
3937 PHINode *PHI = dyn_cast<PHINode>(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003938 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003939 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003940
3941 // For the exit block we stop modeling after the last PHI node.
3942 if (!PHI && IsExitBlock)
3943 break;
3944
Johannes Doerfert09e36972015-10-07 20:17:36 +00003945 // TODO: At this point we only know that elements of ScopRIL have to be
3946 // invariant and will be hoisted for the SCoP to be processed. Though,
3947 // there might be other invariant accesses that will be hoisted and
3948 // that would allow to make a non-affine access affine.
Michael Kruse70131d32016-01-27 17:09:17 +00003949 if (auto MemInst = MemAccInst::dyn_cast(Inst))
3950 buildMemoryAccess(MemInst, L, &R, BoxedLoops, ScopRIL);
Michael Kruse7bf39442015-09-10 12:46:52 +00003951
Michael Kruse2e02d562016-02-06 09:19:40 +00003952 if (isIgnoredIntrinsic(&Inst))
Michael Kruse7bf39442015-09-10 12:46:52 +00003953 continue;
3954
Michael Kruse2e02d562016-02-06 09:19:40 +00003955 if (!PHI)
3956 buildScalarDependences(&Inst);
3957 if (!IsExitBlock)
3958 buildEscapingDependences(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003959 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003960}
Michael Kruse7bf39442015-09-10 12:46:52 +00003961
Michael Kruseee6a4fc2016-01-26 13:33:27 +00003962MemoryAccess *ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3963 MemoryAccess::AccessType Type,
3964 Value *BaseAddress, unsigned ElemBytes,
3965 bool Affine, Value *AccessValue,
3966 ArrayRef<const SCEV *> Subscripts,
3967 ArrayRef<const SCEV *> Sizes,
3968 ScopArrayInfo::MemoryKind Kind) {
Michael Krusecac948e2015-10-02 13:53:07 +00003969 ScopStmt *Stmt = scop->getStmtForBasicBlock(BB);
3970
3971 // Do not create a memory access for anything not in the SCoP. It would be
3972 // ignored anyway.
3973 if (!Stmt)
Michael Kruseee6a4fc2016-01-26 13:33:27 +00003974 return nullptr;
Michael Krusecac948e2015-10-02 13:53:07 +00003975
Michael Krusee2bccbb2015-09-18 19:59:43 +00003976 AccFuncSetType &AccList = AccFuncMap[BB];
Michael Krusee2bccbb2015-09-18 19:59:43 +00003977 Value *BaseAddr = BaseAddress;
3978 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3979
Tobias Grosserf4f68702015-12-14 15:05:37 +00003980 bool isKnownMustAccess = false;
3981
3982 // Accesses in single-basic block statements are always excuted.
3983 if (Stmt->isBlockStmt())
3984 isKnownMustAccess = true;
3985
3986 if (Stmt->isRegionStmt()) {
3987 // Accesses that dominate the exit block of a non-affine region are always
3988 // executed. In non-affine regions there may exist MK_Values that do not
3989 // dominate the exit. MK_Values will always dominate the exit and MK_PHIs
3990 // only if there is at most one PHI_WRITE in the non-affine region.
3991 if (DT->dominates(BB, Stmt->getRegion()->getExit()))
3992 isKnownMustAccess = true;
3993 }
3994
Michael Kruseee6a4fc2016-01-26 13:33:27 +00003995 // Non-affine PHI writes do not "happen" at a particular instruction, but
3996 // after exiting the statement. Therefore they are guaranteed execute and
3997 // overwrite the old value.
3998 if (Kind == ScopArrayInfo::MK_PHI || Kind == ScopArrayInfo::MK_ExitPHI)
3999 isKnownMustAccess = true;
4000
Tobias Grosserf4f68702015-12-14 15:05:37 +00004001 if (!isKnownMustAccess && Type == MemoryAccess::MUST_WRITE)
Michael Krusecac948e2015-10-02 13:53:07 +00004002 Type = MemoryAccess::MAY_WRITE;
4003
Tobias Grosserf1bfd752015-11-05 20:15:37 +00004004 AccList.emplace_back(Stmt, Inst, Type, BaseAddress, ElemBytes, Affine,
Tobias Grossera535dff2015-12-13 19:59:01 +00004005 Subscripts, Sizes, AccessValue, Kind, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00004006 Stmt->addAccess(&AccList.back());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004007 return &AccList.back();
Michael Kruse7bf39442015-09-10 12:46:52 +00004008}
4009
Michael Kruse70131d32016-01-27 17:09:17 +00004010void ScopInfo::addArrayAccess(MemAccInst MemAccInst,
Tobias Grossera535dff2015-12-13 19:59:01 +00004011 MemoryAccess::AccessType Type, Value *BaseAddress,
4012 unsigned ElemBytes, bool IsAffine,
4013 ArrayRef<const SCEV *> Subscripts,
4014 ArrayRef<const SCEV *> Sizes,
4015 Value *AccessValue) {
Michael Kruse70131d32016-01-27 17:09:17 +00004016 assert(MemAccInst.isLoad() == (Type == MemoryAccess::READ));
4017 addMemoryAccess(MemAccInst.getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00004018 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00004019 ScopArrayInfo::MK_Array);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004020}
Michael Kruse436db622016-01-26 13:33:10 +00004021void ScopInfo::ensureValueWrite(Instruction *Value) {
4022 ScopStmt *Stmt = scop->getStmtForBasicBlock(Value->getParent());
4023
4024 // Value not defined within this SCoP.
4025 if (!Stmt)
4026 return;
4027
4028 // Do not process further if the value is already written.
4029 if (Stmt->lookupValueWriteOf(Value))
4030 return;
4031
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004032 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
4033 true, Value, ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004034 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004035}
Michael Krusead28e5a2016-01-26 13:33:15 +00004036void ScopInfo::ensureValueRead(Value *Value, BasicBlock *UserBB) {
Michael Krusefd463082016-01-27 22:51:56 +00004037
Michael Kruse2e02d562016-02-06 09:19:40 +00004038 // There cannot be an "access" for literal constants. BasicBlock references
4039 // (jump destinations) also never change.
4040 if ((isa<Constant>(Value) && !isa<GlobalVariable>(Value)) ||
4041 isa<BasicBlock>(Value))
4042 return;
4043
Michael Krusefd463082016-01-27 22:51:56 +00004044 // If the instruction can be synthesized and the user is in the region we do
4045 // not need to add a value dependences.
4046 Region &ScopRegion = scop->getRegion();
4047 if (canSynthesize(Value, LI, SE, &ScopRegion))
4048 return;
4049
Michael Kruse2e02d562016-02-06 09:19:40 +00004050 // Do not build scalar dependences for required invariant loads as we will
4051 // hoist them later on anyway or drop the SCoP if we cannot.
4052 auto ScopRIL = SD->getRequiredInvariantLoads(&ScopRegion);
4053 if (ScopRIL->count(dyn_cast<LoadInst>(Value)))
4054 return;
4055
4056 // Determine the ScopStmt containing the value's definition and use. There is
4057 // no defining ScopStmt if the value is a function argument, a global value,
4058 // or defined outside the SCoP.
4059 Instruction *ValueInst = dyn_cast<Instruction>(Value);
4060 ScopStmt *ValueStmt =
4061 ValueInst ? scop->getStmtForBasicBlock(ValueInst->getParent()) : nullptr;
4062
Michael Krusead28e5a2016-01-26 13:33:15 +00004063 ScopStmt *UserStmt = scop->getStmtForBasicBlock(UserBB);
4064
4065 // We do not model uses outside the scop.
4066 if (!UserStmt)
4067 return;
4068
Michael Kruse2e02d562016-02-06 09:19:40 +00004069 // Add MemoryAccess for invariant values only if requested.
4070 if (!ModelReadOnlyScalars && !ValueStmt)
4071 return;
4072
4073 // Ignore use-def chains within the same ScopStmt.
4074 if (ValueStmt == UserStmt)
4075 return;
4076
Michael Krusead28e5a2016-01-26 13:33:15 +00004077 // Do not create another MemoryAccess for reloading the value if one already
4078 // exists.
4079 if (UserStmt->lookupValueReadOf(Value))
4080 return;
4081
4082 addMemoryAccess(UserBB, nullptr, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00004083 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004084 ScopArrayInfo::MK_Value);
Michael Kruse2e02d562016-02-06 09:19:40 +00004085 if (ValueInst)
4086 ensureValueWrite(ValueInst);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004087}
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004088void ScopInfo::ensurePHIWrite(PHINode *PHI, BasicBlock *IncomingBlock,
4089 Value *IncomingValue, bool IsExitBlock) {
4090 ScopStmt *IncomingStmt = scop->getStmtForBasicBlock(IncomingBlock);
Michael Kruse2e02d562016-02-06 09:19:40 +00004091 if (!IncomingStmt)
4092 return;
4093
4094 // Take care for the incoming value being available in the incoming block.
4095 // This must be done before the check for multiple PHI writes because multiple
4096 // exiting edges from subregion each can be the effective written value of the
4097 // subregion. As such, all of them must be made available in the subregion
4098 // statement.
4099 ensureValueRead(IncomingValue, IncomingBlock);
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004100
4101 // Do not add more than one MemoryAccess per PHINode and ScopStmt.
4102 if (MemoryAccess *Acc = IncomingStmt->lookupPHIWriteOf(PHI)) {
4103 assert(Acc->getAccessInstruction() == PHI);
4104 Acc->addIncoming(IncomingBlock, IncomingValue);
4105 return;
4106 }
4107
4108 MemoryAccess *Acc = addMemoryAccess(
4109 IncomingStmt->isBlockStmt() ? IncomingBlock
4110 : IncomingStmt->getRegion()->getEntry(),
4111 PHI, MemoryAccess::MUST_WRITE, PHI, 1, true, PHI,
4112 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
4113 IsExitBlock ? ScopArrayInfo::MK_ExitPHI : ScopArrayInfo::MK_PHI);
4114 assert(Acc);
4115 Acc->addIncoming(IncomingBlock, IncomingValue);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004116}
4117void ScopInfo::addPHIReadAccess(PHINode *PHI) {
4118 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00004119 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004120 ScopArrayInfo::MK_PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004121}
4122
Michael Krusedaf66942015-12-13 22:10:37 +00004123void ScopInfo::buildScop(Region &R, AssumptionCache &AC) {
Michael Kruse9d080092015-09-11 21:41:48 +00004124 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00004125 scop = new Scop(R, AccFuncMap, *SE, *LI, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00004126
Johannes Doerferta8781032016-02-02 14:14:40 +00004127 buildStmts(R, R);
Michael Kruse7bf39442015-09-10 12:46:52 +00004128 buildAccessFunctions(R, R);
4129
4130 // In case the region does not have an exiting block we will later (during
4131 // code generation) split the exit block. This will move potential PHI nodes
4132 // from the current exit block into the new region exiting block. Hence, PHI
4133 // nodes that are at this point not part of the region will be.
4134 // To handle these PHI nodes later we will now model their operands as scalar
4135 // accesses. Note that we do not model anything in the exit block if we have
4136 // an exiting block in the region, as there will not be any splitting later.
4137 if (!R.getExitingBlock())
4138 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
4139
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00004140 scop->init(*AA, AC, *SD, *DT);
Michael Kruse7bf39442015-09-10 12:46:52 +00004141}
4142
Michael Krused868b5d2015-09-10 15:25:24 +00004143void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00004144 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00004145 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00004146 return;
4147 }
4148
Michael Kruse9d080092015-09-11 21:41:48 +00004149 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00004150}
4151
Michael Krused868b5d2015-09-10 15:25:24 +00004152void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00004153 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00004154 if (scop) {
4155 delete scop;
4156 scop = 0;
4157 }
Michael Kruse7bf39442015-09-10 12:46:52 +00004158}
4159
4160//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00004161ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00004162 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00004163 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00004164}
4165
4166ScopInfo::~ScopInfo() {
4167 clear();
4168 isl_ctx_free(ctx);
4169}
4170
Tobias Grosser75805372011-04-29 06:27:02 +00004171void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00004172 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00004173 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00004174 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00004175 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4176 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004177 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004178 AU.addRequired<AssumptionCacheTracker>();
Tobias Grosser75805372011-04-29 06:27:02 +00004179 AU.setPreservesAll();
4180}
4181
4182bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00004183 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00004184
Michael Krused868b5d2015-09-10 15:25:24 +00004185 if (!SD->isMaxRegionInScop(*R))
4186 return false;
4187
4188 Function *F = R->getEntry()->getParent();
4189 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4190 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4191 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Johannes Doerferta1f291e2016-02-02 14:15:13 +00004192 DL = &F->getParent()->getDataLayout();
Michael Krusedaf66942015-12-13 22:10:37 +00004193 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004194 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krused868b5d2015-09-10 15:25:24 +00004195
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004196 DebugLoc Beg, End;
4197 getDebugLocations(R, Beg, End);
4198 std::string Msg = "SCoP begins here.";
4199 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg);
4200
Michael Krusedaf66942015-12-13 22:10:37 +00004201 buildScop(*R, AC);
Tobias Grosser75805372011-04-29 06:27:02 +00004202
Tobias Grosserd6a50b32015-05-30 06:26:21 +00004203 DEBUG(scop->print(dbgs()));
4204
Michael Kruseafe06702015-10-02 16:33:27 +00004205 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004206 Msg = "SCoP ends here but was dismissed.";
Johannes Doerfert43788c52015-08-20 05:58:56 +00004207 delete scop;
4208 scop = nullptr;
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004209 } else {
4210 Msg = "SCoP ends here.";
4211 ++ScopFound;
4212 if (scop->getMaxLoopDepth() > 0)
4213 ++RichScopFound;
Johannes Doerfert43788c52015-08-20 05:58:56 +00004214 }
4215
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004216 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg);
4217
Tobias Grosser75805372011-04-29 06:27:02 +00004218 return false;
4219}
4220
4221char ScopInfo::ID = 0;
4222
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004223Pass *polly::createScopInfoPass() { return new ScopInfo(); }
4224
Tobias Grosser73600b82011-10-08 00:30:40 +00004225INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
4226 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004227 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004228INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004229INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004230INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004231INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004232INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004233INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004234INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00004235INITIALIZE_PASS_END(ScopInfo, "polly-scops",
4236 "Polly - Create polyhedral description of Scops", false,
4237 false)