blob: 496aadfe72d3892b9848bce38c000ca095a349fe [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 Grosser75805372011-04-29 06:27:02 +000020#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000021#include "polly/Options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000022#include "polly/ScopInfo.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 Grosserf4c24b22015-04-05 13:11:54 +000026#include "llvm/ADT/MapVector.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000027#include "llvm/ADT/PostOrderIterator.h"
28#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000029#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000030#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000031#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000032#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000033#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000034#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000035#include "llvm/Analysis/RegionIterator.h"
36#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser75805372011-04-29 06:27:02 +000037#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000038#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000039#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000040#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000041#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000042#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000043#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000044#include "isl/schedule.h"
45#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000046#include "isl/set.h"
47#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000048#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000049#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000050#include <sstream>
51#include <string>
52#include <vector>
53
54using namespace llvm;
55using namespace polly;
56
Chandler Carruth95fef942014-04-22 03:30:19 +000057#define DEBUG_TYPE "polly-scops"
58
Tobias Grosser74394f02013-01-14 22:40:23 +000059STATISTIC(ScopFound, "Number of valid Scops");
60STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000061
Michael Kruse7bf39442015-09-10 12:46:52 +000062static cl::opt<bool> ModelReadOnlyScalars(
63 "polly-analyze-read-only-scalars",
64 cl::desc("Model read-only scalar values in the scop description"),
65 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
66
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000067// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000068// operations can overflow easily. Additive reductions and bit operations
69// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000070static cl::opt<bool> DisableMultiplicativeReductions(
71 "polly-disable-multiplicative-reductions",
72 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
73 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000074
Johannes Doerfert9143d672014-09-27 11:02:39 +000075static cl::opt<unsigned> RunTimeChecksMaxParameters(
76 "polly-rtc-max-parameters",
77 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
78 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
79
Tobias Grosser71500722015-03-28 15:11:14 +000080static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
81 "polly-rtc-max-arrays-per-group",
82 cl::desc("The maximal number of arrays to compare in each alias group."),
83 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000084static cl::opt<std::string> UserContextStr(
85 "polly-context", cl::value_desc("isl parameter set"),
86 cl::desc("Provide additional constraints on the context parameters"),
87 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000088
Tobias Grosserd83b8a82015-08-20 19:08:11 +000089static cl::opt<bool> DetectReductions("polly-detect-reductions",
90 cl::desc("Detect and exploit reductions"),
91 cl::Hidden, cl::ZeroOrMore,
92 cl::init(true), cl::cat(PollyCategory));
93
Michael Kruse7bf39442015-09-10 12:46:52 +000094//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +000095
Michael Kruse046dde42015-08-10 13:01:57 +000096// Create a sequence of two schedules. Either argument may be null and is
97// interpreted as the empty schedule. Can also return null if both schedules are
98// empty.
99static __isl_give isl_schedule *
100combineInSequence(__isl_take isl_schedule *Prev,
101 __isl_take isl_schedule *Succ) {
102 if (!Prev)
103 return Succ;
104 if (!Succ)
105 return Prev;
106
107 return isl_schedule_sequence(Prev, Succ);
108}
109
Johannes Doerferte7044942015-02-24 11:58:30 +0000110static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
111 const ConstantRange &Range,
112 int dim,
113 enum isl_dim_type type) {
114 isl_val *V;
115 isl_ctx *ctx = isl_set_get_ctx(S);
116
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000117 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
118 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000119 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000120 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
121
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000122 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000123 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000124 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000125 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000126 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
127
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000128 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000129 return isl_set_union(SLB, SUB);
130 else
131 return isl_set_intersect(SLB, SUB);
132}
133
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000134static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
135 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
136 if (!BasePtrLI)
137 return nullptr;
138
139 if (!S->getRegion().contains(BasePtrLI))
140 return nullptr;
141
142 ScalarEvolution &SE = *S->getSE();
143
144 auto *OriginBaseSCEV =
145 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
146 if (!OriginBaseSCEV)
147 return nullptr;
148
149 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
150 if (!OriginBaseSCEVUnknown)
151 return nullptr;
152
153 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue());
154}
155
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000156ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000157 ArrayRef<const SCEV *> Sizes, bool IsPHI, Scop *S)
158 : BasePtr(BasePtr), ElementType(ElementType), IsPHI(IsPHI), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000159 std::string BasePtrName =
160 getIslCompatibleName("MemRef_", BasePtr, IsPHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000161 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000162
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000163 updateSizes(Sizes);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000164 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
165 if (BasePtrOriginSAI)
166 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000167}
168
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000169__isl_give isl_space *ScopArrayInfo::getSpace() const {
170 auto Space =
171 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
172 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
173 return Space;
174}
175
Tobias Grosser8286b832015-11-02 11:29:32 +0000176bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000177 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
178 int ExtraDimsNew = NewSizes.size() - SharedDims;
179 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Tobias Grosser8286b832015-11-02 11:29:32 +0000180 for (int i = 0; i < SharedDims; i++)
181 if (NewSizes[i + ExtraDimsNew] != DimensionSizes[i + ExtraDimsOld])
182 return false;
183
184 if (DimensionSizes.size() >= NewSizes.size())
185 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000186
187 DimensionSizes.clear();
188 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
189 NewSizes.end());
190 for (isl_pw_aff *Size : DimensionSizesPw)
191 isl_pw_aff_free(Size);
192 DimensionSizesPw.clear();
193 for (const SCEV *Expr : DimensionSizes) {
194 isl_pw_aff *Size = S.getPwAff(Expr);
195 DimensionSizesPw.push_back(Size);
196 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000197 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000198}
199
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000200ScopArrayInfo::~ScopArrayInfo() {
201 isl_id_free(Id);
202 for (isl_pw_aff *Size : DimensionSizesPw)
203 isl_pw_aff_free(Size);
204}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000205
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000206std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
207
208int ScopArrayInfo::getElemSizeInBytes() const {
209 return ElementType->getPrimitiveSizeInBits() / 8;
210}
211
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000212isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
213
214void ScopArrayInfo::dump() const { print(errs()); }
215
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000216void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000217 OS.indent(8) << *getElementType() << " " << getName() << "[*]";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000218 for (unsigned u = 0; u < getNumberOfDimensions(); u++) {
219 OS << "[";
220
221 if (SizeAsPwAff)
222 OS << " " << DimensionSizesPw[u] << " ";
223 else
224 OS << *DimensionSizes[u];
225
226 OS << "]";
227 }
228
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000229 if (BasePtrOriginSAI)
230 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
231
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000232 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000233}
234
235const ScopArrayInfo *
236ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
237 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
238 assert(Id && "Output dimension didn't have an ID");
239 return getFromId(Id);
240}
241
242const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
243 void *User = isl_id_get_user(Id);
244 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
245 isl_id_free(Id);
246 return SAI;
247}
248
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000249void MemoryAccess::updateDimensionality() {
250 auto ArraySpace = getScopArrayInfo()->getSpace();
251 auto AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
252
253 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
254 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
255 auto DimsMissing = DimsArray - DimsAccess;
256
257 auto Map = isl_map_from_domain_and_range(isl_set_universe(AccessSpace),
258 isl_set_universe(ArraySpace));
259
260 for (unsigned i = 0; i < DimsMissing; i++)
261 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
262
263 for (unsigned i = DimsMissing; i < DimsArray; i++)
264 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
265
266 AccessRelation = isl_map_apply_range(AccessRelation, Map);
267}
268
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000269const std::string
270MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
271 switch (RT) {
272 case MemoryAccess::RT_NONE:
273 llvm_unreachable("Requested a reduction operator string for a memory "
274 "access which isn't a reduction");
275 case MemoryAccess::RT_ADD:
276 return "+";
277 case MemoryAccess::RT_MUL:
278 return "*";
279 case MemoryAccess::RT_BOR:
280 return "|";
281 case MemoryAccess::RT_BXOR:
282 return "^";
283 case MemoryAccess::RT_BAND:
284 return "&";
285 }
286 llvm_unreachable("Unknown reduction type");
287 return "";
288}
289
Johannes Doerfertf6183392014-07-01 20:52:51 +0000290/// @brief Return the reduction type for a given binary operator
291static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
292 const Instruction *Load) {
293 if (!BinOp)
294 return MemoryAccess::RT_NONE;
295 switch (BinOp->getOpcode()) {
296 case Instruction::FAdd:
297 if (!BinOp->hasUnsafeAlgebra())
298 return MemoryAccess::RT_NONE;
299 // Fall through
300 case Instruction::Add:
301 return MemoryAccess::RT_ADD;
302 case Instruction::Or:
303 return MemoryAccess::RT_BOR;
304 case Instruction::Xor:
305 return MemoryAccess::RT_BXOR;
306 case Instruction::And:
307 return MemoryAccess::RT_BAND;
308 case Instruction::FMul:
309 if (!BinOp->hasUnsafeAlgebra())
310 return MemoryAccess::RT_NONE;
311 // Fall through
312 case Instruction::Mul:
313 if (DisableMultiplicativeReductions)
314 return MemoryAccess::RT_NONE;
315 return MemoryAccess::RT_MUL;
316 default:
317 return MemoryAccess::RT_NONE;
318 }
319}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000320
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000321/// @brief Derive the individual index expressions from a GEP instruction
322///
323/// This function optimistically assumes the GEP references into a fixed size
324/// array. If this is actually true, this function returns a list of array
325/// subscript expressions as SCEV as well as a list of integers describing
326/// the size of the individual array dimensions. Both lists have either equal
327/// length of the size list is one element shorter in case there is no known
328/// size available for the outermost array dimension.
329///
330/// @param GEP The GetElementPtr instruction to analyze.
331///
332/// @return A tuple with the subscript expressions and the dimension sizes.
333static std::tuple<std::vector<const SCEV *>, std::vector<int>>
334getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
335 std::vector<const SCEV *> Subscripts;
336 std::vector<int> Sizes;
337
338 Type *Ty = GEP->getPointerOperandType();
339
340 bool DroppedFirstDim = false;
341
Michael Kruse26ed65e2015-09-24 17:32:49 +0000342 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000343
344 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
345
346 if (i == 1) {
347 if (auto PtrTy = dyn_cast<PointerType>(Ty)) {
348 Ty = PtrTy->getElementType();
349 } else if (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
350 Ty = ArrayTy->getElementType();
351 } else {
352 Subscripts.clear();
353 Sizes.clear();
354 break;
355 }
356 if (auto Const = dyn_cast<SCEVConstant>(Expr))
357 if (Const->getValue()->isZero()) {
358 DroppedFirstDim = true;
359 continue;
360 }
361 Subscripts.push_back(Expr);
362 continue;
363 }
364
365 auto ArrayTy = dyn_cast<ArrayType>(Ty);
366 if (!ArrayTy) {
367 Subscripts.clear();
368 Sizes.clear();
369 break;
370 }
371
372 Subscripts.push_back(Expr);
373 if (!(DroppedFirstDim && i == 2))
374 Sizes.push_back(ArrayTy->getNumElements());
375
376 Ty = ArrayTy->getElementType();
377 }
378
379 return std::make_tuple(Subscripts, Sizes);
380}
381
Tobias Grosser75805372011-04-29 06:27:02 +0000382MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000383 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000384 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000385 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000386}
387
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000388const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
389 isl_id *ArrayId = getArrayId();
390 void *User = isl_id_get_user(ArrayId);
391 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
392 isl_id_free(ArrayId);
393 return SAI;
394}
395
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000396__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000397 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
398}
399
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000400__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
401 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000402 isl_map *Schedule, *ScheduledAccRel;
403 isl_union_set *UDomain;
404
405 UDomain = isl_union_set_from_set(getStatement()->getDomain());
406 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
407 Schedule = isl_map_from_union_map(USchedule);
408 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
409 return isl_pw_multi_aff_from_map(ScheduledAccRel);
410}
411
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000412__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000413 return isl_map_copy(AccessRelation);
414}
415
Johannes Doerferta99130f2014-10-13 12:58:03 +0000416std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000417 return stringFromIslObj(AccessRelation);
418}
419
Johannes Doerferta99130f2014-10-13 12:58:03 +0000420__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000421 return isl_map_get_space(AccessRelation);
422}
423
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000424__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000425 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000426}
427
Tobias Grosser6f730082015-09-05 07:46:47 +0000428std::string MemoryAccess::getNewAccessRelationStr() const {
429 return stringFromIslObj(NewAccessRelation);
430}
431
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000432__isl_give isl_basic_map *
433MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000434 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000435 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000436
Tobias Grosser084d8f72012-05-29 09:29:44 +0000437 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000438 isl_basic_set_universe(Statement->getDomainSpace()),
439 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000440}
441
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000442// Formalize no out-of-bound access assumption
443//
444// When delinearizing array accesses we optimistically assume that the
445// delinearized accesses do not access out of bound locations (the subscript
446// expression of each array evaluates for each statement instance that is
447// executed to a value that is larger than zero and strictly smaller than the
448// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000449// dimension for which we do not need to assume any upper bound. At this point
450// we formalize this assumption to ensure that at code generation time the
451// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000452//
453// To find the set of constraints necessary to avoid out of bound accesses, we
454// first build the set of data locations that are not within array bounds. We
455// then apply the reverse access relation to obtain the set of iterations that
456// may contain invalid accesses and reduce this set of iterations to the ones
457// that are actually executed by intersecting them with the domain of the
458// statement. If we now project out all loop dimensions, we obtain a set of
459// parameters that may cause statement instances to be executed that may
460// possibly yield out of bound memory accesses. The complement of these
461// constraints is the set of constraints that needs to be assumed to ensure such
462// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000463void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000464 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000465 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Michael Krusee2bccbb2015-09-18 19:59:43 +0000466 for (int i = 1, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000467 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
468 isl_pw_aff *Var =
469 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
470 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
471
472 isl_set *DimOutside;
473
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000474 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Michael Krusee2bccbb2015-09-18 19:59:43 +0000475 isl_pw_aff *SizeE = Statement->getPwAff(Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000476
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000477 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
478 Statement->getNumIterators());
479 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
480 isl_space_dim(Space, isl_dim_set));
481 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
482 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000483
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000484 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000485
486 Outside = isl_set_union(Outside, DimOutside);
487 }
488
489 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
490 Outside = isl_set_intersect(Outside, Statement->getDomain());
491 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000492
493 // Remove divs to avoid the construction of overly complicated assumptions.
494 // Doing so increases the set of parameter combinations that are assumed to
495 // not appear. This is always save, but may make the resulting run-time check
496 // bail out more often than strictly necessary.
497 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000498 Outside = isl_set_complement(Outside);
499 Statement->getParent()->addAssumption(Outside);
500 isl_space_free(Space);
501}
502
Johannes Doerferte7044942015-02-24 11:58:30 +0000503void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
504 ScalarEvolution *SE = Statement->getParent()->getSE();
505
506 Value *Ptr = getPointerOperand(*getAccessInstruction());
507 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
508 return;
509
510 auto *PtrSCEV = SE->getSCEV(Ptr);
511 if (isa<SCEVCouldNotCompute>(PtrSCEV))
512 return;
513
514 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
515 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
516 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
517
518 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
519 if (Range.isFullSet())
520 return;
521
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000522 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000523 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000524 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
525 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
526
527 auto Min = LB.sdiv(APInt(BW, ElementSize));
528 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000529
530 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
531 AccessRange =
532 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
533 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
534}
535
Michael Krusee2bccbb2015-09-18 19:59:43 +0000536__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000537 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000538 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000539
540 for (int i = Size - 2; i >= 0; --i) {
541 isl_space *Space;
542 isl_map *MapOne, *MapTwo;
Michael Krusee2bccbb2015-09-18 19:59:43 +0000543 isl_pw_aff *DimSize = Statement->getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000544
545 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
546 isl_pw_aff_free(DimSize);
547 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
548
549 Space = isl_map_get_space(AccessRelation);
550 Space = isl_space_map_from_set(isl_space_range(Space));
551 Space = isl_space_align_params(Space, SpaceSize);
552
553 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
554 isl_id_free(ParamId);
555
556 MapOne = isl_map_universe(isl_space_copy(Space));
557 for (int j = 0; j < Size; ++j)
558 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
559 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
560
561 MapTwo = isl_map_universe(isl_space_copy(Space));
562 for (int j = 0; j < Size; ++j)
563 if (j < i || j > i + 1)
564 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
565
566 isl_local_space *LS = isl_local_space_from_space(Space);
567 isl_constraint *C;
568 C = isl_equality_alloc(isl_local_space_copy(LS));
569 C = isl_constraint_set_constant_si(C, -1);
570 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
571 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
572 MapTwo = isl_map_add_constraint(MapTwo, C);
573 C = isl_equality_alloc(LS);
574 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
575 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
576 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
577 MapTwo = isl_map_add_constraint(MapTwo, C);
578 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
579
580 MapOne = isl_map_union(MapOne, MapTwo);
581 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
582 }
583 return AccessRelation;
584}
585
Michael Krusee2bccbb2015-09-18 19:59:43 +0000586void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
587 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000588
Michael Krusee2bccbb2015-09-18 19:59:43 +0000589 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000590 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000591
Michael Krusee2bccbb2015-09-18 19:59:43 +0000592 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000593 // We overapproximate non-affine accesses with a possible access to the
594 // whole array. For read accesses it does not make a difference, if an
595 // access must or may happen. However, for write accesses it is important to
596 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000597 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000598 AccessRelation =
599 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000600
Michael Krusee2bccbb2015-09-18 19:59:43 +0000601 computeBoundsOnAccessRelation(getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000602 return;
603 }
604
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000605 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000606 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000607
Michael Krusee2bccbb2015-09-18 19:59:43 +0000608 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
609 isl_pw_aff *Affine = Statement->getPwAff(Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000610
Sebastian Pop422e33f2014-06-03 18:16:31 +0000611 if (Size == 1) {
612 // For the non delinearized arrays, divide the access function of the last
613 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000614 //
615 // A stride one array access in C expressed as A[i] is expressed in
616 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
617 // two subsequent values of 'i' index two values that are stored next to
618 // each other in memory. By this division we make this characteristic
619 // obvious again.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000620 isl_val *v = isl_val_int_from_si(Ctx, getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000621 Affine = isl_pw_aff_scale_down_val(Affine, v);
622 }
623
624 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
625
Tobias Grosser79baa212014-04-10 08:38:02 +0000626 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000627 }
628
Michael Krusee2bccbb2015-09-18 19:59:43 +0000629 if (Sizes.size() > 1 && !isa<SCEVConstant>(Sizes[0]))
630 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000631
Tobias Grosser79baa212014-04-10 08:38:02 +0000632 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000633 AccessRelation = isl_map_set_tuple_id(
634 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000635 AccessRelation =
636 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
637
Michael Krusee2bccbb2015-09-18 19:59:43 +0000638 assumeNoOutOfBound();
Tobias Grosseraa660a92015-03-30 00:07:50 +0000639 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000640 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000641}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000642
Michael Krusecac948e2015-10-02 13:53:07 +0000643MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
644 __isl_take isl_id *Id, AccessType Type,
645 Value *BaseAddress, unsigned ElemBytes, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000646 ArrayRef<const SCEV *> Subscripts,
647 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Michael Kruse8d0b7342015-09-25 21:21:00 +0000648 AccessOrigin Origin, StringRef BaseName)
Michael Krusecac948e2015-10-02 13:53:07 +0000649 : Id(Id), Origin(Origin), AccType(Type), RedType(RT_NONE), Statement(Stmt),
650 BaseAddr(BaseAddress), BaseName(BaseName), ElemBytes(ElemBytes),
651 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
652 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000653 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
654 NewAccessRelation(nullptr) {}
655
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000656void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000657 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000658 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000659}
660
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000661const std::string MemoryAccess::getReductionOperatorStr() const {
662 return MemoryAccess::getReductionOperatorStr(getReductionType());
663}
664
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000665__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
666
Johannes Doerfertf6183392014-07-01 20:52:51 +0000667raw_ostream &polly::operator<<(raw_ostream &OS,
668 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000669 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000670 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000671 else
672 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000673 return OS;
674}
675
Tobias Grosser75805372011-04-29 06:27:02 +0000676void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000677 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000678 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000679 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000680 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000681 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000682 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000683 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000684 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000685 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000686 break;
687 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000688 OS << "[Reduction Type: " << getReductionType() << "] ";
Michael Kruse8d0b7342015-09-25 21:21:00 +0000689 OS << "[Scalar: " << isImplicit() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000690 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000691 if (hasNewAccessRelation())
692 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000693}
694
Tobias Grosser74394f02013-01-14 22:40:23 +0000695void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000696
697// Create a map in the size of the provided set domain, that maps from the
698// one element of the provided set domain to another element of the provided
699// set domain.
700// The mapping is limited to all points that are equal in all but the last
701// dimension and for which the last dimension of the input is strict smaller
702// than the last dimension of the output.
703//
704// getEqualAndLarger(set[i0, i1, ..., iX]):
705//
706// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
707// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
708//
Tobias Grosserf5338802011-10-06 00:03:35 +0000709static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000710 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000711 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000712 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000713
714 // Set all but the last dimension to be equal for the input and output
715 //
716 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
717 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000718 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000719 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000720
721 // Set the last dimension of the input to be strict smaller than the
722 // last dimension of the output.
723 //
724 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000725 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
726 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000727 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000728}
729
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000730__isl_give isl_set *
731MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000732 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000733 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000734 isl_space *Space = isl_space_range(isl_map_get_space(S));
735 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000736
Sebastian Popa00a0292012-12-18 07:46:06 +0000737 S = isl_map_reverse(S);
738 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000739
Sebastian Popa00a0292012-12-18 07:46:06 +0000740 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
741 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
742 NextScatt = isl_map_apply_domain(NextScatt, S);
743 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000744
Sebastian Popa00a0292012-12-18 07:46:06 +0000745 isl_set *Deltas = isl_map_deltas(NextScatt);
746 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000747}
748
Sebastian Popa00a0292012-12-18 07:46:06 +0000749bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000750 int StrideWidth) const {
751 isl_set *Stride, *StrideX;
752 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000753
Sebastian Popa00a0292012-12-18 07:46:06 +0000754 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000755 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000756 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
757 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
758 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
759 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000760 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000761
Tobias Grosser28dd4862012-01-24 16:42:16 +0000762 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000763 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000764
Tobias Grosser28dd4862012-01-24 16:42:16 +0000765 return IsStrideX;
766}
767
Sebastian Popa00a0292012-12-18 07:46:06 +0000768bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
769 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000770}
771
Sebastian Popa00a0292012-12-18 07:46:06 +0000772bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
773 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000774}
775
Tobias Grosser166c4222015-09-05 07:46:40 +0000776void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
777 isl_map_free(NewAccessRelation);
778 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000779}
Tobias Grosser75805372011-04-29 06:27:02 +0000780
781//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000782
Tobias Grosser808cd692015-07-14 09:33:13 +0000783isl_map *ScopStmt::getSchedule() const {
784 isl_set *Domain = getDomain();
785 if (isl_set_is_empty(Domain)) {
786 isl_set_free(Domain);
787 return isl_map_from_aff(
788 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
789 }
790 auto *Schedule = getParent()->getSchedule();
791 Schedule = isl_union_map_intersect_domain(
792 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
793 if (isl_union_map_is_empty(Schedule)) {
794 isl_set_free(Domain);
795 isl_union_map_free(Schedule);
796 return isl_map_from_aff(
797 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
798 }
799 auto *M = isl_map_from_union_map(Schedule);
800 M = isl_map_coalesce(M);
801 M = isl_map_gist_domain(M, Domain);
802 M = isl_map_coalesce(M);
803 return M;
804}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000805
Johannes Doerfert574182d2015-08-12 10:19:50 +0000806__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000807 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
808 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000809}
810
Tobias Grosser37eb4222014-02-20 21:43:54 +0000811void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
812 assert(isl_set_is_subset(NewDomain, Domain) &&
813 "New domain is not a subset of old domain!");
814 isl_set_free(Domain);
815 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000816}
817
Michael Krusecac948e2015-10-02 13:53:07 +0000818void ScopStmt::buildAccessRelations() {
819 for (MemoryAccess *Access : MemAccs) {
820 Type *ElementType = Access->getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000821
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000822 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Michael Krusecac948e2015-10-02 13:53:07 +0000823 Access->getBaseAddr(), ElementType, Access->Sizes, Access->isPHI());
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000824
Michael Krusecac948e2015-10-02 13:53:07 +0000825 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +0000826 }
827}
828
Michael Krusecac948e2015-10-02 13:53:07 +0000829void ScopStmt::addAccess(MemoryAccess *Access) {
830 Instruction *AccessInst = Access->getAccessInstruction();
831
832 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
833 if (!MAL)
834 MAL = new MemoryAccessList();
835 MAL->emplace_front(Access);
836 MemAccs.push_back(MAL->front());
837}
838
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000839void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000840 for (MemoryAccess *MA : *this)
841 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000842
843 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000844}
845
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000846/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
847static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
848 void *User) {
849 isl_set **BoundedParts = static_cast<isl_set **>(User);
850 if (isl_basic_set_is_bounded(BSet))
851 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
852 else
853 isl_basic_set_free(BSet);
854 return isl_stat_ok;
855}
856
857/// @brief Return the bounded parts of @p S.
858static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
859 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
860 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
861 isl_set_free(S);
862 return BoundedParts;
863}
864
865/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
866///
867/// @returns A separation of @p S into first an unbounded then a bounded subset,
868/// both with regards to the dimension @p Dim.
869static std::pair<__isl_give isl_set *, __isl_give isl_set *>
870partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
871
872 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000873 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000874
875 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000876 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000877
878 // Remove dimensions that are greater than Dim as they are not interesting.
879 assert(NumDimsS >= Dim + 1);
880 OnlyDimS =
881 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
882
883 // Create artificial parametric upper bounds for dimensions smaller than Dim
884 // as we are not interested in them.
885 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
886 for (unsigned u = 0; u < Dim; u++) {
887 isl_constraint *C = isl_inequality_alloc(
888 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
889 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
890 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
891 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
892 }
893
894 // Collect all bounded parts of OnlyDimS.
895 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
896
897 // Create the dimensions greater than Dim again.
898 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
899 NumDimsS - Dim - 1);
900
901 // Remove the artificial upper bound parameters again.
902 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
903
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000904 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000905 return std::make_pair(UnboundedParts, BoundedParts);
906}
907
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000908/// @brief Set the dimension Ids from @p From in @p To.
909static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
910 __isl_take isl_set *To) {
911 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
912 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
913 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
914 }
915 return To;
916}
917
918/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000919static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000920 __isl_take isl_pw_aff *L,
921 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +0000922 switch (Pred) {
923 case ICmpInst::ICMP_EQ:
924 return isl_pw_aff_eq_set(L, R);
925 case ICmpInst::ICMP_NE:
926 return isl_pw_aff_ne_set(L, R);
927 case ICmpInst::ICMP_SLT:
928 return isl_pw_aff_lt_set(L, R);
929 case ICmpInst::ICMP_SLE:
930 return isl_pw_aff_le_set(L, R);
931 case ICmpInst::ICMP_SGT:
932 return isl_pw_aff_gt_set(L, R);
933 case ICmpInst::ICMP_SGE:
934 return isl_pw_aff_ge_set(L, R);
935 case ICmpInst::ICMP_ULT:
936 return isl_pw_aff_lt_set(L, R);
937 case ICmpInst::ICMP_UGT:
938 return isl_pw_aff_gt_set(L, R);
939 case ICmpInst::ICMP_ULE:
940 return isl_pw_aff_le_set(L, R);
941 case ICmpInst::ICMP_UGE:
942 return isl_pw_aff_ge_set(L, R);
943 default:
944 llvm_unreachable("Non integer predicate not supported");
945 }
946}
947
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000948/// @brief Create the conditions under which @p L @p Pred @p R is true.
949///
950/// Helper function that will make sure the dimensions of the result have the
951/// same isl_id's as the @p Domain.
952static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
953 __isl_take isl_pw_aff *L,
954 __isl_take isl_pw_aff *R,
955 __isl_keep isl_set *Domain) {
956 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
957 return setDimensionIds(Domain, ConsequenceCondSet);
958}
959
960/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000961///
962/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000963/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
964/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000965static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000966buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +0000967 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
968
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000969 Value *Condition = getConditionFromTerminator(SI);
970 assert(Condition && "No condition for switch");
971
972 ScalarEvolution &SE = *S.getSE();
973 BasicBlock *BB = SI->getParent();
974 isl_pw_aff *LHS, *RHS;
975 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
976
977 unsigned NumSuccessors = SI->getNumSuccessors();
978 ConditionSets.resize(NumSuccessors);
979 for (auto &Case : SI->cases()) {
980 unsigned Idx = Case.getSuccessorIndex();
981 ConstantInt *CaseValue = Case.getCaseValue();
982
983 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
984 isl_set *CaseConditionSet =
985 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
986 ConditionSets[Idx] = isl_set_coalesce(
987 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
988 }
989
990 assert(ConditionSets[0] == nullptr && "Default condition set was set");
991 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
992 for (unsigned u = 2; u < NumSuccessors; u++)
993 ConditionSetUnion =
994 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
995 ConditionSets[0] = setDimensionIds(
996 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
997
998 S.markAsOptimized();
999 isl_pw_aff_free(LHS);
1000}
1001
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001002/// @brief Build the conditions sets for the branch condition @p Condition in
1003/// the @p Domain.
1004///
1005/// This will fill @p ConditionSets with the conditions under which control
1006/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1007/// have as many elements as @p TI has successors.
1008static void
1009buildConditionSets(Scop &S, Value *Condition, TerminatorInst *TI, Loop *L,
1010 __isl_keep isl_set *Domain,
1011 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1012
1013 isl_set *ConsequenceCondSet = nullptr;
1014 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1015 if (CCond->isZero())
1016 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1017 else
1018 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1019 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1020 auto Opcode = BinOp->getOpcode();
1021 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1022
1023 buildConditionSets(S, BinOp->getOperand(0), TI, L, Domain, ConditionSets);
1024 buildConditionSets(S, BinOp->getOperand(1), TI, L, Domain, ConditionSets);
1025
1026 isl_set_free(ConditionSets.pop_back_val());
1027 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1028 isl_set_free(ConditionSets.pop_back_val());
1029 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1030
1031 if (Opcode == Instruction::And)
1032 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1033 else
1034 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1035 } else {
1036 auto *ICond = dyn_cast<ICmpInst>(Condition);
1037 assert(ICond &&
1038 "Condition of exiting branch was neither constant nor ICmp!");
1039
1040 ScalarEvolution &SE = *S.getSE();
1041 BasicBlock *BB = TI->getParent();
1042 isl_pw_aff *LHS, *RHS;
1043 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1044 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
1045 ConsequenceCondSet =
1046 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1047 }
1048
1049 assert(ConsequenceCondSet);
1050 isl_set *AlternativeCondSet =
1051 isl_set_complement(isl_set_copy(ConsequenceCondSet));
1052
1053 ConditionSets.push_back(isl_set_coalesce(
1054 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
1055 ConditionSets.push_back(isl_set_coalesce(
1056 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
1057}
1058
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001059/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1060///
1061/// This will fill @p ConditionSets with the conditions under which control
1062/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1063/// have as many elements as @p TI has successors.
1064static void
1065buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1066 __isl_keep isl_set *Domain,
1067 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1068
1069 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1070 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1071
1072 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1073
1074 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001075 ConditionSets.push_back(isl_set_copy(Domain));
1076 return;
1077 }
1078
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001079 Value *Condition = getConditionFromTerminator(TI);
1080 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001081
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001082 return buildConditionSets(S, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001083}
1084
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001085void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +00001086 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +00001087
Tobias Grosser084d8f72012-05-29 09:29:44 +00001088 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1089
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001090 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001091 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001092}
1093
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001094void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001095 isl_ctx *Ctx = Parent.getIslCtx();
1096 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1097 Type *Ty = GEP->getPointerOperandType();
1098 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001099 ScopDetection &SD = Parent.getSD();
1100
1101 // The set of loads that are required to be invariant.
1102 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001103
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001104 std::vector<const SCEV *> Subscripts;
1105 std::vector<int> Sizes;
1106
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001107 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001108
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001109 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001110 Ty = PtrTy->getElementType();
1111 }
1112
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001113 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001114
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001115 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001116
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001117 for (size_t i = 0; i < Sizes.size(); i++) {
1118 auto Expr = Subscripts[i + IndexOffset];
1119 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001120
Johannes Doerfert09e36972015-10-07 20:17:36 +00001121 InvariantLoadsSetTy AccessILS;
1122 if (!isAffineExpr(&Parent.getRegion(), Expr, SE, nullptr, &AccessILS))
1123 continue;
1124
1125 bool NonAffine = false;
1126 for (LoadInst *LInst : AccessILS)
1127 if (!ScopRIL.count(LInst))
1128 NonAffine = true;
1129
1130 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001131 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001132
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001133 isl_pw_aff *AccessOffset = getPwAff(Expr);
1134 AccessOffset =
1135 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001136
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001137 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1138 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001139
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001140 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1141 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1142 OutOfBound = isl_set_params(OutOfBound);
1143 isl_set *InBound = isl_set_complement(OutOfBound);
1144 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001145
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001146 // A => B == !A or B
1147 isl_set *InBoundIfExecuted =
1148 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001149
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001150 Parent.addAssumption(InBoundIfExecuted);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001151 }
1152
1153 isl_local_space_free(LSpace);
1154}
1155
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001156void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1157 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001158 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1159 deriveAssumptionsFromGEP(GEP);
1160}
1161
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001162void ScopStmt::collectSurroundingLoops() {
1163 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1164 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1165 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1166 isl_id_free(DimId);
1167 }
1168}
1169
Michael Kruse9d080092015-09-11 21:41:48 +00001170ScopStmt::ScopStmt(Scop &parent, Region &R)
Michael Krusecac948e2015-10-02 13:53:07 +00001171 : Parent(parent), Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001172
Tobias Grosser16c44032015-07-09 07:31:45 +00001173 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001174}
1175
Michael Kruse9d080092015-09-11 21:41:48 +00001176ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Michael Krusecac948e2015-10-02 13:53:07 +00001177 : Parent(parent), Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001178
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001179 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001180}
1181
1182void ScopStmt::init() {
1183 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001184
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001185 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001186 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001187 buildAccessRelations();
1188
1189 if (BB) {
1190 deriveAssumptions(BB);
1191 } else {
1192 for (BasicBlock *Block : R->blocks()) {
1193 deriveAssumptions(Block);
1194 }
1195 }
1196
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001197 if (DetectReductions)
1198 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001199}
1200
Johannes Doerferte58a0122014-06-27 20:31:28 +00001201/// @brief Collect loads which might form a reduction chain with @p StoreMA
1202///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001203/// Check if the stored value for @p StoreMA is a binary operator with one or
1204/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001205/// used only once (by @p StoreMA) and its load operands are also used only
1206/// once, we have found a possible reduction chain. It starts at an operand
1207/// load and includes the binary operator and @p StoreMA.
1208///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001209/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001210/// escape this block or into any other store except @p StoreMA.
1211void ScopStmt::collectCandiateReductionLoads(
1212 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1213 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1214 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001215 return;
1216
1217 // Skip if there is not one binary operator between the load and the store
1218 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001219 if (!BinOp)
1220 return;
1221
1222 // Skip if the binary operators has multiple uses
1223 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001224 return;
1225
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001226 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001227 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1228 return;
1229
Johannes Doerfert9890a052014-07-01 00:32:29 +00001230 // Skip if the binary operator is outside the current SCoP
1231 if (BinOp->getParent() != Store->getParent())
1232 return;
1233
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001234 // Skip if it is a multiplicative reduction and we disabled them
1235 if (DisableMultiplicativeReductions &&
1236 (BinOp->getOpcode() == Instruction::Mul ||
1237 BinOp->getOpcode() == Instruction::FMul))
1238 return;
1239
Johannes Doerferte58a0122014-06-27 20:31:28 +00001240 // Check the binary operator operands for a candidate load
1241 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1242 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1243 if (!PossibleLoad0 && !PossibleLoad1)
1244 return;
1245
1246 // A load is only a candidate if it cannot escape (thus has only this use)
1247 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001248 if (PossibleLoad0->getParent() == Store->getParent())
1249 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001250 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001251 if (PossibleLoad1->getParent() == Store->getParent())
1252 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001253}
1254
1255/// @brief Check for reductions in this ScopStmt
1256///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001257/// Iterate over all store memory accesses and check for valid binary reduction
1258/// like chains. For all candidates we check if they have the same base address
1259/// and there are no other accesses which overlap with them. The base address
1260/// check rules out impossible reductions candidates early. The overlap check,
1261/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001262/// guarantees that none of the intermediate results will escape during
1263/// execution of the loop nest. We basically check here that no other memory
1264/// access can access the same memory as the potential reduction.
1265void ScopStmt::checkForReductions() {
1266 SmallVector<MemoryAccess *, 2> Loads;
1267 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1268
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001269 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001270 // stores and collecting possible reduction loads.
1271 for (MemoryAccess *StoreMA : MemAccs) {
1272 if (StoreMA->isRead())
1273 continue;
1274
1275 Loads.clear();
1276 collectCandiateReductionLoads(StoreMA, Loads);
1277 for (MemoryAccess *LoadMA : Loads)
1278 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1279 }
1280
1281 // Then check each possible candidate pair.
1282 for (const auto &CandidatePair : Candidates) {
1283 bool Valid = true;
1284 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1285 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1286
1287 // Skip those with obviously unequal base addresses.
1288 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1289 isl_map_free(LoadAccs);
1290 isl_map_free(StoreAccs);
1291 continue;
1292 }
1293
1294 // And check if the remaining for overlap with other memory accesses.
1295 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1296 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1297 isl_set *AllAccs = isl_map_range(AllAccsRel);
1298
1299 for (MemoryAccess *MA : MemAccs) {
1300 if (MA == CandidatePair.first || MA == CandidatePair.second)
1301 continue;
1302
1303 isl_map *AccRel =
1304 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1305 isl_set *Accs = isl_map_range(AccRel);
1306
1307 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1308 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1309 Valid = Valid && isl_set_is_empty(OverlapAccs);
1310 isl_set_free(OverlapAccs);
1311 }
1312 }
1313
1314 isl_set_free(AllAccs);
1315 if (!Valid)
1316 continue;
1317
Johannes Doerfertf6183392014-07-01 20:52:51 +00001318 const LoadInst *Load =
1319 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1320 MemoryAccess::ReductionType RT =
1321 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1322
Johannes Doerferte58a0122014-06-27 20:31:28 +00001323 // If no overlapping access was found we mark the load and store as
1324 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001325 CandidatePair.first->markAsReductionLike(RT);
1326 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001327 }
Tobias Grosser75805372011-04-29 06:27:02 +00001328}
1329
Tobias Grosser74394f02013-01-14 22:40:23 +00001330std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001331
Tobias Grosser54839312015-04-21 11:37:25 +00001332std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001333 auto *S = getSchedule();
1334 auto Str = stringFromIslObj(S);
1335 isl_map_free(S);
1336 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001337}
1338
Tobias Grosser74394f02013-01-14 22:40:23 +00001339unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001340
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001341unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001342
Tobias Grosser75805372011-04-29 06:27:02 +00001343const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1344
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001345const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001346 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001347}
1348
Tobias Grosser74394f02013-01-14 22:40:23 +00001349isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001350
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001351__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001352
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001353__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001354 return isl_set_get_space(Domain);
1355}
1356
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001357__isl_give isl_id *ScopStmt::getDomainId() const {
1358 return isl_set_get_tuple_id(Domain);
1359}
Tobias Grossercd95b772012-08-30 11:49:38 +00001360
Tobias Grosser75805372011-04-29 06:27:02 +00001361ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001362 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001363 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001364}
1365
1366void ScopStmt::print(raw_ostream &OS) const {
1367 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001368 OS.indent(12) << "Domain :=\n";
1369
1370 if (Domain) {
1371 OS.indent(16) << getDomainStr() << ";\n";
1372 } else
1373 OS.indent(16) << "n/a\n";
1374
Tobias Grosser54839312015-04-21 11:37:25 +00001375 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001376
1377 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001378 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001379 } else
1380 OS.indent(16) << "n/a\n";
1381
Tobias Grosser083d3d32014-06-28 08:59:45 +00001382 for (MemoryAccess *Access : MemAccs)
1383 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001384}
1385
1386void ScopStmt::dump() const { print(dbgs()); }
1387
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001388void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001389
1390 // Remove all memory accesses in @p InvMAs from this statement together
1391 // with all scalar accesses that were caused by them. The tricky iteration
1392 // order uses is needed because the MemAccs is a vector and the order in
1393 // which the accesses of each memory access list (MAL) are stored in this
1394 // vector is reversed.
1395 for (MemoryAccess *MA : InvMAs) {
1396 auto &MAL = *lookupAccessesFor(MA->getAccessInstruction());
1397 MAL.reverse();
1398
1399 auto MALIt = MAL.begin();
1400 auto MALEnd = MAL.end();
1401 auto MemAccsIt = MemAccs.begin();
1402 while (MALIt != MALEnd) {
1403 while (*MemAccsIt != *MALIt)
1404 MemAccsIt++;
1405
1406 MALIt++;
1407 MemAccs.erase(MemAccsIt);
1408 }
1409
1410 InstructionToAccess.erase(MA->getAccessInstruction());
1411 delete &MAL;
1412 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001413}
1414
Tobias Grosser75805372011-04-29 06:27:02 +00001415//===----------------------------------------------------------------------===//
1416/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001417
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001418void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001419 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1420 isl_set_free(Context);
1421 Context = NewContext;
1422}
1423
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001424const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
1425 return SCEVParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001426}
1427
Tobias Grosserabfbe632013-02-05 12:09:06 +00001428void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001429 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001430 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001431
1432 // Normalize the SCEV to get the representing element for an invariant load.
1433 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1434
Tobias Grosser60b54f12011-11-08 15:41:28 +00001435 if (ParameterIds.find(Parameter) != ParameterIds.end())
1436 continue;
1437
1438 int dimension = Parameters.size();
1439
1440 Parameters.push_back(Parameter);
1441 ParameterIds[Parameter] = dimension;
1442 }
1443}
1444
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001445__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001446 // Normalize the SCEV to get the representing element for an invariant load.
1447 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1448
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001449 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001450
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001451 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001452 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001453
Tobias Grosser8f99c162011-11-15 11:38:55 +00001454 std::string ParameterName;
1455
1456 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1457 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001458 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001459 }
1460
1461 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001462 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001463
Tobias Grosser20532b82014-04-11 17:56:49 +00001464 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1465 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001466}
Tobias Grosser75805372011-04-29 06:27:02 +00001467
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001468isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1469 isl_set *DomainContext = isl_union_set_params(getDomains());
1470 return isl_set_intersect_params(C, DomainContext);
1471}
1472
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001473void Scop::buildBoundaryContext() {
1474 BoundaryContext = Affinator.getWrappingContext();
1475 BoundaryContext = isl_set_complement(BoundaryContext);
1476 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
1477}
1478
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001479void Scop::addUserContext() {
1480 if (UserContextStr.empty())
1481 return;
1482
1483 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1484 isl_space *Space = getParamSpace();
1485 if (isl_space_dim(Space, isl_dim_param) !=
1486 isl_set_dim(UserContext, isl_dim_param)) {
1487 auto SpaceStr = isl_space_to_str(Space);
1488 errs() << "Error: the context provided in -polly-context has not the same "
1489 << "number of dimensions than the computed context. Due to this "
1490 << "mismatch, the -polly-context option is ignored. Please provide "
1491 << "the context in the parameter space: " << SpaceStr << ".\n";
1492 free(SpaceStr);
1493 isl_set_free(UserContext);
1494 isl_space_free(Space);
1495 return;
1496 }
1497
1498 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1499 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1500 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1501
1502 if (strcmp(NameContext, NameUserContext) != 0) {
1503 auto SpaceStr = isl_space_to_str(Space);
1504 errs() << "Error: the name of dimension " << i
1505 << " provided in -polly-context "
1506 << "is '" << NameUserContext << "', but the name in the computed "
1507 << "context is '" << NameContext
1508 << "'. Due to this name mismatch, "
1509 << "the -polly-context option is ignored. Please provide "
1510 << "the context in the parameter space: " << SpaceStr << ".\n";
1511 free(SpaceStr);
1512 isl_set_free(UserContext);
1513 isl_space_free(Space);
1514 return;
1515 }
1516
1517 UserContext =
1518 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1519 isl_space_get_dim_id(Space, isl_dim_param, i));
1520 }
1521
1522 Context = isl_set_intersect(Context, UserContext);
1523 isl_space_free(Space);
1524}
1525
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001526void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001527 DenseMap<const SCEV *, LoadInst *> EquivClasses;
1528
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001529 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001530 for (LoadInst *LInst : RIL) {
1531 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1532
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001533 LoadInst *&ClassRep = EquivClasses[PointerSCEV];
1534 if (!ClassRep)
1535 ClassRep = LInst;
1536 else
1537 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001538 }
1539}
1540
Tobias Grosser6be480c2011-11-08 15:41:13 +00001541void Scop::buildContext() {
1542 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001543 Context = isl_set_universe(isl_space_copy(Space));
1544 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001545}
1546
Tobias Grosser18daaca2012-05-22 10:47:27 +00001547void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001548 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001549 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001550
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001551 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001552
Johannes Doerferte7044942015-02-24 11:58:30 +00001553 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001554 }
1555}
1556
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001557void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001558 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001559 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001560
Tobias Grosser083d3d32014-06-28 08:59:45 +00001561 for (const auto &ParamID : ParameterIds) {
1562 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001563 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001564 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001565 }
1566
1567 // Align the parameters of all data structures to the model.
1568 Context = isl_set_align_params(Context, Space);
1569
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001570 for (ScopStmt &Stmt : *this)
1571 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001572}
1573
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001574static __isl_give isl_set *
1575simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1576 const Scop &S) {
1577 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1578 AssumptionContext = isl_set_gist_params(AssumptionContext, DomainParameters);
1579 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1580 return AssumptionContext;
1581}
1582
1583void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001584 // The parameter constraints of the iteration domains give us a set of
1585 // constraints that need to hold for all cases where at least a single
1586 // statement iteration is executed in the whole scop. We now simplify the
1587 // assumed context under the assumption that such constraints hold and at
1588 // least a single statement iteration is executed. For cases where no
1589 // statement instances are executed, the assumptions we have taken about
1590 // the executed code do not matter and can be changed.
1591 //
1592 // WARNING: This only holds if the assumptions we have taken do not reduce
1593 // the set of statement instances that are executed. Otherwise we
1594 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001595 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001596 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001597 // performed. In such a case, modifying the run-time conditions and
1598 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001599 // to not be executed.
1600 //
1601 // Example:
1602 //
1603 // When delinearizing the following code:
1604 //
1605 // for (long i = 0; i < 100; i++)
1606 // for (long j = 0; j < m; j++)
1607 // A[i+p][j] = 1.0;
1608 //
1609 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001610 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001611 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001612 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1613 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001614}
1615
Johannes Doerfertb164c792014-09-18 11:17:17 +00001616/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001617static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001618 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1619 isl_pw_multi_aff *MinPMA, *MaxPMA;
1620 isl_pw_aff *LastDimAff;
1621 isl_aff *OneAff;
1622 unsigned Pos;
1623
Johannes Doerfert9143d672014-09-27 11:02:39 +00001624 // Restrict the number of parameters involved in the access as the lexmin/
1625 // lexmax computation will take too long if this number is high.
1626 //
1627 // Experiments with a simple test case using an i7 4800MQ:
1628 //
1629 // #Parameters involved | Time (in sec)
1630 // 6 | 0.01
1631 // 7 | 0.04
1632 // 8 | 0.12
1633 // 9 | 0.40
1634 // 10 | 1.54
1635 // 11 | 6.78
1636 // 12 | 30.38
1637 //
1638 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1639 unsigned InvolvedParams = 0;
1640 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1641 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1642 InvolvedParams++;
1643
1644 if (InvolvedParams > RunTimeChecksMaxParameters) {
1645 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001646 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001647 }
1648 }
1649
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001650 Set = isl_set_remove_divs(Set);
1651
Johannes Doerfertb164c792014-09-18 11:17:17 +00001652 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1653 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1654
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001655 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1656 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1657
Johannes Doerfertb164c792014-09-18 11:17:17 +00001658 // Adjust the last dimension of the maximal access by one as we want to
1659 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1660 // we test during code generation might now point after the end of the
1661 // allocated array but we will never dereference it anyway.
1662 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1663 "Assumed at least one output dimension");
1664 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1665 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1666 OneAff = isl_aff_zero_on_domain(
1667 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1668 OneAff = isl_aff_add_constant_si(OneAff, 1);
1669 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1670 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1671
1672 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1673
1674 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001675 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001676}
1677
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001678static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1679 isl_set *Domain = MA->getStatement()->getDomain();
1680 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1681 return isl_set_reset_tuple_id(Domain);
1682}
1683
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001684/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1685static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001686 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001687 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001688
1689 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1690 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001691 Locations = isl_union_set_coalesce(Locations);
1692 Locations = isl_union_set_detect_equalities(Locations);
1693 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001694 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001695 isl_union_set_free(Locations);
1696 return Valid;
1697}
1698
Johannes Doerfert96425c22015-08-30 21:13:53 +00001699/// @brief Helper to treat non-affine regions and basic blocks the same.
1700///
1701///{
1702
1703/// @brief Return the block that is the representing block for @p RN.
1704static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1705 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1706 : RN->getNodeAs<BasicBlock>();
1707}
1708
1709/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001710static inline BasicBlock *
1711getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001712 if (RN->isSubRegion()) {
1713 assert(idx == 0);
1714 return RN->getNodeAs<Region>()->getExit();
1715 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001716 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001717}
1718
1719/// @brief Return the smallest loop surrounding @p RN.
1720static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1721 if (!RN->isSubRegion())
1722 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1723
1724 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1725 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1726 while (L && NonAffineSubRegion->contains(L))
1727 L = L->getParentLoop();
1728 return L;
1729}
1730
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001731static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1732 if (!RN->isSubRegion())
1733 return 1;
1734
1735 unsigned NumBlocks = 0;
1736 Region *R = RN->getNodeAs<Region>();
1737 for (auto BB : R->blocks()) {
1738 (void)BB;
1739 NumBlocks++;
1740 }
1741 return NumBlocks;
1742}
1743
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001744static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
1745 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00001746 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001747 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00001748 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001749 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00001750 return true;
1751 return false;
1752}
1753
Johannes Doerfert96425c22015-08-30 21:13:53 +00001754///}
1755
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001756static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1757 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001758 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001759 isl_id *DimId =
1760 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
1761 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
1762}
1763
Johannes Doerfert96425c22015-08-30 21:13:53 +00001764isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1765 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1766 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00001767 return getDomainConditions(BB);
1768}
1769
1770isl_set *Scop::getDomainConditions(BasicBlock *BB) {
1771 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001772 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001773}
1774
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001775void Scop::buildDomains(Region *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001776
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001777 auto *EntryBB = R->getEntry();
1778 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
1779 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001780
1781 Loop *L = LI.getLoopFor(EntryBB);
1782 while (LD-- >= 0) {
1783 S = addDomainDimId(S, LD + 1, L);
1784 L = L->getParentLoop();
1785 }
1786
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001787 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001788
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00001789 if (SD.isNonAffineSubRegion(R, R))
1790 return;
1791
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001792 buildDomainsWithBranchConstraints(R);
1793 propagateDomainConstraints(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001794}
1795
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001796void Scop::buildDomainsWithBranchConstraints(Region *R) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001797 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00001798
1799 // To create the domain for each block in R we iterate over all blocks and
1800 // subregions in R and propagate the conditions under which the current region
1801 // element is executed. To this end we iterate in reverse post order over R as
1802 // it ensures that we first visit all predecessors of a region node (either a
1803 // basic block or a subregion) before we visit the region node itself.
1804 // Initially, only the domain for the SCoP region entry block is set and from
1805 // there we propagate the current domain to all successors, however we add the
1806 // condition that the successor is actually executed next.
1807 // As we are only interested in non-loop carried constraints here we can
1808 // simply skip loop back edges.
1809
1810 ReversePostOrderTraversal<Region *> RTraversal(R);
1811 for (auto *RN : RTraversal) {
1812
1813 // Recurse for affine subregions but go on for basic blocks and non-affine
1814 // subregions.
1815 if (RN->isSubRegion()) {
1816 Region *SubRegion = RN->getNodeAs<Region>();
1817 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001818 buildDomainsWithBranchConstraints(SubRegion);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001819 continue;
1820 }
1821 }
1822
Johannes Doerfertf5673802015-10-01 23:48:18 +00001823 // Error blocks are assumed not to be executed. Therefor they are not
1824 // checked properly in the ScopDetection. Any attempt to generate control
1825 // conditions from them might result in a crash. However, this is only true
1826 // for the first step of the domain generation (this function) where we
1827 // push the control conditions of a block to the successors. In the second
1828 // step (propagateDomainConstraints) we only receive domain constraints from
1829 // the predecessors and can therefor look at the domain of a error block.
1830 // That allows us to generate the assumptions needed for them not to be
1831 // executed at runtime.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001832 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00001833 continue;
1834
Johannes Doerfert96425c22015-08-30 21:13:53 +00001835 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001836 TerminatorInst *TI = BB->getTerminator();
1837
Johannes Doerfertf5673802015-10-01 23:48:18 +00001838 isl_set *Domain = DomainMap.lookup(BB);
1839 if (!Domain) {
1840 DEBUG(dbgs() << "\tSkip: " << BB->getName()
1841 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001842 continue;
1843 }
1844
Johannes Doerfert96425c22015-08-30 21:13:53 +00001845 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001846
1847 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1848 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1849
1850 // Build the condition sets for the successor nodes of the current region
1851 // node. If it is a non-affine subregion we will always execute the single
1852 // exit node, hence the single entry node domain is the condition set. For
1853 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001854 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001855 if (RN->isSubRegion())
1856 ConditionSets.push_back(isl_set_copy(Domain));
1857 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001858 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001859
1860 // Now iterate over the successors and set their initial domain based on
1861 // their condition set. We skip back edges here and have to be careful when
1862 // we leave a loop not to keep constraints over a dimension that doesn't
1863 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001864 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00001865 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001866 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001867 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001868
1869 // Skip back edges.
1870 if (DT.dominates(SuccBB, BB)) {
1871 isl_set_free(CondSet);
1872 continue;
1873 }
1874
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001875 // Do not adjust the number of dimensions if we enter a boxed loop or are
1876 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001877 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001878 Region *SuccRegion = RI.getRegionFor(SuccBB);
Johannes Doerfert634909c2015-10-04 14:57:41 +00001879 if (SD.isNonAffineSubRegion(SuccRegion, &getRegion()))
1880 while (SuccBBLoop && SuccRegion->contains(SuccBBLoop))
1881 SuccBBLoop = SuccBBLoop->getParentLoop();
1882
1883 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001884
1885 // Check if the edge to SuccBB is a loop entry or exit edge. If so
1886 // adjust the dimensionality accordingly. Lastly, if we leave a loop
1887 // and enter a new one we need to drop the old constraints.
1888 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001889 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001890 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001891 CondSet = isl_set_project_out(CondSet, isl_dim_set,
1892 isl_set_n_dim(CondSet) - LoopDepthDiff,
1893 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001894 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001895 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001896 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001897 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001898 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001899 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001900 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
1901 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001902 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001903 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00001904 }
1905
1906 // Set the domain for the successor or merge it with an existing domain in
1907 // case there are multiple paths (without loop back edges) to the
1908 // successor block.
1909 isl_set *&SuccDomain = DomainMap[SuccBB];
1910 if (!SuccDomain)
1911 SuccDomain = CondSet;
1912 else
1913 SuccDomain = isl_set_union(SuccDomain, CondSet);
1914
1915 SuccDomain = isl_set_coalesce(SuccDomain);
Johannes Doerfert634909c2015-10-04 14:57:41 +00001916 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
1917 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001918 }
1919 }
1920}
1921
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001922/// @brief Return the domain for @p BB wrt @p DomainMap.
1923///
1924/// This helper function will lookup @p BB in @p DomainMap but also handle the
1925/// case where @p BB is contained in a non-affine subregion using the region
1926/// tree obtained by @p RI.
1927static __isl_give isl_set *
1928getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
1929 RegionInfo &RI) {
1930 auto DIt = DomainMap.find(BB);
1931 if (DIt != DomainMap.end())
1932 return isl_set_copy(DIt->getSecond());
1933
1934 Region *R = RI.getRegionFor(BB);
1935 while (R->getEntry() == BB)
1936 R = R->getParent();
1937 return getDomainForBlock(R->getEntry(), DomainMap, RI);
1938}
1939
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001940void Scop::propagateDomainConstraints(Region *R) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001941 // Iterate over the region R and propagate the domain constrains from the
1942 // predecessors to the current node. In contrast to the
1943 // buildDomainsWithBranchConstraints function, this one will pull the domain
1944 // information from the predecessors instead of pushing it to the successors.
1945 // Additionally, we assume the domains to be already present in the domain
1946 // map here. However, we iterate again in reverse post order so we know all
1947 // predecessors have been visited before a block or non-affine subregion is
1948 // visited.
1949
1950 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
1951 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
1952
1953 ReversePostOrderTraversal<Region *> RTraversal(R);
1954 for (auto *RN : RTraversal) {
1955
1956 // Recurse for affine subregions but go on for basic blocks and non-affine
1957 // subregions.
1958 if (RN->isSubRegion()) {
1959 Region *SubRegion = RN->getNodeAs<Region>();
1960 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001961 propagateDomainConstraints(SubRegion);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001962 continue;
1963 }
1964 }
1965
Johannes Doerfertf5673802015-10-01 23:48:18 +00001966 // Get the domain for the current block and check if it was initialized or
1967 // not. The only way it was not is if this block is only reachable via error
1968 // blocks, thus will not be executed under the assumptions we make. Such
1969 // blocks have to be skipped as their predecessors might not have domains
1970 // either. It would not benefit us to compute the domain anyway, only the
1971 // domains of the error blocks that are reachable from non-error blocks
1972 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001973 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00001974 isl_set *&Domain = DomainMap[BB];
1975 if (!Domain) {
1976 DEBUG(dbgs() << "\tSkip: " << BB->getName()
1977 << ", it is only reachable from error blocks.\n");
1978 DomainMap.erase(BB);
1979 continue;
1980 }
1981 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
1982
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001983 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1984 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1985
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001986 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
1987 for (auto *PredBB : predecessors(BB)) {
1988
1989 // Skip backedges
1990 if (DT.dominates(BB, PredBB))
1991 continue;
1992
1993 isl_set *PredBBDom = nullptr;
1994
1995 // Handle the SCoP entry block with its outside predecessors.
1996 if (!getRegion().contains(PredBB))
1997 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
1998
1999 if (!PredBBDom) {
2000 // Determine the loop depth of the predecessor and adjust its domain to
2001 // the domain of the current block. This can mean we have to:
2002 // o) Drop a dimension if this block is the exit of a loop, not the
2003 // header of a new loop and the predecessor was part of the loop.
2004 // o) Add an unconstrainted new dimension if this block is the header
2005 // of a loop and the predecessor is not part of it.
2006 // o) Drop the information about the innermost loop dimension when the
2007 // predecessor and the current block are surrounded by different
2008 // loops in the same depth.
2009 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2010 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2011 while (BoxedLoops.count(PredBBLoop))
2012 PredBBLoop = PredBBLoop->getParentLoop();
2013
2014 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002015 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002016 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002017 PredBBDom = isl_set_project_out(
2018 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2019 LoopDepthDiff);
2020 else if (PredBBLoopDepth < BBLoopDepth) {
2021 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002022 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002023 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2024 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002025 PredBBDom = isl_set_drop_constraints_involving_dims(
2026 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002027 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002028 }
2029
2030 PredDom = isl_set_union(PredDom, PredBBDom);
2031 }
2032
2033 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002034 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002035
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002036 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002037 addLoopBoundsToHeaderDomain(BBLoop);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002038
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002039 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002040 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002041 IsOptimized = true;
2042 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2043 addAssumption(isl_set_complement(DomPar));
2044 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002045 }
2046}
2047
2048/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2049/// is incremented by one and all other dimensions are equal, e.g.,
2050/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2051/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2052static __isl_give isl_map *
2053createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2054 auto *MapSpace = isl_space_map_from_set(SetSpace);
2055 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2056 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2057 if (u != Dim)
2058 NextIterationMap =
2059 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2060 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2061 C = isl_constraint_set_constant_si(C, 1);
2062 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2063 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2064 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2065 return NextIterationMap;
2066}
2067
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002068void Scop::addLoopBoundsToHeaderDomain(Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002069 int LoopDepth = getRelativeLoopDepth(L);
2070 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002071
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002072 BasicBlock *HeaderBB = L->getHeader();
2073 assert(DomainMap.count(HeaderBB));
2074 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002075
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002076 isl_map *NextIterationMap =
2077 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002078
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002079 isl_set *UnionBackedgeCondition =
2080 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002081
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002082 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2083 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002084
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002085 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002086
2087 // If the latch is only reachable via error statements we skip it.
2088 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2089 if (!LatchBBDom)
2090 continue;
2091
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002092 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002093
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002094 TerminatorInst *TI = LatchBB->getTerminator();
2095 BranchInst *BI = dyn_cast<BranchInst>(TI);
2096 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002097 BackedgeCondition = isl_set_copy(LatchBBDom);
2098 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002099 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002100 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002101 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002102
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002103 // Free the non back edge condition set as we do not need it.
2104 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002105
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002106 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002107 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002108
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002109 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2110 assert(LatchLoopDepth >= LoopDepth);
2111 BackedgeCondition =
2112 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2113 LatchLoopDepth - LoopDepth);
2114 UnionBackedgeCondition =
2115 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002116 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002117
2118 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2119 for (int i = 0; i < LoopDepth; i++)
2120 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2121
2122 isl_set *UnionBackedgeConditionComplement =
2123 isl_set_complement(UnionBackedgeCondition);
2124 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2125 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2126 UnionBackedgeConditionComplement =
2127 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2128 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2129 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2130
2131 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2132 HeaderBBDom = Parts.second;
2133
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002134 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2135 // the bounded assumptions to the context as they are already implied by the
2136 // <nsw> tag.
2137 if (Affinator.hasNSWAddRecForLoop(L)) {
2138 isl_set_free(Parts.first);
2139 return;
2140 }
2141
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002142 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2143 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfert707a4062015-09-20 16:38:19 +00002144 addAssumption(BoundedCtx);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002145}
2146
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002147void Scop::buildAliasChecks(AliasAnalysis &AA) {
2148 if (!PollyUseRuntimeAliasChecks)
2149 return;
2150
2151 if (buildAliasGroups(AA))
2152 return;
2153
2154 // If a problem occurs while building the alias groups we need to delete
2155 // this SCoP and pretend it wasn't valid in the first place. To this end
2156 // we make the assumed context infeasible.
2157 addAssumption(isl_set_empty(getParamSpace()));
2158
2159 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2160 << " could not be created as the number of parameters involved "
2161 "is too high. The SCoP will be "
2162 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2163 "the maximal number of parameters but be advised that the "
2164 "compile time might increase exponentially.\n\n");
2165}
2166
Johannes Doerfert9143d672014-09-27 11:02:39 +00002167bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002168 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002169 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002170 // for all memory accesses inside the SCoP.
2171 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002172 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002173 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002174 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002175 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002176 // if their access domains intersect, otherwise they are in different
2177 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002178 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002179 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002180 // and maximal accesses to each array of a group in read only and non
2181 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002182 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2183
2184 AliasSetTracker AST(AA);
2185
2186 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002187 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002188 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002189
2190 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002191 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002192 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2193 isl_set_free(StmtDomain);
2194 if (StmtDomainEmpty)
2195 continue;
2196
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002197 for (MemoryAccess *MA : Stmt) {
Michael Kruse8d0b7342015-09-25 21:21:00 +00002198 if (MA->isImplicit())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002199 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002200 if (!MA->isRead())
2201 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002202 Instruction *Acc = MA->getAccessInstruction();
2203 PtrToAcc[getPointerOperand(*Acc)] = MA;
2204 AST.add(Acc);
2205 }
2206 }
2207
2208 SmallVector<AliasGroupTy, 4> AliasGroups;
2209 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002210 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002211 continue;
2212 AliasGroupTy AG;
2213 for (auto PR : AS)
2214 AG.push_back(PtrToAcc[PR.getValue()]);
2215 assert(AG.size() > 1 &&
2216 "Alias groups should contain at least two accesses");
2217 AliasGroups.push_back(std::move(AG));
2218 }
2219
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002220 // Split the alias groups based on their domain.
2221 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2222 AliasGroupTy NewAG;
2223 AliasGroupTy &AG = AliasGroups[u];
2224 AliasGroupTy::iterator AGI = AG.begin();
2225 isl_set *AGDomain = getAccessDomain(*AGI);
2226 while (AGI != AG.end()) {
2227 MemoryAccess *MA = *AGI;
2228 isl_set *MADomain = getAccessDomain(MA);
2229 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2230 NewAG.push_back(MA);
2231 AGI = AG.erase(AGI);
2232 isl_set_free(MADomain);
2233 } else {
2234 AGDomain = isl_set_union(AGDomain, MADomain);
2235 AGI++;
2236 }
2237 }
2238 if (NewAG.size() > 1)
2239 AliasGroups.push_back(std::move(NewAG));
2240 isl_set_free(AGDomain);
2241 }
2242
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002243 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002244 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2245 for (AliasGroupTy &AG : AliasGroups) {
2246 NonReadOnlyBaseValues.clear();
2247 ReadOnlyPairs.clear();
2248
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002249 if (AG.size() < 2) {
2250 AG.clear();
2251 continue;
2252 }
2253
Johannes Doerfert13771732014-10-01 12:40:46 +00002254 for (auto II = AG.begin(); II != AG.end();) {
2255 Value *BaseAddr = (*II)->getBaseAddr();
2256 if (HasWriteAccess.count(BaseAddr)) {
2257 NonReadOnlyBaseValues.insert(BaseAddr);
2258 II++;
2259 } else {
2260 ReadOnlyPairs[BaseAddr].insert(*II);
2261 II = AG.erase(II);
2262 }
2263 }
2264
2265 // If we don't have read only pointers check if there are at least two
2266 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002267 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002268 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002269 continue;
2270 }
2271
2272 // If we don't have non read only pointers clear the alias group.
2273 if (NonReadOnlyBaseValues.empty()) {
2274 AG.clear();
2275 continue;
2276 }
2277
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002278 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002279 MinMaxAliasGroups.emplace_back();
2280 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2281 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2282 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2283 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002284
2285 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002286
2287 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002288 for (MemoryAccess *MA : AG)
2289 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002290
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002291 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2292 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002293
2294 // Bail out if the number of values we need to compare is too large.
2295 // This is important as the number of comparisions grows quadratically with
2296 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002297 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2298 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002299 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002300
2301 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002302 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002303 Accesses = isl_union_map_empty(getParamSpace());
2304
2305 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2306 for (MemoryAccess *MA : ReadOnlyPair.second)
2307 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2308
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002309 Valid =
2310 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002311
2312 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002313 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002314 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002315
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002316 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002317}
2318
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002319static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
2320 Loop *L = LI.getLoopFor(R.getEntry());
2321 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2322}
2323
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002324static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2325 ScopDetection &SD) {
2326
2327 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2328
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002329 unsigned MinLD = INT_MAX, MaxLD = 0;
2330 for (BasicBlock *BB : R.blocks()) {
2331 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002332 if (!R.contains(L))
2333 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002334 if (BoxedLoops && BoxedLoops->count(L))
2335 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002336 unsigned LD = L->getLoopDepth();
2337 MinLD = std::min(MinLD, LD);
2338 MaxLD = std::max(MaxLD, LD);
2339 }
2340 }
2341
2342 // Handle the case that there is no loop in the SCoP first.
2343 if (MaxLD == 0)
2344 return 1;
2345
2346 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2347 assert(MaxLD >= MinLD &&
2348 "Maximal loop depth was smaller than mininaml loop depth?");
2349 return MaxLD - MinLD + 1;
2350}
2351
Johannes Doerfert478a7de2015-10-02 13:09:31 +00002352Scop::Scop(Region &R, AccFuncMapType &AccFuncMap, ScopDetection &SD,
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002353 ScalarEvolution &ScalarEvolution, DominatorTree &DT, LoopInfo &LI,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002354 isl_ctx *Context, unsigned MaxLoopDepth)
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002355 : LI(LI), DT(DT), SE(&ScalarEvolution), SD(SD), R(R),
2356 AccFuncMap(AccFuncMap), IsOptimized(false),
2357 HasSingleExitEdge(R.getExitingBlock()), MaxLoopDepth(MaxLoopDepth),
2358 IslCtx(Context), Context(nullptr), Affinator(this),
2359 AssumedContext(nullptr), BoundaryContext(nullptr), Schedule(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002360
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002361void Scop::init(AliasAnalysis &AA) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002362 buildContext();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002363 buildInvariantEquivalenceClasses();
2364
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002365 buildDomains(&R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002366
Michael Krusecac948e2015-10-02 13:53:07 +00002367 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002368 // Exit early in case there are no executable statements left in this scop.
Michael Krusecac948e2015-10-02 13:53:07 +00002369 simplifySCoP(true);
Michael Kruseafe06702015-10-02 16:33:27 +00002370 if (Stmts.empty())
2371 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002372
Michael Krusecac948e2015-10-02 13:53:07 +00002373 // The ScopStmts now have enough information to initialize themselves.
2374 for (ScopStmt &Stmt : Stmts)
2375 Stmt.init();
2376
2377 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002378 Loop *L = getLoopSurroundingRegion(R, LI);
2379 LoopSchedules[L];
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002380 buildSchedule(&R, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002381 Schedule = LoopSchedules[L].first;
Tobias Grosser75805372011-04-29 06:27:02 +00002382
Tobias Grosser8286b832015-11-02 11:29:32 +00002383 if (isl_set_is_empty(AssumedContext))
2384 return;
2385
2386 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002387 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002388 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002389 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002390 buildBoundaryContext();
2391 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002392 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002393
2394 hoistInvariantLoads();
Michael Krusecac948e2015-10-02 13:53:07 +00002395 simplifySCoP(false);
Tobias Grosser75805372011-04-29 06:27:02 +00002396}
2397
2398Scop::~Scop() {
2399 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002400 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002401 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002402 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002403
Johannes Doerfert96425c22015-08-30 21:13:53 +00002404 for (auto It : DomainMap)
2405 isl_set_free(It.second);
2406
Johannes Doerfertb164c792014-09-18 11:17:17 +00002407 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002408 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002409 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002410 isl_pw_multi_aff_free(MMA.first);
2411 isl_pw_multi_aff_free(MMA.second);
2412 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002413 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002414 isl_pw_multi_aff_free(MMA.first);
2415 isl_pw_multi_aff_free(MMA.second);
2416 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002417 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002418
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002419 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002420 isl_set_free(std::get<2>(IAClass));
Tobias Grosser75805372011-04-29 06:27:02 +00002421}
2422
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002423void Scop::updateAccessDimensionality() {
2424 for (auto &Stmt : *this)
2425 for (auto &Access : Stmt)
2426 Access->updateDimensionality();
2427}
2428
Michael Krusecac948e2015-10-02 13:53:07 +00002429void Scop::simplifySCoP(bool RemoveIgnoredStmts) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002430 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2431 ScopStmt &Stmt = *StmtIt;
Michael Krusecac948e2015-10-02 13:53:07 +00002432 RegionNode *RN = Stmt.isRegionStmt()
2433 ? Stmt.getRegion()->getNode()
2434 : getRegion().getBBNode(Stmt.getBasicBlock());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002435
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002436 if (StmtIt->isEmpty() ||
2437 isl_set_is_empty(DomainMap[getRegionNodeBasicBlock(RN)]) ||
2438 (RemoveIgnoredStmts && isIgnored(RN))) {
2439
Michael Krusecac948e2015-10-02 13:53:07 +00002440 // Remove the statement because it is unnecessary.
2441 if (Stmt.isRegionStmt())
2442 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2443 StmtMap.erase(BB);
2444 else
2445 StmtMap.erase(Stmt.getBasicBlock());
2446
2447 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002448 continue;
2449 }
2450
Michael Krusecac948e2015-10-02 13:53:07 +00002451 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002452 }
2453}
2454
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002455const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2456 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2457 if (!LInst)
2458 return nullptr;
2459
2460 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2461 LInst = cast<LoadInst>(Rep);
2462
2463 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2464 for (auto &IAClass : InvariantEquivClasses)
2465 if (PointerSCEV == std::get<0>(IAClass))
2466 return &IAClass;
2467
2468 return nullptr;
2469}
2470
2471void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2472
2473 // Get the context under which the statement is executed.
2474 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2475 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2476 DomainCtx = isl_set_detect_equalities(DomainCtx);
2477 DomainCtx = isl_set_coalesce(DomainCtx);
2478
2479 // Project out all parameters that relate to loads in the statement. Otherwise
2480 // we could have cyclic dependences on the constraints under which the
2481 // hoisted loads are executed and we could not determine an order in which to
2482 // pre-load them. This happens because not only lower bounds are part of the
2483 // domain but also upper bounds.
2484 for (MemoryAccess *MA : InvMAs) {
2485 Instruction *AccInst = MA->getAccessInstruction();
2486 if (SE->isSCEVable(AccInst->getType())) {
2487 isl_id *ParamId = getIdForParam(SE->getSCEV(AccInst));
2488 if (ParamId) {
2489 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2490 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2491 }
2492 isl_id_free(ParamId);
2493 }
2494 }
2495
2496 for (MemoryAccess *MA : InvMAs) {
2497 // Check for another invariant access that accesses the same location as
2498 // MA and if found consolidate them. Otherwise create a new equivalence
2499 // class at the end of InvariantEquivClasses.
2500 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
2501 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2502
2503 bool Consolidated = false;
2504 for (auto &IAClass : InvariantEquivClasses) {
2505 if (PointerSCEV != std::get<0>(IAClass))
2506 continue;
2507
2508 Consolidated = true;
2509
2510 // Add MA to the list of accesses that are in this class.
2511 auto &MAs = std::get<1>(IAClass);
2512 MAs.push_front(MA);
2513
2514 // Unify the execution context of the class and this statement.
2515 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
2516 IAClassDomainCtx = isl_set_coalesce(
2517 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
2518 break;
2519 }
2520
2521 if (Consolidated)
2522 continue;
2523
2524 // If we did not consolidate MA, thus did not find an equivalence class
2525 // for it, we create a new one.
2526 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
2527 isl_set_copy(DomainCtx));
2528 }
2529
2530 isl_set_free(DomainCtx);
2531}
2532
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002533void Scop::hoistInvariantLoads() {
2534 isl_union_map *Writes = getWrites();
2535 for (ScopStmt &Stmt : *this) {
2536
2537 // TODO: Loads that are not loop carried, hence are in a statement with
2538 // zero iterators, are by construction invariant, though we
Johannes Doerfert09e36972015-10-07 20:17:36 +00002539 // currently "hoist" them anyway. This is necessary because we allow
2540 // them to be treated as parameters (e.g., in conditions) and our code
2541 // generation would otherwise use the old value.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002542
Johannes Doerfert8930f482015-10-02 14:51:00 +00002543 BasicBlock *BB = Stmt.isBlockStmt() ? Stmt.getBasicBlock()
2544 : Stmt.getRegion()->getEntry();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002545 isl_set *Domain = Stmt.getDomain();
2546 MemoryAccessList InvMAs;
2547
2548 for (MemoryAccess *MA : Stmt) {
2549 if (MA->isImplicit() || MA->isWrite() || !MA->isAffine())
2550 continue;
2551
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002552 // Skip accesses that have an invariant base pointer which is defined but
2553 // not loaded inside the SCoP. This can happened e.g., if a readnone call
2554 // returns a pointer that is used as a base address. However, as we want
2555 // to hoist indirect pointers, we allow the base pointer to be defined in
Johannes Doerfert654c3282015-10-21 22:14:57 +00002556 // the region if it is also a memory access. Each ScopArrayInfo object
2557 // that has a base pointer origin has a base pointer that is loaded and
2558 // that it is invariant, thus it will be hoisted too. However, if there is
Tobias Grosser27e19a02015-10-25 12:05:14 +00002559 // no base pointer origin we check that the base pointer is defined
Johannes Doerfert654c3282015-10-21 22:14:57 +00002560 // outside the region.
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002561 const ScopArrayInfo *SAI = MA->getScopArrayInfo();
Johannes Doerfert654c3282015-10-21 22:14:57 +00002562 while (auto *BasePtrOriginSAI = SAI->getBasePtrOriginSAI())
2563 SAI = BasePtrOriginSAI;
2564
2565 if (auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr()))
2566 if (R.contains(BasePtrInst))
2567 continue;
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002568
Johannes Doerfert8930f482015-10-02 14:51:00 +00002569 // Skip accesses in non-affine subregions as they might not be executed
2570 // under the same condition as the entry of the non-affine subregion.
2571 if (BB != MA->getAccessInstruction()->getParent())
2572 continue;
2573
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002574 isl_map *AccessRelation = MA->getAccessRelation();
Johannes Doerfertb864c2c2015-10-18 19:50:18 +00002575
2576 // Skip accesses that have an empty access relation. These can be caused
2577 // by multiple offsets with a type cast in-between that cause the overall
2578 // byte offset to be not divisible by the new types sizes.
2579 if (isl_map_is_empty(AccessRelation)) {
2580 isl_map_free(AccessRelation);
2581 continue;
2582 }
2583
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002584 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
2585 Stmt.getNumIterators())) {
2586 isl_map_free(AccessRelation);
2587 continue;
2588 }
2589
2590 AccessRelation =
2591 isl_map_intersect_domain(AccessRelation, isl_set_copy(Domain));
2592 isl_set *AccessRange = isl_map_range(AccessRelation);
2593
2594 isl_union_map *Written = isl_union_map_intersect_range(
2595 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
2596 bool IsWritten = !isl_union_map_is_empty(Written);
2597 isl_union_map_free(Written);
2598
2599 if (IsWritten)
2600 continue;
2601
2602 InvMAs.push_front(MA);
2603 }
2604
2605 // We inserted invariant accesses always in the front but need them to be
2606 // sorted in a "natural order". The statements are already sorted in reverse
2607 // post order and that suffices for the accesses too. The reason we require
2608 // an order in the first place is the dependences between invariant loads
2609 // that can be caused by indirect loads.
2610 InvMAs.reverse();
2611
2612 // Transfer the memory access from the statement to the SCoP.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002613 Stmt.removeMemoryAccesses(InvMAs);
2614 addInvariantLoads(Stmt, InvMAs);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002615
2616 isl_set_free(Domain);
2617 }
2618 isl_union_map_free(Writes);
2619
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002620 if (!InvariantEquivClasses.empty())
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002621 IsOptimized = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00002622
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002623 auto &ScopRIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert09e36972015-10-07 20:17:36 +00002624 // Check required invariant loads that were tagged during SCoP detection.
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002625 for (LoadInst *LI : ScopRIL) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00002626 assert(LI && getRegion().contains(LI));
2627 ScopStmt *Stmt = getStmtForBasicBlock(LI->getParent());
2628 if (Stmt && Stmt->lookupAccessesFor(LI) != nullptr) {
2629 DEBUG(dbgs() << "\n\nWARNING: Load (" << *LI
2630 << ") is required to be invariant but was not marked as "
2631 "such. SCoP for "
2632 << getRegion() << " will be dropped\n\n");
2633 addAssumption(isl_set_empty(getParamSpace()));
2634 return;
2635 }
2636 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002637}
2638
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002639const ScopArrayInfo *
2640Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Michael Kruse28468772015-09-14 15:45:33 +00002641 ArrayRef<const SCEV *> Sizes, bool IsPHI) {
Tobias Grosser92245222015-07-28 14:53:44 +00002642 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002643 if (!SAI) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002644 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, IsPHI,
2645 this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002646 } else {
Tobias Grosser8286b832015-11-02 11:29:32 +00002647 // In case of mismatching array sizes, we bail out by setting the run-time
2648 // context to false.
2649 if (!SAI->updateSizes(Sizes))
2650 addAssumption(isl_set_empty(getParamSpace()));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002651 }
Tobias Grosserab671442015-05-23 05:58:27 +00002652 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002653}
2654
Tobias Grosser92245222015-07-28 14:53:44 +00002655const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, bool IsPHI) {
2656 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002657 assert(SAI && "No ScopArrayInfo available for this base pointer");
2658 return SAI;
2659}
2660
Tobias Grosser74394f02013-01-14 22:40:23 +00002661std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002662std::string Scop::getAssumedContextStr() const {
2663 return stringFromIslObj(AssumedContext);
2664}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002665std::string Scop::getBoundaryContextStr() const {
2666 return stringFromIslObj(BoundaryContext);
2667}
Tobias Grosser75805372011-04-29 06:27:02 +00002668
2669std::string Scop::getNameStr() const {
2670 std::string ExitName, EntryName;
2671 raw_string_ostream ExitStr(ExitName);
2672 raw_string_ostream EntryStr(EntryName);
2673
Tobias Grosserf240b482014-01-09 10:42:15 +00002674 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002675 EntryStr.str();
2676
2677 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00002678 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002679 ExitStr.str();
2680 } else
2681 ExitName = "FunctionExit";
2682
2683 return EntryName + "---" + ExitName;
2684}
2685
Tobias Grosser74394f02013-01-14 22:40:23 +00002686__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00002687__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002688 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00002689}
2690
Tobias Grossere86109f2013-10-29 21:05:49 +00002691__isl_give isl_set *Scop::getAssumedContext() const {
2692 return isl_set_copy(AssumedContext);
2693}
2694
Johannes Doerfert43788c52015-08-20 05:58:56 +00002695__isl_give isl_set *Scop::getRuntimeCheckContext() const {
2696 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002697 RuntimeCheckContext =
2698 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
2699 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002700 return RuntimeCheckContext;
2701}
2702
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002703bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002704 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002705 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002706 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
2707 isl_set_free(RuntimeCheckContext);
2708 return IsFeasible;
2709}
2710
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002711void Scop::addAssumption(__isl_take isl_set *Set) {
2712 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00002713 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002714}
2715
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002716__isl_give isl_set *Scop::getBoundaryContext() const {
2717 return isl_set_copy(BoundaryContext);
2718}
2719
Tobias Grosser75805372011-04-29 06:27:02 +00002720void Scop::printContext(raw_ostream &OS) const {
2721 OS << "Context:\n";
2722
2723 if (!Context) {
2724 OS.indent(4) << "n/a\n\n";
2725 return;
2726 }
2727
2728 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00002729
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002730 OS.indent(4) << "Assumed Context:\n";
2731 if (!AssumedContext) {
2732 OS.indent(4) << "n/a\n\n";
2733 return;
2734 }
2735
2736 OS.indent(4) << getAssumedContextStr() << "\n";
2737
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002738 OS.indent(4) << "Boundary Context:\n";
2739 if (!BoundaryContext) {
2740 OS.indent(4) << "n/a\n\n";
2741 return;
2742 }
2743
2744 OS.indent(4) << getBoundaryContextStr() << "\n";
2745
Tobias Grosser083d3d32014-06-28 08:59:45 +00002746 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00002747 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00002748 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
2749 }
Tobias Grosser75805372011-04-29 06:27:02 +00002750}
2751
Johannes Doerfertb164c792014-09-18 11:17:17 +00002752void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002753 int noOfGroups = 0;
2754 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002755 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002756 noOfGroups += 1;
2757 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002758 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002759 }
2760
Tobias Grosserbb853c22015-07-25 12:31:03 +00002761 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00002762 if (MinMaxAliasGroups.empty()) {
2763 OS.indent(8) << "n/a\n";
2764 return;
2765 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002766
Tobias Grosserbb853c22015-07-25 12:31:03 +00002767 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002768
2769 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002770 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002771 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002772 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002773 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2774 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002775 }
2776 OS << " ]]\n";
2777 }
2778
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002779 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002780 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00002781 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002782 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002783 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2784 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002785 }
2786 OS << " ]]\n";
2787 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002788 }
2789}
2790
Tobias Grosser75805372011-04-29 06:27:02 +00002791void Scop::printStatements(raw_ostream &OS) const {
2792 OS << "Statements {\n";
2793
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002794 for (const ScopStmt &Stmt : *this)
2795 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00002796
2797 OS.indent(4) << "}\n";
2798}
2799
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002800void Scop::printArrayInfo(raw_ostream &OS) const {
2801 OS << "Arrays {\n";
2802
Tobias Grosserab671442015-05-23 05:58:27 +00002803 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002804 Array.second->print(OS);
2805
2806 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002807
2808 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
2809
2810 for (auto &Array : arrays())
2811 Array.second->print(OS, /* SizeAsPwAff */ true);
2812
2813 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002814}
2815
Tobias Grosser75805372011-04-29 06:27:02 +00002816void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00002817 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
2818 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00002819 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00002820 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002821 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002822 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002823 const auto &MAs = std::get<1>(IAClass);
2824 if (MAs.empty()) {
2825 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002826 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002827 MAs.front()->print(OS);
2828 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002829 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002830 }
2831 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00002832 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002833 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002834 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00002835 printStatements(OS.indent(4));
2836}
2837
2838void Scop::dump() const { print(dbgs()); }
2839
Tobias Grosser9a38ab82011-11-08 15:41:03 +00002840isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00002841
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002842__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
2843 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00002844}
2845
Tobias Grosser808cd692015-07-14 09:33:13 +00002846__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002847 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002848
Tobias Grosser808cd692015-07-14 09:33:13 +00002849 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002850 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002851
2852 return Domain;
2853}
2854
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002855__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002856 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002857
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002858 for (ScopStmt &Stmt : *this) {
2859 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002860 if (!MA->isMustWrite())
2861 continue;
2862
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002863 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002864 isl_map *AccessDomain = MA->getAccessRelation();
2865 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2866 Write = isl_union_map_add_map(Write, AccessDomain);
2867 }
2868 }
2869 return isl_union_map_coalesce(Write);
2870}
2871
2872__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002873 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002874
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002875 for (ScopStmt &Stmt : *this) {
2876 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002877 if (!MA->isMayWrite())
2878 continue;
2879
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002880 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002881 isl_map *AccessDomain = MA->getAccessRelation();
2882 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2883 Write = isl_union_map_add_map(Write, AccessDomain);
2884 }
2885 }
2886 return isl_union_map_coalesce(Write);
2887}
2888
Tobias Grosser37eb4222014-02-20 21:43:54 +00002889__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002890 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002891
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002892 for (ScopStmt &Stmt : *this) {
2893 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002894 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002895 continue;
2896
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002897 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002898 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002899 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2900 Write = isl_union_map_add_map(Write, AccessDomain);
2901 }
2902 }
2903 return isl_union_map_coalesce(Write);
2904}
2905
2906__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002907 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002908
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002909 for (ScopStmt &Stmt : *this) {
2910 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002911 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002912 continue;
2913
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002914 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002915 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002916
2917 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2918 Read = isl_union_map_add_map(Read, AccessDomain);
2919 }
2920 }
2921 return isl_union_map_coalesce(Read);
2922}
2923
Tobias Grosser808cd692015-07-14 09:33:13 +00002924__isl_give isl_union_map *Scop::getSchedule() const {
2925 auto Tree = getScheduleTree();
2926 auto S = isl_schedule_get_map(Tree);
2927 isl_schedule_free(Tree);
2928 return S;
2929}
Tobias Grosser37eb4222014-02-20 21:43:54 +00002930
Tobias Grosser808cd692015-07-14 09:33:13 +00002931__isl_give isl_schedule *Scop::getScheduleTree() const {
2932 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
2933 getDomains());
2934}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002935
Tobias Grosser808cd692015-07-14 09:33:13 +00002936void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
2937 auto *S = isl_schedule_from_domain(getDomains());
2938 S = isl_schedule_insert_partial_schedule(
2939 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
2940 isl_schedule_free(Schedule);
2941 Schedule = S;
2942}
2943
2944void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
2945 isl_schedule_free(Schedule);
2946 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00002947}
2948
2949bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
2950 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002951 for (ScopStmt &Stmt : *this) {
2952 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002953 isl_union_set *NewStmtDomain = isl_union_set_intersect(
2954 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
2955
2956 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
2957 isl_union_set_free(StmtDomain);
2958 isl_union_set_free(NewStmtDomain);
2959 continue;
2960 }
2961
2962 Changed = true;
2963
2964 isl_union_set_free(StmtDomain);
2965 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
2966
2967 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002968 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002969 isl_union_set_free(NewStmtDomain);
2970 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002971 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002972 }
2973 isl_union_set_free(Domain);
2974 return Changed;
2975}
2976
Tobias Grosser75805372011-04-29 06:27:02 +00002977ScalarEvolution *Scop::getSE() const { return SE; }
2978
Johannes Doerfertf5673802015-10-01 23:48:18 +00002979bool Scop::isIgnored(RegionNode *RN) {
2980 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser75805372011-04-29 06:27:02 +00002981
Johannes Doerfertf5673802015-10-01 23:48:18 +00002982 // Check if there are accesses contained.
2983 bool ContainsAccesses = false;
2984 if (!RN->isSubRegion())
2985 ContainsAccesses = getAccessFunctions(BB);
2986 else
2987 for (BasicBlock *RBB : RN->getNodeAs<Region>()->blocks())
2988 ContainsAccesses |= (getAccessFunctions(RBB) != nullptr);
2989 if (!ContainsAccesses)
2990 return true;
2991
2992 // Check for reachability via non-error blocks.
2993 if (!DomainMap.count(BB))
2994 return true;
2995
2996 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002997 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002998 return true;
2999
3000 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003001}
3002
Tobias Grosser808cd692015-07-14 09:33:13 +00003003struct MapToDimensionDataTy {
3004 int N;
3005 isl_union_pw_multi_aff *Res;
3006};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003007
Tobias Grosser808cd692015-07-14 09:33:13 +00003008// @brief Create a function that maps the elements of 'Set' to its N-th
3009// dimension.
3010//
3011// The result is added to 'User->Res'.
3012//
3013// @param Set The input set.
3014// @param N The dimension to map to.
3015//
3016// @returns Zero if no error occurred, non-zero otherwise.
3017static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3018 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3019 int Dim;
3020 isl_space *Space;
3021 isl_pw_multi_aff *PMA;
3022
3023 Dim = isl_set_dim(Set, isl_dim_set);
3024 Space = isl_set_get_space(Set);
3025 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3026 Dim - Data->N);
3027 if (Data->N > 1)
3028 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3029 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3030
3031 isl_set_free(Set);
3032
3033 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003034}
3035
Tobias Grosser808cd692015-07-14 09:33:13 +00003036// @brief Create a function that maps the elements of Domain to their Nth
3037// dimension.
3038//
3039// @param Domain The set of elements to map.
3040// @param N The dimension to map to.
3041static __isl_give isl_multi_union_pw_aff *
3042mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003043 if (N <= 0 || isl_union_set_is_empty(Domain)) {
3044 isl_union_set_free(Domain);
3045 return nullptr;
3046 }
3047
Tobias Grosser808cd692015-07-14 09:33:13 +00003048 struct MapToDimensionDataTy Data;
3049 isl_space *Space;
3050
3051 Space = isl_union_set_get_space(Domain);
3052 Data.N = N;
3053 Data.Res = isl_union_pw_multi_aff_empty(Space);
3054 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
3055 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
3056
3057 isl_union_set_free(Domain);
3058 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3059}
3060
Michael Kruse9d080092015-09-11 21:41:48 +00003061ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003062 ScopStmt *Stmt;
3063 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003064 Stmts.emplace_back(*this, *BB);
Tobias Grosser808cd692015-07-14 09:33:13 +00003065 Stmt = &Stmts.back();
3066 StmtMap[BB] = Stmt;
3067 } else {
3068 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003069 Stmts.emplace_back(*this, *R);
Tobias Grosser808cd692015-07-14 09:33:13 +00003070 Stmt = &Stmts.back();
3071 for (BasicBlock *BB : R->blocks())
3072 StmtMap[BB] = Stmt;
3073 }
3074 return Stmt;
3075}
3076
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003077void Scop::buildSchedule(
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003078 Region *R,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003079 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00003080
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003081 if (SD.isNonAffineSubRegion(R, &getRegion())) {
Johannes Doerfertc6987c12015-09-26 13:41:43 +00003082 Loop *L = getLoopSurroundingRegion(*R, LI);
3083 auto &LSchedulePair = LoopSchedules[L];
Michael Krusecac948e2015-10-02 13:53:07 +00003084 ScopStmt *Stmt = getStmtForBasicBlock(R->getEntry());
Michael Kruseafe06702015-10-02 16:33:27 +00003085 isl_set *Domain = Stmt->getDomain();
Michael Krusecac948e2015-10-02 13:53:07 +00003086 auto *UDomain = isl_union_set_from_set(Domain);
3087 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003088 LSchedulePair.first = StmtSchedule;
3089 return;
3090 }
3091
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003092 ReversePostOrderTraversal<Region *> RTraversal(R);
3093 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00003094
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003095 if (RN->isSubRegion()) {
3096 Region *SubRegion = RN->getNodeAs<Region>();
3097 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003098 buildSchedule(SubRegion, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003099 continue;
3100 }
Tobias Grosser75805372011-04-29 06:27:02 +00003101 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003102
3103 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert30c22652015-10-18 21:17:11 +00003104 if (!getRegion().contains(L))
3105 L = getLoopSurroundingRegion(getRegion(), LI);
3106
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003107 int LD = getRelativeLoopDepth(L);
3108 auto &LSchedulePair = LoopSchedules[L];
3109 LSchedulePair.second += getNumBlocksInRegionNode(RN);
3110
Michael Krusecac948e2015-10-02 13:53:07 +00003111 BasicBlock *BB = getRegionNodeBasicBlock(RN);
3112 ScopStmt *Stmt = getStmtForBasicBlock(BB);
3113 if (Stmt) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003114 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3115 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
3116 LSchedulePair.first =
3117 combineInSequence(LSchedulePair.first, StmtSchedule);
3118 }
3119
3120 unsigned NumVisited = LSchedulePair.second;
3121 while (L && NumVisited == L->getNumBlocks()) {
3122 auto *LDomain = isl_schedule_get_domain(LSchedulePair.first);
3123 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
3124 LSchedulePair.first =
3125 isl_schedule_insert_partial_schedule(LSchedulePair.first, MUPA);
3126
3127 auto *PL = L->getParentLoop();
Johannes Doerfertdca28372015-11-03 00:28:07 +00003128
3129 // Either we have a proper loop and we also build a schedule for the
3130 // parent loop or we have a infinite loop that does not have a proper
3131 // parent loop. In the former case this conditional will be skipped, in
3132 // the latter case however we will break here as we do not build a domain
3133 // nor a schedule for a infinite loop.
3134 assert(LoopSchedules.count(PL) || LSchedulePair.first == nullptr);
3135 if (!LoopSchedules.count(PL))
3136 break;
3137
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003138 auto &PSchedulePair = LoopSchedules[PL];
3139 PSchedulePair.first =
3140 combineInSequence(PSchedulePair.first, LSchedulePair.first);
3141 PSchedulePair.second += NumVisited;
3142
3143 L = PL;
3144 NumVisited = PSchedulePair.second;
3145 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003146 }
Tobias Grosser75805372011-04-29 06:27:02 +00003147}
3148
Johannes Doerfert7c494212014-10-31 23:13:39 +00003149ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003150 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003151 if (StmtMapIt == StmtMap.end())
3152 return nullptr;
3153 return StmtMapIt->second;
3154}
3155
Johannes Doerfert96425c22015-08-30 21:13:53 +00003156int Scop::getRelativeLoopDepth(const Loop *L) const {
3157 Loop *OuterLoop =
3158 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3159 if (!OuterLoop)
3160 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003161 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3162}
3163
Michael Krused868b5d2015-09-10 15:25:24 +00003164void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003165 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003166
3167 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3168 // true, are not modeled as ordinary PHI nodes as they are not part of the
3169 // region. However, we model the operands in the predecessor blocks that are
3170 // part of the region as regular scalar accesses.
3171
3172 // If we can synthesize a PHI we can skip it, however only if it is in
3173 // the region. If it is not it can only be in the exit block of the region.
3174 // In this case we model the operands but not the PHI itself.
3175 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3176 return;
3177
3178 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3179 // detection. Hence, the PHI is a load of a new memory location in which the
3180 // incoming value was written at the end of the incoming basic block.
3181 bool OnlyNonAffineSubRegionOperands = true;
3182 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3183 Value *Op = PHI->getIncomingValue(u);
3184 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3185
3186 // Do not build scalar dependences inside a non-affine subregion.
3187 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3188 continue;
3189
3190 OnlyNonAffineSubRegionOperands = false;
3191
3192 if (!R.contains(OpBB))
3193 continue;
3194
3195 Instruction *OpI = dyn_cast<Instruction>(Op);
3196 if (OpI) {
3197 BasicBlock *OpIBB = OpI->getParent();
3198 // As we pretend there is a use (or more precise a write) of OpI in OpBB
3199 // we have to insert a scalar dependence from the definition of OpI to
3200 // OpBB if the definition is not in OpBB.
Michael Kruse668af712015-10-15 14:45:48 +00003201 if (scop->getStmtForBasicBlock(OpIBB) !=
3202 scop->getStmtForBasicBlock(OpBB)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003203 addScalarReadAccess(OpI, PHI, OpBB);
3204 addScalarWriteAccess(OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003205 }
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003206 } else if (ModelReadOnlyScalars && !isa<Constant>(Op)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003207 addScalarReadAccess(Op, PHI, OpBB);
Michael Kruse7bf39442015-09-10 12:46:52 +00003208 }
3209
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003210 addPHIWriteAccess(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003211 }
3212
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003213 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3214 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003215 }
3216}
3217
Michael Krused868b5d2015-09-10 15:25:24 +00003218bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
3219 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003220 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
3221 if (isIgnoredIntrinsic(Inst))
3222 return false;
3223
3224 bool AnyCrossStmtUse = false;
3225 BasicBlock *ParentBB = Inst->getParent();
3226
3227 for (User *U : Inst->users()) {
3228 Instruction *UI = dyn_cast<Instruction>(U);
3229
3230 // Ignore the strange user
3231 if (UI == 0)
3232 continue;
3233
3234 BasicBlock *UseParent = UI->getParent();
3235
Tobias Grosserbaffa092015-10-24 20:55:27 +00003236 // Ignore basic block local uses. A value that is defined in a scop, but
3237 // used in a PHI node in the same basic block does not count as basic block
3238 // local, as for such cases a control flow edge is passed between definition
3239 // and use.
3240 if (UseParent == ParentBB && !isa<PHINode>(UI))
Michael Kruse7bf39442015-09-10 12:46:52 +00003241 continue;
3242
3243 // Do not build scalar dependences inside a non-affine subregion.
3244 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
3245 continue;
3246
Michael Kruse01cb3792015-10-17 21:07:08 +00003247 // Check for PHI nodes in the region exit and skip them, if they will be
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003248 // modeled as PHI nodes.
Michael Kruse01cb3792015-10-17 21:07:08 +00003249 //
3250 // PHI nodes in the region exit that have more than two incoming edges need
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003251 // to be modeled as PHI-Nodes to correctly model the fact that depending on
3252 // the control flow a different value will be assigned to the PHI node. In
3253 // case this is the case, there is no need to create an additional normal
3254 // scalar dependence. Hence, bail out before we register an "out-of-region"
3255 // use for this definition.
Michael Kruse01cb3792015-10-17 21:07:08 +00003256 if (isa<PHINode>(UI) && UI->getParent() == R->getExit() &&
3257 !R->getExitingBlock())
3258 continue;
3259
Michael Kruse7bf39442015-09-10 12:46:52 +00003260 // Check whether or not the use is in the SCoP.
Tobias Grosserc73d8b02015-10-23 22:36:22 +00003261 if (!R->contains(UseParent)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003262 AnyCrossStmtUse = true;
3263 continue;
3264 }
3265
Tobias Grosserbaffa092015-10-24 20:55:27 +00003266 // Uses by PHI nodes in the entry node count as external uses in case the
3267 // use is through an incoming block that is itself not contained in the
3268 // region.
3269 if (R->getEntry() == UseParent) {
3270 if (auto *PHI = dyn_cast<PHINode>(UI)) {
3271 bool ExternalUse = false;
3272 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
3273 if (PHI->getIncomingValue(i) == Inst &&
3274 !R->contains(PHI->getIncomingBlock(i))) {
3275 ExternalUse = true;
3276 break;
3277 }
3278 }
3279
3280 if (ExternalUse) {
3281 AnyCrossStmtUse = true;
3282 continue;
3283 }
3284 }
3285 }
3286
Michael Kruse7bf39442015-09-10 12:46:52 +00003287 // If the instruction can be synthesized and the user is in the region
3288 // we do not need to add scalar dependences.
3289 if (canSynthesizeInst)
3290 continue;
3291
3292 // No need to translate these scalar dependences into polyhedral form,
3293 // because synthesizable scalars can be generated by the code generator.
3294 if (canSynthesize(UI, LI, SE, R))
3295 continue;
3296
3297 // Skip PHI nodes in the region as they handle their operands on their own.
3298 if (isa<PHINode>(UI))
3299 continue;
3300
3301 // Now U is used in another statement.
3302 AnyCrossStmtUse = true;
3303
3304 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00003305 // Use the def instruction as base address of the MemoryAccess, so that it
3306 // will become the name of the scalar access in the polyhedral form.
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003307 addScalarReadAccess(Inst, UI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003308 }
3309
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003310 if (ModelReadOnlyScalars && !isa<PHINode>(Inst)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003311 for (Value *Op : Inst->operands()) {
3312 if (canSynthesize(Op, LI, SE, R))
3313 continue;
3314
3315 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
3316 if (R->contains(OpInst))
3317 continue;
3318
3319 if (isa<Constant>(Op))
3320 continue;
3321
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003322 addScalarReadAccess(Op, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003323 }
3324 }
3325
3326 return AnyCrossStmtUse;
3327}
3328
3329extern MapInsnToMemAcc InsnToMemAcc;
3330
Michael Krusee2bccbb2015-09-18 19:59:43 +00003331void ScopInfo::buildMemoryAccess(
3332 Instruction *Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003333 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3334 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003335 unsigned Size;
3336 Type *SizeType;
3337 Value *Val;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003338 enum MemoryAccess::AccessType Type;
Michael Kruse7bf39442015-09-10 12:46:52 +00003339
3340 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
3341 SizeType = Load->getType();
3342 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003343 Type = MemoryAccess::READ;
Michael Kruse7bf39442015-09-10 12:46:52 +00003344 Val = Load;
3345 } else {
3346 StoreInst *Store = cast<StoreInst>(Inst);
3347 SizeType = Store->getValueOperand()->getType();
3348 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003349 Type = MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003350 Val = Store->getValueOperand();
3351 }
3352
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003353 auto Address = getPointerOperand(*Inst);
3354
3355 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003356 const SCEVUnknown *BasePointer =
3357 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3358
3359 assert(BasePointer && "Could not find base pointer");
3360 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
3361
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003362 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3363 auto NewAddress = Address;
3364 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3365 auto Src = BitCast->getOperand(0);
3366 auto SrcTy = Src->getType();
3367 auto DstTy = BitCast->getType();
3368 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3369 NewAddress = Src;
3370 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003371
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003372 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3373 std::vector<const SCEV *> Subscripts;
3374 std::vector<int> Sizes;
3375 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3376 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003377
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003378 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003379
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003380 bool AllAffineSubcripts = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003381 for (auto Subscript : Subscripts) {
3382 InvariantLoadsSetTy AccessILS;
3383 AllAffineSubcripts =
3384 isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS);
3385
3386 for (LoadInst *LInst : AccessILS)
3387 if (!ScopRIL.count(LInst))
3388 AllAffineSubcripts = false;
3389
3390 if (!AllAffineSubcripts)
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003391 break;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003392 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003393
3394 if (AllAffineSubcripts && Sizes.size() > 0) {
3395 for (auto V : Sizes)
3396 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3397 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003398 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003399 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003400
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003401 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3402 Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00003403 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003404 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003405 }
3406 }
3407
Michael Kruse7bf39442015-09-10 12:46:52 +00003408 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003409 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003410 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3411 AccItr->second.DelinearizedSubscripts,
3412 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003413 return;
3414 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003415
3416 // Check if the access depends on a loop contained in a non-affine subregion.
3417 bool isVariantInNonAffineLoop = false;
3418 if (BoxedLoops) {
3419 SetVector<const Loop *> Loops;
3420 findLoops(AccessFunction, Loops);
3421 for (const Loop *L : Loops)
3422 if (BoxedLoops->count(L))
3423 isVariantInNonAffineLoop = true;
3424 }
3425
Johannes Doerfert09e36972015-10-07 20:17:36 +00003426 InvariantLoadsSetTy AccessILS;
3427 bool IsAffine =
3428 !isVariantInNonAffineLoop &&
3429 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3430
3431 for (LoadInst *LInst : AccessILS)
3432 if (!ScopRIL.count(LInst))
3433 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003434
Michael Krusecaac2b62015-09-26 15:51:44 +00003435 // FIXME: Size of the number of bytes of an array element, not the number of
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003436 // elements as probably intended here.
Tobias Grossera43b6e92015-09-27 17:54:50 +00003437 const SCEV *SizeSCEV =
3438 SE->getConstant(TD->getIntPtrType(Inst->getContext()), Size);
Michael Kruse7bf39442015-09-10 12:46:52 +00003439
Michael Krusee2bccbb2015-09-18 19:59:43 +00003440 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3441 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003442
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003443 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, IsAffine,
3444 ArrayRef<const SCEV *>(AccessFunction),
3445 ArrayRef<const SCEV *>(SizeSCEV), Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003446}
3447
Michael Krused868b5d2015-09-10 15:25:24 +00003448void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003449
3450 if (SD->isNonAffineSubRegion(&SR, &R)) {
3451 for (BasicBlock *BB : SR.blocks())
3452 buildAccessFunctions(R, *BB, &SR);
3453 return;
3454 }
3455
3456 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3457 if (I->isSubRegion())
3458 buildAccessFunctions(R, *I->getNodeAs<Region>());
3459 else
3460 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
3461}
3462
Michael Krusecac948e2015-10-02 13:53:07 +00003463void ScopInfo::buildStmts(Region &SR) {
3464 Region *R = getRegion();
3465
3466 if (SD->isNonAffineSubRegion(&SR, R)) {
3467 scop->addScopStmt(nullptr, &SR);
3468 return;
3469 }
3470
3471 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3472 if (I->isSubRegion())
3473 buildStmts(*I->getNodeAs<Region>());
3474 else
3475 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
3476}
3477
Michael Krused868b5d2015-09-10 15:25:24 +00003478void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
3479 Region *NonAffineSubRegion,
3480 bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003481 Loop *L = LI->getLoopFor(&BB);
3482
3483 // The set of loops contained in non-affine subregions that are part of R.
3484 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3485
Johannes Doerfert09e36972015-10-07 20:17:36 +00003486 // The set of loads that are required to be invariant.
3487 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
3488
Michael Kruse7bf39442015-09-10 12:46:52 +00003489 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
3490 Instruction *Inst = I;
3491
3492 PHINode *PHI = dyn_cast<PHINode>(Inst);
3493 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003494 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003495
3496 // For the exit block we stop modeling after the last PHI node.
3497 if (!PHI && IsExitBlock)
3498 break;
3499
Johannes Doerfert09e36972015-10-07 20:17:36 +00003500 // TODO: At this point we only know that elements of ScopRIL have to be
3501 // invariant and will be hoisted for the SCoP to be processed. Though,
3502 // there might be other invariant accesses that will be hoisted and
3503 // that would allow to make a non-affine access affine.
Michael Kruse7bf39442015-09-10 12:46:52 +00003504 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
Johannes Doerfert09e36972015-10-07 20:17:36 +00003505 buildMemoryAccess(Inst, L, &R, BoxedLoops, ScopRIL);
Michael Kruse7bf39442015-09-10 12:46:52 +00003506
3507 if (isIgnoredIntrinsic(Inst))
3508 continue;
3509
Johannes Doerfert09e36972015-10-07 20:17:36 +00003510 // Do not build scalar dependences for required invariant loads as we will
3511 // hoist them later on anyway or drop the SCoP if we cannot.
3512 if (ScopRIL.count(dyn_cast<LoadInst>(Inst)))
3513 continue;
3514
Michael Kruse7bf39442015-09-10 12:46:52 +00003515 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00003516 if (!isa<StoreInst>(Inst))
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003517 addScalarWriteAccess(Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003518 }
3519 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003520}
Michael Kruse7bf39442015-09-10 12:46:52 +00003521
Michael Kruse2d0ece92015-09-24 11:41:21 +00003522void ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3523 MemoryAccess::AccessType Type,
3524 Value *BaseAddress, unsigned ElemBytes,
3525 bool Affine, Value *AccessValue,
3526 ArrayRef<const SCEV *> Subscripts,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003527 ArrayRef<const SCEV *> Sizes,
3528 MemoryAccess::AccessOrigin Origin) {
Michael Krusecac948e2015-10-02 13:53:07 +00003529 ScopStmt *Stmt = scop->getStmtForBasicBlock(BB);
3530
3531 // Do not create a memory access for anything not in the SCoP. It would be
3532 // ignored anyway.
3533 if (!Stmt)
3534 return;
3535
Michael Krusee2bccbb2015-09-18 19:59:43 +00003536 AccFuncSetType &AccList = AccFuncMap[BB];
3537 size_t Identifier = AccList.size();
Michael Kruse7bf39442015-09-10 12:46:52 +00003538
Michael Krusee2bccbb2015-09-18 19:59:43 +00003539 Value *BaseAddr = BaseAddress;
3540 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3541
3542 std::string IdName = "__polly_array_ref_" + std::to_string(Identifier);
3543 isl_id *Id = isl_id_alloc(ctx, IdName.c_str(), nullptr);
3544
Michael Krusecac948e2015-10-02 13:53:07 +00003545 bool isApproximated =
3546 Stmt->isRegionStmt() && (Stmt->getRegion()->getEntry() != BB);
3547 if (isApproximated && Type == MemoryAccess::MUST_WRITE)
3548 Type = MemoryAccess::MAY_WRITE;
3549
3550 AccList.emplace_back(Stmt, Inst, Id, Type, BaseAddress, ElemBytes, Affine,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003551 Subscripts, Sizes, AccessValue, Origin, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00003552 Stmt->addAccess(&AccList.back());
Michael Kruse7bf39442015-09-10 12:46:52 +00003553}
3554
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003555void ScopInfo::addExplicitAccess(
3556 Instruction *MemAccInst, MemoryAccess::AccessType Type, Value *BaseAddress,
3557 unsigned ElemBytes, bool IsAffine, ArrayRef<const SCEV *> Subscripts,
3558 ArrayRef<const SCEV *> Sizes, Value *AccessValue) {
3559 assert(isa<LoadInst>(MemAccInst) || isa<StoreInst>(MemAccInst));
3560 assert(isa<LoadInst>(MemAccInst) == (Type == MemoryAccess::READ));
3561 addMemoryAccess(MemAccInst->getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003562 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
3563 MemoryAccess::EXPLICIT);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003564}
3565void ScopInfo::addScalarWriteAccess(Instruction *Value) {
3566 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
3567 true, Value, ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003568 ArrayRef<const SCEV *>(), MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003569}
3570void ScopInfo::addScalarReadAccess(Value *Value, Instruction *User) {
3571 assert(!isa<PHINode>(User));
3572 addMemoryAccess(User->getParent(), User, MemoryAccess::READ, Value, 1, true,
3573 Value, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003574 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003575}
3576void ScopInfo::addScalarReadAccess(Value *Value, PHINode *User,
3577 BasicBlock *UserBB) {
3578 addMemoryAccess(UserBB, User, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003579 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3580 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003581}
3582void ScopInfo::addPHIWriteAccess(PHINode *PHI, BasicBlock *IncomingBlock,
3583 Value *IncomingValue, bool IsExitBlock) {
3584 addMemoryAccess(IncomingBlock, IncomingBlock->getTerminator(),
3585 MemoryAccess::MUST_WRITE, PHI, 1, true, IncomingValue,
3586 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003587 IsExitBlock ? MemoryAccess::SCALAR : MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003588}
3589void ScopInfo::addPHIReadAccess(PHINode *PHI) {
3590 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003591 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3592 MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003593}
3594
Michael Kruse76e924d2015-09-30 09:16:07 +00003595void ScopInfo::buildScop(Region &R, DominatorTree &DT) {
Michael Kruse9d080092015-09-11 21:41:48 +00003596 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003597 scop = new Scop(R, AccFuncMap, *SD, *SE, DT, *LI, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00003598
Michael Krusecac948e2015-10-02 13:53:07 +00003599 buildStmts(R);
Michael Kruse7bf39442015-09-10 12:46:52 +00003600 buildAccessFunctions(R, R);
3601
3602 // In case the region does not have an exiting block we will later (during
3603 // code generation) split the exit block. This will move potential PHI nodes
3604 // from the current exit block into the new region exiting block. Hence, PHI
3605 // nodes that are at this point not part of the region will be.
3606 // To handle these PHI nodes later we will now model their operands as scalar
3607 // accesses. Note that we do not model anything in the exit block if we have
3608 // an exiting block in the region, as there will not be any splitting later.
3609 if (!R.getExitingBlock())
3610 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
3611
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003612 scop->init(*AA);
Michael Kruse7bf39442015-09-10 12:46:52 +00003613}
3614
Michael Krused868b5d2015-09-10 15:25:24 +00003615void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00003616 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00003617 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00003618 return;
3619 }
3620
Michael Kruse9d080092015-09-11 21:41:48 +00003621 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00003622}
3623
Michael Krused868b5d2015-09-10 15:25:24 +00003624void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00003625 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00003626 if (scop) {
3627 delete scop;
3628 scop = 0;
3629 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003630}
3631
3632//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00003633ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00003634 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00003635 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00003636}
3637
3638ScopInfo::~ScopInfo() {
3639 clear();
3640 isl_ctx_free(ctx);
3641}
3642
Tobias Grosser75805372011-04-29 06:27:02 +00003643void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00003644 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00003645 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00003646 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00003647 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
3648 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003649 AU.addRequired<AAResultsWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00003650 AU.setPreservesAll();
3651}
3652
3653bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00003654 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00003655
Michael Krused868b5d2015-09-10 15:25:24 +00003656 if (!SD->isMaxRegionInScop(*R))
3657 return false;
3658
3659 Function *F = R->getEntry()->getParent();
3660 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3661 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3662 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3663 TD = &F->getParent()->getDataLayout();
3664 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Krused868b5d2015-09-10 15:25:24 +00003665
Michael Kruse76e924d2015-09-30 09:16:07 +00003666 buildScop(*R, DT);
Tobias Grosser75805372011-04-29 06:27:02 +00003667
Tobias Grosserd6a50b32015-05-30 06:26:21 +00003668 DEBUG(scop->print(dbgs()));
3669
Michael Kruseafe06702015-10-02 16:33:27 +00003670 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003671 delete scop;
3672 scop = nullptr;
3673 return false;
3674 }
3675
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003676 // Statistics.
3677 ++ScopFound;
3678 if (scop->getMaxLoopDepth() > 0)
3679 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00003680 return false;
3681}
3682
3683char ScopInfo::ID = 0;
3684
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003685Pass *polly::createScopInfoPass() { return new ScopInfo(); }
3686
Tobias Grosser73600b82011-10-08 00:30:40 +00003687INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
3688 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003689 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003690INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00003691INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00003692INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00003693INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003694INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003695INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00003696INITIALIZE_PASS_END(ScopInfo, "polly-scops",
3697 "Polly - Create polyhedral description of Scops", false,
3698 false)