blob: 90d08fec117a4c1f1c9a714b4f3eeb1b5e60e2ca [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
176void ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
177#ifndef NDEBUG
178 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
179 int ExtraDimsNew = NewSizes.size() - SharedDims;
180 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
181 for (int i = 0; i < SharedDims; i++) {
182 assert(NewSizes[i + ExtraDimsNew] == DimensionSizes[i + ExtraDimsOld] &&
183 "Array update with non-matching dimension sizes");
184 }
185#endif
186
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 }
197}
198
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000199ScopArrayInfo::~ScopArrayInfo() {
200 isl_id_free(Id);
201 for (isl_pw_aff *Size : DimensionSizesPw)
202 isl_pw_aff_free(Size);
203}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000204
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000205std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
206
207int ScopArrayInfo::getElemSizeInBytes() const {
208 return ElementType->getPrimitiveSizeInBits() / 8;
209}
210
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000211isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
212
213void ScopArrayInfo::dump() const { print(errs()); }
214
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000215void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000216 OS.indent(8) << *getElementType() << " " << getName() << "[*]";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000217 for (unsigned u = 0; u < getNumberOfDimensions(); u++) {
218 OS << "[";
219
220 if (SizeAsPwAff)
221 OS << " " << DimensionSizesPw[u] << " ";
222 else
223 OS << *DimensionSizes[u];
224
225 OS << "]";
226 }
227
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000228 if (BasePtrOriginSAI)
229 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
230
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000231 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000232}
233
234const ScopArrayInfo *
235ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
236 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
237 assert(Id && "Output dimension didn't have an ID");
238 return getFromId(Id);
239}
240
241const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
242 void *User = isl_id_get_user(Id);
243 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
244 isl_id_free(Id);
245 return SAI;
246}
247
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000248void MemoryAccess::updateDimensionality() {
249 auto ArraySpace = getScopArrayInfo()->getSpace();
250 auto AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
251
252 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
253 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
254 auto DimsMissing = DimsArray - DimsAccess;
255
256 auto Map = isl_map_from_domain_and_range(isl_set_universe(AccessSpace),
257 isl_set_universe(ArraySpace));
258
259 for (unsigned i = 0; i < DimsMissing; i++)
260 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
261
262 for (unsigned i = DimsMissing; i < DimsArray; i++)
263 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
264
265 AccessRelation = isl_map_apply_range(AccessRelation, Map);
266}
267
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000268const std::string
269MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
270 switch (RT) {
271 case MemoryAccess::RT_NONE:
272 llvm_unreachable("Requested a reduction operator string for a memory "
273 "access which isn't a reduction");
274 case MemoryAccess::RT_ADD:
275 return "+";
276 case MemoryAccess::RT_MUL:
277 return "*";
278 case MemoryAccess::RT_BOR:
279 return "|";
280 case MemoryAccess::RT_BXOR:
281 return "^";
282 case MemoryAccess::RT_BAND:
283 return "&";
284 }
285 llvm_unreachable("Unknown reduction type");
286 return "";
287}
288
Johannes Doerfertf6183392014-07-01 20:52:51 +0000289/// @brief Return the reduction type for a given binary operator
290static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
291 const Instruction *Load) {
292 if (!BinOp)
293 return MemoryAccess::RT_NONE;
294 switch (BinOp->getOpcode()) {
295 case Instruction::FAdd:
296 if (!BinOp->hasUnsafeAlgebra())
297 return MemoryAccess::RT_NONE;
298 // Fall through
299 case Instruction::Add:
300 return MemoryAccess::RT_ADD;
301 case Instruction::Or:
302 return MemoryAccess::RT_BOR;
303 case Instruction::Xor:
304 return MemoryAccess::RT_BXOR;
305 case Instruction::And:
306 return MemoryAccess::RT_BAND;
307 case Instruction::FMul:
308 if (!BinOp->hasUnsafeAlgebra())
309 return MemoryAccess::RT_NONE;
310 // Fall through
311 case Instruction::Mul:
312 if (DisableMultiplicativeReductions)
313 return MemoryAccess::RT_NONE;
314 return MemoryAccess::RT_MUL;
315 default:
316 return MemoryAccess::RT_NONE;
317 }
318}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000319
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000320/// @brief Derive the individual index expressions from a GEP instruction
321///
322/// This function optimistically assumes the GEP references into a fixed size
323/// array. If this is actually true, this function returns a list of array
324/// subscript expressions as SCEV as well as a list of integers describing
325/// the size of the individual array dimensions. Both lists have either equal
326/// length of the size list is one element shorter in case there is no known
327/// size available for the outermost array dimension.
328///
329/// @param GEP The GetElementPtr instruction to analyze.
330///
331/// @return A tuple with the subscript expressions and the dimension sizes.
332static std::tuple<std::vector<const SCEV *>, std::vector<int>>
333getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
334 std::vector<const SCEV *> Subscripts;
335 std::vector<int> Sizes;
336
337 Type *Ty = GEP->getPointerOperandType();
338
339 bool DroppedFirstDim = false;
340
Michael Kruse26ed65e2015-09-24 17:32:49 +0000341 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000342
343 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
344
345 if (i == 1) {
346 if (auto PtrTy = dyn_cast<PointerType>(Ty)) {
347 Ty = PtrTy->getElementType();
348 } else if (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
349 Ty = ArrayTy->getElementType();
350 } else {
351 Subscripts.clear();
352 Sizes.clear();
353 break;
354 }
355 if (auto Const = dyn_cast<SCEVConstant>(Expr))
356 if (Const->getValue()->isZero()) {
357 DroppedFirstDim = true;
358 continue;
359 }
360 Subscripts.push_back(Expr);
361 continue;
362 }
363
364 auto ArrayTy = dyn_cast<ArrayType>(Ty);
365 if (!ArrayTy) {
366 Subscripts.clear();
367 Sizes.clear();
368 break;
369 }
370
371 Subscripts.push_back(Expr);
372 if (!(DroppedFirstDim && i == 2))
373 Sizes.push_back(ArrayTy->getNumElements());
374
375 Ty = ArrayTy->getElementType();
376 }
377
378 return std::make_tuple(Subscripts, Sizes);
379}
380
Tobias Grosser75805372011-04-29 06:27:02 +0000381MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000382 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000383 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000384 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000385}
386
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000387const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
388 isl_id *ArrayId = getArrayId();
389 void *User = isl_id_get_user(ArrayId);
390 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
391 isl_id_free(ArrayId);
392 return SAI;
393}
394
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000395__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000396 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
397}
398
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000399__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
400 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000401 isl_map *Schedule, *ScheduledAccRel;
402 isl_union_set *UDomain;
403
404 UDomain = isl_union_set_from_set(getStatement()->getDomain());
405 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
406 Schedule = isl_map_from_union_map(USchedule);
407 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
408 return isl_pw_multi_aff_from_map(ScheduledAccRel);
409}
410
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000411__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000412 return isl_map_copy(AccessRelation);
413}
414
Johannes Doerferta99130f2014-10-13 12:58:03 +0000415std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000416 return stringFromIslObj(AccessRelation);
417}
418
Johannes Doerferta99130f2014-10-13 12:58:03 +0000419__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000420 return isl_map_get_space(AccessRelation);
421}
422
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000423__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000424 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000425}
426
Tobias Grosser6f730082015-09-05 07:46:47 +0000427std::string MemoryAccess::getNewAccessRelationStr() const {
428 return stringFromIslObj(NewAccessRelation);
429}
430
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000431__isl_give isl_basic_map *
432MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000433 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000434 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000435
Tobias Grosser084d8f72012-05-29 09:29:44 +0000436 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000437 isl_basic_set_universe(Statement->getDomainSpace()),
438 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000439}
440
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000441// Formalize no out-of-bound access assumption
442//
443// When delinearizing array accesses we optimistically assume that the
444// delinearized accesses do not access out of bound locations (the subscript
445// expression of each array evaluates for each statement instance that is
446// executed to a value that is larger than zero and strictly smaller than the
447// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000448// dimension for which we do not need to assume any upper bound. At this point
449// we formalize this assumption to ensure that at code generation time the
450// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000451//
452// To find the set of constraints necessary to avoid out of bound accesses, we
453// first build the set of data locations that are not within array bounds. We
454// then apply the reverse access relation to obtain the set of iterations that
455// may contain invalid accesses and reduce this set of iterations to the ones
456// that are actually executed by intersecting them with the domain of the
457// statement. If we now project out all loop dimensions, we obtain a set of
458// parameters that may cause statement instances to be executed that may
459// possibly yield out of bound memory accesses. The complement of these
460// constraints is the set of constraints that needs to be assumed to ensure such
461// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000462void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000463 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000464 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Michael Krusee2bccbb2015-09-18 19:59:43 +0000465 for (int i = 1, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000466 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
467 isl_pw_aff *Var =
468 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
469 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
470
471 isl_set *DimOutside;
472
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000473 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Michael Krusee2bccbb2015-09-18 19:59:43 +0000474 isl_pw_aff *SizeE = Statement->getPwAff(Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000475
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000476 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
477 Statement->getNumIterators());
478 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
479 isl_space_dim(Space, isl_dim_set));
480 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
481 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000482
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000483 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000484
485 Outside = isl_set_union(Outside, DimOutside);
486 }
487
488 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
489 Outside = isl_set_intersect(Outside, Statement->getDomain());
490 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000491
492 // Remove divs to avoid the construction of overly complicated assumptions.
493 // Doing so increases the set of parameter combinations that are assumed to
494 // not appear. This is always save, but may make the resulting run-time check
495 // bail out more often than strictly necessary.
496 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000497 Outside = isl_set_complement(Outside);
498 Statement->getParent()->addAssumption(Outside);
499 isl_space_free(Space);
500}
501
Johannes Doerferte7044942015-02-24 11:58:30 +0000502void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
503 ScalarEvolution *SE = Statement->getParent()->getSE();
504
505 Value *Ptr = getPointerOperand(*getAccessInstruction());
506 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
507 return;
508
509 auto *PtrSCEV = SE->getSCEV(Ptr);
510 if (isa<SCEVCouldNotCompute>(PtrSCEV))
511 return;
512
513 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
514 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
515 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
516
517 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
518 if (Range.isFullSet())
519 return;
520
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000521 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000522 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000523 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
524 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
525
526 auto Min = LB.sdiv(APInt(BW, ElementSize));
527 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000528
529 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
530 AccessRange =
531 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
532 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
533}
534
Michael Krusee2bccbb2015-09-18 19:59:43 +0000535__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000536 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000537 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000538
539 for (int i = Size - 2; i >= 0; --i) {
540 isl_space *Space;
541 isl_map *MapOne, *MapTwo;
Michael Krusee2bccbb2015-09-18 19:59:43 +0000542 isl_pw_aff *DimSize = Statement->getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000543
544 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
545 isl_pw_aff_free(DimSize);
546 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
547
548 Space = isl_map_get_space(AccessRelation);
549 Space = isl_space_map_from_set(isl_space_range(Space));
550 Space = isl_space_align_params(Space, SpaceSize);
551
552 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
553 isl_id_free(ParamId);
554
555 MapOne = isl_map_universe(isl_space_copy(Space));
556 for (int j = 0; j < Size; ++j)
557 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
558 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
559
560 MapTwo = isl_map_universe(isl_space_copy(Space));
561 for (int j = 0; j < Size; ++j)
562 if (j < i || j > i + 1)
563 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
564
565 isl_local_space *LS = isl_local_space_from_space(Space);
566 isl_constraint *C;
567 C = isl_equality_alloc(isl_local_space_copy(LS));
568 C = isl_constraint_set_constant_si(C, -1);
569 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
570 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
571 MapTwo = isl_map_add_constraint(MapTwo, C);
572 C = isl_equality_alloc(LS);
573 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
574 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
575 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
576 MapTwo = isl_map_add_constraint(MapTwo, C);
577 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
578
579 MapOne = isl_map_union(MapOne, MapTwo);
580 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
581 }
582 return AccessRelation;
583}
584
Michael Krusee2bccbb2015-09-18 19:59:43 +0000585void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
586 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000587
Michael Krusee2bccbb2015-09-18 19:59:43 +0000588 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000589 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000590
Michael Krusee2bccbb2015-09-18 19:59:43 +0000591 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000592 // We overapproximate non-affine accesses with a possible access to the
593 // whole array. For read accesses it does not make a difference, if an
594 // access must or may happen. However, for write accesses it is important to
595 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000596 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000597 AccessRelation =
598 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000599
Michael Krusee2bccbb2015-09-18 19:59:43 +0000600 computeBoundsOnAccessRelation(getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000601 return;
602 }
603
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000604 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000605 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000606
Michael Krusee2bccbb2015-09-18 19:59:43 +0000607 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
608 isl_pw_aff *Affine = Statement->getPwAff(Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000609
Sebastian Pop422e33f2014-06-03 18:16:31 +0000610 if (Size == 1) {
611 // For the non delinearized arrays, divide the access function of the last
612 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000613 //
614 // A stride one array access in C expressed as A[i] is expressed in
615 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
616 // two subsequent values of 'i' index two values that are stored next to
617 // each other in memory. By this division we make this characteristic
618 // obvious again.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000619 isl_val *v = isl_val_int_from_si(Ctx, getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000620 Affine = isl_pw_aff_scale_down_val(Affine, v);
621 }
622
623 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
624
Tobias Grosser79baa212014-04-10 08:38:02 +0000625 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000626 }
627
Michael Krusee2bccbb2015-09-18 19:59:43 +0000628 if (Sizes.size() > 1 && !isa<SCEVConstant>(Sizes[0]))
629 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000630
Tobias Grosser79baa212014-04-10 08:38:02 +0000631 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000632 AccessRelation = isl_map_set_tuple_id(
633 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000634 AccessRelation =
635 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
636
Michael Krusee2bccbb2015-09-18 19:59:43 +0000637 assumeNoOutOfBound();
Tobias Grosseraa660a92015-03-30 00:07:50 +0000638 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000639 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000640}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000641
Michael Krusecac948e2015-10-02 13:53:07 +0000642MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
643 __isl_take isl_id *Id, AccessType Type,
644 Value *BaseAddress, unsigned ElemBytes, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000645 ArrayRef<const SCEV *> Subscripts,
646 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Michael Kruse8d0b7342015-09-25 21:21:00 +0000647 AccessOrigin Origin, StringRef BaseName)
Michael Krusecac948e2015-10-02 13:53:07 +0000648 : Id(Id), Origin(Origin), AccType(Type), RedType(RT_NONE), Statement(Stmt),
649 BaseAddr(BaseAddress), BaseName(BaseName), ElemBytes(ElemBytes),
650 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
651 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000652 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
653 NewAccessRelation(nullptr) {}
654
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000655void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000656 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000657 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000658}
659
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000660const std::string MemoryAccess::getReductionOperatorStr() const {
661 return MemoryAccess::getReductionOperatorStr(getReductionType());
662}
663
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000664__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
665
Johannes Doerfertf6183392014-07-01 20:52:51 +0000666raw_ostream &polly::operator<<(raw_ostream &OS,
667 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000668 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000669 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000670 else
671 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000672 return OS;
673}
674
Tobias Grosser75805372011-04-29 06:27:02 +0000675void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000676 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000677 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000678 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000679 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000680 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000681 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000682 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000683 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000684 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000685 break;
686 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000687 OS << "[Reduction Type: " << getReductionType() << "] ";
Michael Kruse8d0b7342015-09-25 21:21:00 +0000688 OS << "[Scalar: " << isImplicit() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000689 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000690 if (hasNewAccessRelation())
691 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000692}
693
Tobias Grosser74394f02013-01-14 22:40:23 +0000694void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000695
696// Create a map in the size of the provided set domain, that maps from the
697// one element of the provided set domain to another element of the provided
698// set domain.
699// The mapping is limited to all points that are equal in all but the last
700// dimension and for which the last dimension of the input is strict smaller
701// than the last dimension of the output.
702//
703// getEqualAndLarger(set[i0, i1, ..., iX]):
704//
705// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
706// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
707//
Tobias Grosserf5338802011-10-06 00:03:35 +0000708static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000709 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000710 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000711 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000712
713 // Set all but the last dimension to be equal for the input and output
714 //
715 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
716 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000717 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000718 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000719
720 // Set the last dimension of the input to be strict smaller than the
721 // last dimension of the output.
722 //
723 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000724 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
725 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000726 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000727}
728
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000729__isl_give isl_set *
730MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000731 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000732 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000733 isl_space *Space = isl_space_range(isl_map_get_space(S));
734 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000735
Sebastian Popa00a0292012-12-18 07:46:06 +0000736 S = isl_map_reverse(S);
737 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000738
Sebastian Popa00a0292012-12-18 07:46:06 +0000739 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
740 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
741 NextScatt = isl_map_apply_domain(NextScatt, S);
742 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000743
Sebastian Popa00a0292012-12-18 07:46:06 +0000744 isl_set *Deltas = isl_map_deltas(NextScatt);
745 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000746}
747
Sebastian Popa00a0292012-12-18 07:46:06 +0000748bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000749 int StrideWidth) const {
750 isl_set *Stride, *StrideX;
751 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000752
Sebastian Popa00a0292012-12-18 07:46:06 +0000753 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000754 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000755 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
756 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
757 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
758 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000759 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000760
Tobias Grosser28dd4862012-01-24 16:42:16 +0000761 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000762 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000763
Tobias Grosser28dd4862012-01-24 16:42:16 +0000764 return IsStrideX;
765}
766
Sebastian Popa00a0292012-12-18 07:46:06 +0000767bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
768 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000769}
770
Sebastian Popa00a0292012-12-18 07:46:06 +0000771bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
772 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000773}
774
Tobias Grosser166c4222015-09-05 07:46:40 +0000775void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
776 isl_map_free(NewAccessRelation);
777 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000778}
Tobias Grosser75805372011-04-29 06:27:02 +0000779
780//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000781
Tobias Grosser808cd692015-07-14 09:33:13 +0000782isl_map *ScopStmt::getSchedule() const {
783 isl_set *Domain = getDomain();
784 if (isl_set_is_empty(Domain)) {
785 isl_set_free(Domain);
786 return isl_map_from_aff(
787 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
788 }
789 auto *Schedule = getParent()->getSchedule();
790 Schedule = isl_union_map_intersect_domain(
791 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
792 if (isl_union_map_is_empty(Schedule)) {
793 isl_set_free(Domain);
794 isl_union_map_free(Schedule);
795 return isl_map_from_aff(
796 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
797 }
798 auto *M = isl_map_from_union_map(Schedule);
799 M = isl_map_coalesce(M);
800 M = isl_map_gist_domain(M, Domain);
801 M = isl_map_coalesce(M);
802 return M;
803}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000804
Johannes Doerfert574182d2015-08-12 10:19:50 +0000805__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000806 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
807 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000808}
809
Tobias Grosser37eb4222014-02-20 21:43:54 +0000810void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
811 assert(isl_set_is_subset(NewDomain, Domain) &&
812 "New domain is not a subset of old domain!");
813 isl_set_free(Domain);
814 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000815}
816
Michael Krusecac948e2015-10-02 13:53:07 +0000817void ScopStmt::buildAccessRelations() {
818 for (MemoryAccess *Access : MemAccs) {
819 Type *ElementType = Access->getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000820
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000821 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Michael Krusecac948e2015-10-02 13:53:07 +0000822 Access->getBaseAddr(), ElementType, Access->Sizes, Access->isPHI());
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000823
Michael Krusecac948e2015-10-02 13:53:07 +0000824 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +0000825 }
826}
827
Michael Krusecac948e2015-10-02 13:53:07 +0000828void ScopStmt::addAccess(MemoryAccess *Access) {
829 Instruction *AccessInst = Access->getAccessInstruction();
830
831 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
832 if (!MAL)
833 MAL = new MemoryAccessList();
834 MAL->emplace_front(Access);
835 MemAccs.push_back(MAL->front());
836}
837
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000838void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000839 for (MemoryAccess *MA : *this)
840 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000841
842 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000843}
844
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000845/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
846static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
847 void *User) {
848 isl_set **BoundedParts = static_cast<isl_set **>(User);
849 if (isl_basic_set_is_bounded(BSet))
850 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
851 else
852 isl_basic_set_free(BSet);
853 return isl_stat_ok;
854}
855
856/// @brief Return the bounded parts of @p S.
857static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
858 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
859 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
860 isl_set_free(S);
861 return BoundedParts;
862}
863
864/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
865///
866/// @returns A separation of @p S into first an unbounded then a bounded subset,
867/// both with regards to the dimension @p Dim.
868static std::pair<__isl_give isl_set *, __isl_give isl_set *>
869partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
870
871 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000872 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000873
874 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000875 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000876
877 // Remove dimensions that are greater than Dim as they are not interesting.
878 assert(NumDimsS >= Dim + 1);
879 OnlyDimS =
880 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
881
882 // Create artificial parametric upper bounds for dimensions smaller than Dim
883 // as we are not interested in them.
884 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
885 for (unsigned u = 0; u < Dim; u++) {
886 isl_constraint *C = isl_inequality_alloc(
887 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
888 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
889 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
890 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
891 }
892
893 // Collect all bounded parts of OnlyDimS.
894 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
895
896 // Create the dimensions greater than Dim again.
897 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
898 NumDimsS - Dim - 1);
899
900 // Remove the artificial upper bound parameters again.
901 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
902
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000903 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000904 return std::make_pair(UnboundedParts, BoundedParts);
905}
906
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000907/// @brief Set the dimension Ids from @p From in @p To.
908static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
909 __isl_take isl_set *To) {
910 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
911 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
912 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
913 }
914 return To;
915}
916
917/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000918static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000919 __isl_take isl_pw_aff *L,
920 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +0000921 switch (Pred) {
922 case ICmpInst::ICMP_EQ:
923 return isl_pw_aff_eq_set(L, R);
924 case ICmpInst::ICMP_NE:
925 return isl_pw_aff_ne_set(L, R);
926 case ICmpInst::ICMP_SLT:
927 return isl_pw_aff_lt_set(L, R);
928 case ICmpInst::ICMP_SLE:
929 return isl_pw_aff_le_set(L, R);
930 case ICmpInst::ICMP_SGT:
931 return isl_pw_aff_gt_set(L, R);
932 case ICmpInst::ICMP_SGE:
933 return isl_pw_aff_ge_set(L, R);
934 case ICmpInst::ICMP_ULT:
935 return isl_pw_aff_lt_set(L, R);
936 case ICmpInst::ICMP_UGT:
937 return isl_pw_aff_gt_set(L, R);
938 case ICmpInst::ICMP_ULE:
939 return isl_pw_aff_le_set(L, R);
940 case ICmpInst::ICMP_UGE:
941 return isl_pw_aff_ge_set(L, R);
942 default:
943 llvm_unreachable("Non integer predicate not supported");
944 }
945}
946
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000947/// @brief Create the conditions under which @p L @p Pred @p R is true.
948///
949/// Helper function that will make sure the dimensions of the result have the
950/// same isl_id's as the @p Domain.
951static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
952 __isl_take isl_pw_aff *L,
953 __isl_take isl_pw_aff *R,
954 __isl_keep isl_set *Domain) {
955 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
956 return setDimensionIds(Domain, ConsequenceCondSet);
957}
958
959/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000960///
961/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000962/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
963/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000964static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000965buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +0000966 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
967
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000968 Value *Condition = getConditionFromTerminator(SI);
969 assert(Condition && "No condition for switch");
970
971 ScalarEvolution &SE = *S.getSE();
972 BasicBlock *BB = SI->getParent();
973 isl_pw_aff *LHS, *RHS;
974 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
975
976 unsigned NumSuccessors = SI->getNumSuccessors();
977 ConditionSets.resize(NumSuccessors);
978 for (auto &Case : SI->cases()) {
979 unsigned Idx = Case.getSuccessorIndex();
980 ConstantInt *CaseValue = Case.getCaseValue();
981
982 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
983 isl_set *CaseConditionSet =
984 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
985 ConditionSets[Idx] = isl_set_coalesce(
986 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
987 }
988
989 assert(ConditionSets[0] == nullptr && "Default condition set was set");
990 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
991 for (unsigned u = 2; u < NumSuccessors; u++)
992 ConditionSetUnion =
993 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
994 ConditionSets[0] = setDimensionIds(
995 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
996
997 S.markAsOptimized();
998 isl_pw_aff_free(LHS);
999}
1000
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001001/// @brief Build the conditions sets for the branch condition @p Condition in
1002/// the @p Domain.
1003///
1004/// This will fill @p ConditionSets with the conditions under which control
1005/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1006/// have as many elements as @p TI has successors.
1007static void
1008buildConditionSets(Scop &S, Value *Condition, TerminatorInst *TI, Loop *L,
1009 __isl_keep isl_set *Domain,
1010 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1011
1012 isl_set *ConsequenceCondSet = nullptr;
1013 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1014 if (CCond->isZero())
1015 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1016 else
1017 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1018 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1019 auto Opcode = BinOp->getOpcode();
1020 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1021
1022 buildConditionSets(S, BinOp->getOperand(0), TI, L, Domain, ConditionSets);
1023 buildConditionSets(S, BinOp->getOperand(1), TI, L, Domain, ConditionSets);
1024
1025 isl_set_free(ConditionSets.pop_back_val());
1026 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1027 isl_set_free(ConditionSets.pop_back_val());
1028 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1029
1030 if (Opcode == Instruction::And)
1031 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1032 else
1033 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1034 } else {
1035 auto *ICond = dyn_cast<ICmpInst>(Condition);
1036 assert(ICond &&
1037 "Condition of exiting branch was neither constant nor ICmp!");
1038
1039 ScalarEvolution &SE = *S.getSE();
1040 BasicBlock *BB = TI->getParent();
1041 isl_pw_aff *LHS, *RHS;
1042 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1043 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
1044 ConsequenceCondSet =
1045 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1046 }
1047
1048 assert(ConsequenceCondSet);
1049 isl_set *AlternativeCondSet =
1050 isl_set_complement(isl_set_copy(ConsequenceCondSet));
1051
1052 ConditionSets.push_back(isl_set_coalesce(
1053 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
1054 ConditionSets.push_back(isl_set_coalesce(
1055 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
1056}
1057
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001058/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1059///
1060/// This will fill @p ConditionSets with the conditions under which control
1061/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1062/// have as many elements as @p TI has successors.
1063static void
1064buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1065 __isl_keep isl_set *Domain,
1066 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1067
1068 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1069 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1070
1071 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1072
1073 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001074 ConditionSets.push_back(isl_set_copy(Domain));
1075 return;
1076 }
1077
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001078 Value *Condition = getConditionFromTerminator(TI);
1079 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001080
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001081 return buildConditionSets(S, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001082}
1083
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001084void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +00001085 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +00001086
Tobias Grosser084d8f72012-05-29 09:29:44 +00001087 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1088
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001089 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001090 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001091}
1092
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001093void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001094 isl_ctx *Ctx = Parent.getIslCtx();
1095 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1096 Type *Ty = GEP->getPointerOperandType();
1097 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001098 ScopDetection &SD = Parent.getSD();
1099
1100 // The set of loads that are required to be invariant.
1101 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001102
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001103 std::vector<const SCEV *> Subscripts;
1104 std::vector<int> Sizes;
1105
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001106 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001107
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001108 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001109 Ty = PtrTy->getElementType();
1110 }
1111
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001112 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001113
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001114 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001115
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001116 for (size_t i = 0; i < Sizes.size(); i++) {
1117 auto Expr = Subscripts[i + IndexOffset];
1118 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001119
Johannes Doerfert09e36972015-10-07 20:17:36 +00001120 InvariantLoadsSetTy AccessILS;
1121 if (!isAffineExpr(&Parent.getRegion(), Expr, SE, nullptr, &AccessILS))
1122 continue;
1123
1124 bool NonAffine = false;
1125 for (LoadInst *LInst : AccessILS)
1126 if (!ScopRIL.count(LInst))
1127 NonAffine = true;
1128
1129 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001130 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001131
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001132 isl_pw_aff *AccessOffset = getPwAff(Expr);
1133 AccessOffset =
1134 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001135
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001136 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1137 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001138
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001139 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1140 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1141 OutOfBound = isl_set_params(OutOfBound);
1142 isl_set *InBound = isl_set_complement(OutOfBound);
1143 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001144
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001145 // A => B == !A or B
1146 isl_set *InBoundIfExecuted =
1147 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001148
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001149 Parent.addAssumption(InBoundIfExecuted);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001150 }
1151
1152 isl_local_space_free(LSpace);
1153}
1154
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001155void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1156 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001157 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1158 deriveAssumptionsFromGEP(GEP);
1159}
1160
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001161void ScopStmt::collectSurroundingLoops() {
1162 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1163 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1164 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1165 isl_id_free(DimId);
1166 }
1167}
1168
Michael Kruse9d080092015-09-11 21:41:48 +00001169ScopStmt::ScopStmt(Scop &parent, Region &R)
Michael Krusecac948e2015-10-02 13:53:07 +00001170 : Parent(parent), Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001171
Tobias Grosser16c44032015-07-09 07:31:45 +00001172 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001173}
1174
Michael Kruse9d080092015-09-11 21:41:48 +00001175ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Michael Krusecac948e2015-10-02 13:53:07 +00001176 : Parent(parent), Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001177
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001178 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001179}
1180
1181void ScopStmt::init() {
1182 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001183
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001184 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001185 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001186 buildAccessRelations();
1187
1188 if (BB) {
1189 deriveAssumptions(BB);
1190 } else {
1191 for (BasicBlock *Block : R->blocks()) {
1192 deriveAssumptions(Block);
1193 }
1194 }
1195
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001196 if (DetectReductions)
1197 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001198}
1199
Johannes Doerferte58a0122014-06-27 20:31:28 +00001200/// @brief Collect loads which might form a reduction chain with @p StoreMA
1201///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001202/// Check if the stored value for @p StoreMA is a binary operator with one or
1203/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001204/// used only once (by @p StoreMA) and its load operands are also used only
1205/// once, we have found a possible reduction chain. It starts at an operand
1206/// load and includes the binary operator and @p StoreMA.
1207///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001208/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001209/// escape this block or into any other store except @p StoreMA.
1210void ScopStmt::collectCandiateReductionLoads(
1211 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1212 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1213 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001214 return;
1215
1216 // Skip if there is not one binary operator between the load and the store
1217 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001218 if (!BinOp)
1219 return;
1220
1221 // Skip if the binary operators has multiple uses
1222 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001223 return;
1224
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001225 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001226 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1227 return;
1228
Johannes Doerfert9890a052014-07-01 00:32:29 +00001229 // Skip if the binary operator is outside the current SCoP
1230 if (BinOp->getParent() != Store->getParent())
1231 return;
1232
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001233 // Skip if it is a multiplicative reduction and we disabled them
1234 if (DisableMultiplicativeReductions &&
1235 (BinOp->getOpcode() == Instruction::Mul ||
1236 BinOp->getOpcode() == Instruction::FMul))
1237 return;
1238
Johannes Doerferte58a0122014-06-27 20:31:28 +00001239 // Check the binary operator operands for a candidate load
1240 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1241 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1242 if (!PossibleLoad0 && !PossibleLoad1)
1243 return;
1244
1245 // A load is only a candidate if it cannot escape (thus has only this use)
1246 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001247 if (PossibleLoad0->getParent() == Store->getParent())
1248 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001249 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001250 if (PossibleLoad1->getParent() == Store->getParent())
1251 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001252}
1253
1254/// @brief Check for reductions in this ScopStmt
1255///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001256/// Iterate over all store memory accesses and check for valid binary reduction
1257/// like chains. For all candidates we check if they have the same base address
1258/// and there are no other accesses which overlap with them. The base address
1259/// check rules out impossible reductions candidates early. The overlap check,
1260/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001261/// guarantees that none of the intermediate results will escape during
1262/// execution of the loop nest. We basically check here that no other memory
1263/// access can access the same memory as the potential reduction.
1264void ScopStmt::checkForReductions() {
1265 SmallVector<MemoryAccess *, 2> Loads;
1266 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1267
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001268 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001269 // stores and collecting possible reduction loads.
1270 for (MemoryAccess *StoreMA : MemAccs) {
1271 if (StoreMA->isRead())
1272 continue;
1273
1274 Loads.clear();
1275 collectCandiateReductionLoads(StoreMA, Loads);
1276 for (MemoryAccess *LoadMA : Loads)
1277 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1278 }
1279
1280 // Then check each possible candidate pair.
1281 for (const auto &CandidatePair : Candidates) {
1282 bool Valid = true;
1283 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1284 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1285
1286 // Skip those with obviously unequal base addresses.
1287 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1288 isl_map_free(LoadAccs);
1289 isl_map_free(StoreAccs);
1290 continue;
1291 }
1292
1293 // And check if the remaining for overlap with other memory accesses.
1294 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1295 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1296 isl_set *AllAccs = isl_map_range(AllAccsRel);
1297
1298 for (MemoryAccess *MA : MemAccs) {
1299 if (MA == CandidatePair.first || MA == CandidatePair.second)
1300 continue;
1301
1302 isl_map *AccRel =
1303 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1304 isl_set *Accs = isl_map_range(AccRel);
1305
1306 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1307 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1308 Valid = Valid && isl_set_is_empty(OverlapAccs);
1309 isl_set_free(OverlapAccs);
1310 }
1311 }
1312
1313 isl_set_free(AllAccs);
1314 if (!Valid)
1315 continue;
1316
Johannes Doerfertf6183392014-07-01 20:52:51 +00001317 const LoadInst *Load =
1318 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1319 MemoryAccess::ReductionType RT =
1320 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1321
Johannes Doerferte58a0122014-06-27 20:31:28 +00001322 // If no overlapping access was found we mark the load and store as
1323 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001324 CandidatePair.first->markAsReductionLike(RT);
1325 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001326 }
Tobias Grosser75805372011-04-29 06:27:02 +00001327}
1328
Tobias Grosser74394f02013-01-14 22:40:23 +00001329std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001330
Tobias Grosser54839312015-04-21 11:37:25 +00001331std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001332 auto *S = getSchedule();
1333 auto Str = stringFromIslObj(S);
1334 isl_map_free(S);
1335 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001336}
1337
Tobias Grosser74394f02013-01-14 22:40:23 +00001338unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001339
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001340unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001341
Tobias Grosser75805372011-04-29 06:27:02 +00001342const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1343
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001344const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001345 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001346}
1347
Tobias Grosser74394f02013-01-14 22:40:23 +00001348isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001349
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001350__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001351
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001352__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001353 return isl_set_get_space(Domain);
1354}
1355
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001356__isl_give isl_id *ScopStmt::getDomainId() const {
1357 return isl_set_get_tuple_id(Domain);
1358}
Tobias Grossercd95b772012-08-30 11:49:38 +00001359
Tobias Grosser75805372011-04-29 06:27:02 +00001360ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001361 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001362 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001363}
1364
1365void ScopStmt::print(raw_ostream &OS) const {
1366 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001367 OS.indent(12) << "Domain :=\n";
1368
1369 if (Domain) {
1370 OS.indent(16) << getDomainStr() << ";\n";
1371 } else
1372 OS.indent(16) << "n/a\n";
1373
Tobias Grosser54839312015-04-21 11:37:25 +00001374 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001375
1376 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001377 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001378 } else
1379 OS.indent(16) << "n/a\n";
1380
Tobias Grosser083d3d32014-06-28 08:59:45 +00001381 for (MemoryAccess *Access : MemAccs)
1382 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001383}
1384
1385void ScopStmt::dump() const { print(dbgs()); }
1386
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001387void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001388
1389 // Remove all memory accesses in @p InvMAs from this statement together
1390 // with all scalar accesses that were caused by them. The tricky iteration
1391 // order uses is needed because the MemAccs is a vector and the order in
1392 // which the accesses of each memory access list (MAL) are stored in this
1393 // vector is reversed.
1394 for (MemoryAccess *MA : InvMAs) {
1395 auto &MAL = *lookupAccessesFor(MA->getAccessInstruction());
1396 MAL.reverse();
1397
1398 auto MALIt = MAL.begin();
1399 auto MALEnd = MAL.end();
1400 auto MemAccsIt = MemAccs.begin();
1401 while (MALIt != MALEnd) {
1402 while (*MemAccsIt != *MALIt)
1403 MemAccsIt++;
1404
1405 MALIt++;
1406 MemAccs.erase(MemAccsIt);
1407 }
1408
1409 InstructionToAccess.erase(MA->getAccessInstruction());
1410 delete &MAL;
1411 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001412}
1413
Tobias Grosser75805372011-04-29 06:27:02 +00001414//===----------------------------------------------------------------------===//
1415/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001416
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001417void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001418 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1419 isl_set_free(Context);
1420 Context = NewContext;
1421}
1422
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001423const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
1424 return SCEVParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001425}
1426
Tobias Grosserabfbe632013-02-05 12:09:06 +00001427void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001428 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001429 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001430
1431 // Normalize the SCEV to get the representing element for an invariant load.
1432 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1433
Tobias Grosser60b54f12011-11-08 15:41:28 +00001434 if (ParameterIds.find(Parameter) != ParameterIds.end())
1435 continue;
1436
1437 int dimension = Parameters.size();
1438
1439 Parameters.push_back(Parameter);
1440 ParameterIds[Parameter] = dimension;
1441 }
1442}
1443
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001444__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001445 // Normalize the SCEV to get the representing element for an invariant load.
1446 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1447
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001448 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001449
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001450 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001451 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001452
Tobias Grosser8f99c162011-11-15 11:38:55 +00001453 std::string ParameterName;
1454
1455 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1456 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001457 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001458 }
1459
1460 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001461 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001462
Tobias Grosser20532b82014-04-11 17:56:49 +00001463 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1464 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001465}
Tobias Grosser75805372011-04-29 06:27:02 +00001466
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001467isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1468 isl_set *DomainContext = isl_union_set_params(getDomains());
1469 return isl_set_intersect_params(C, DomainContext);
1470}
1471
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001472void Scop::buildBoundaryContext() {
1473 BoundaryContext = Affinator.getWrappingContext();
1474 BoundaryContext = isl_set_complement(BoundaryContext);
1475 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
1476}
1477
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001478void Scop::addUserContext() {
1479 if (UserContextStr.empty())
1480 return;
1481
1482 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1483 isl_space *Space = getParamSpace();
1484 if (isl_space_dim(Space, isl_dim_param) !=
1485 isl_set_dim(UserContext, isl_dim_param)) {
1486 auto SpaceStr = isl_space_to_str(Space);
1487 errs() << "Error: the context provided in -polly-context has not the same "
1488 << "number of dimensions than the computed context. Due to this "
1489 << "mismatch, the -polly-context option is ignored. Please provide "
1490 << "the context in the parameter space: " << SpaceStr << ".\n";
1491 free(SpaceStr);
1492 isl_set_free(UserContext);
1493 isl_space_free(Space);
1494 return;
1495 }
1496
1497 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1498 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1499 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1500
1501 if (strcmp(NameContext, NameUserContext) != 0) {
1502 auto SpaceStr = isl_space_to_str(Space);
1503 errs() << "Error: the name of dimension " << i
1504 << " provided in -polly-context "
1505 << "is '" << NameUserContext << "', but the name in the computed "
1506 << "context is '" << NameContext
1507 << "'. Due to this name mismatch, "
1508 << "the -polly-context option is ignored. Please provide "
1509 << "the context in the parameter space: " << SpaceStr << ".\n";
1510 free(SpaceStr);
1511 isl_set_free(UserContext);
1512 isl_space_free(Space);
1513 return;
1514 }
1515
1516 UserContext =
1517 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1518 isl_space_get_dim_id(Space, isl_dim_param, i));
1519 }
1520
1521 Context = isl_set_intersect(Context, UserContext);
1522 isl_space_free(Space);
1523}
1524
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001525void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001526 DenseMap<const SCEV *, LoadInst *> EquivClasses;
1527
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001528 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001529 for (LoadInst *LInst : RIL) {
1530 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1531
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001532 LoadInst *&ClassRep = EquivClasses[PointerSCEV];
1533 if (!ClassRep)
1534 ClassRep = LInst;
1535 else
1536 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001537 }
1538}
1539
Tobias Grosser6be480c2011-11-08 15:41:13 +00001540void Scop::buildContext() {
1541 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001542 Context = isl_set_universe(isl_space_copy(Space));
1543 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001544}
1545
Tobias Grosser18daaca2012-05-22 10:47:27 +00001546void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001547 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001548 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001549
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001550 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001551
Johannes Doerferte7044942015-02-24 11:58:30 +00001552 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001553 }
1554}
1555
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001556void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001557 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001558 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001559
Tobias Grosser083d3d32014-06-28 08:59:45 +00001560 for (const auto &ParamID : ParameterIds) {
1561 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001562 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001563 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001564 }
1565
1566 // Align the parameters of all data structures to the model.
1567 Context = isl_set_align_params(Context, Space);
1568
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001569 for (ScopStmt &Stmt : *this)
1570 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001571}
1572
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001573static __isl_give isl_set *
1574simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1575 const Scop &S) {
1576 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1577 AssumptionContext = isl_set_gist_params(AssumptionContext, DomainParameters);
1578 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1579 return AssumptionContext;
1580}
1581
1582void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001583 // The parameter constraints of the iteration domains give us a set of
1584 // constraints that need to hold for all cases where at least a single
1585 // statement iteration is executed in the whole scop. We now simplify the
1586 // assumed context under the assumption that such constraints hold and at
1587 // least a single statement iteration is executed. For cases where no
1588 // statement instances are executed, the assumptions we have taken about
1589 // the executed code do not matter and can be changed.
1590 //
1591 // WARNING: This only holds if the assumptions we have taken do not reduce
1592 // the set of statement instances that are executed. Otherwise we
1593 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001594 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001595 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001596 // performed. In such a case, modifying the run-time conditions and
1597 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001598 // to not be executed.
1599 //
1600 // Example:
1601 //
1602 // When delinearizing the following code:
1603 //
1604 // for (long i = 0; i < 100; i++)
1605 // for (long j = 0; j < m; j++)
1606 // A[i+p][j] = 1.0;
1607 //
1608 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001609 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001610 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001611 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1612 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001613}
1614
Johannes Doerfertb164c792014-09-18 11:17:17 +00001615/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001616static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001617 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1618 isl_pw_multi_aff *MinPMA, *MaxPMA;
1619 isl_pw_aff *LastDimAff;
1620 isl_aff *OneAff;
1621 unsigned Pos;
1622
Johannes Doerfert9143d672014-09-27 11:02:39 +00001623 // Restrict the number of parameters involved in the access as the lexmin/
1624 // lexmax computation will take too long if this number is high.
1625 //
1626 // Experiments with a simple test case using an i7 4800MQ:
1627 //
1628 // #Parameters involved | Time (in sec)
1629 // 6 | 0.01
1630 // 7 | 0.04
1631 // 8 | 0.12
1632 // 9 | 0.40
1633 // 10 | 1.54
1634 // 11 | 6.78
1635 // 12 | 30.38
1636 //
1637 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1638 unsigned InvolvedParams = 0;
1639 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1640 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1641 InvolvedParams++;
1642
1643 if (InvolvedParams > RunTimeChecksMaxParameters) {
1644 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001645 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001646 }
1647 }
1648
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001649 Set = isl_set_remove_divs(Set);
1650
Johannes Doerfertb164c792014-09-18 11:17:17 +00001651 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1652 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1653
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001654 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1655 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1656
Johannes Doerfertb164c792014-09-18 11:17:17 +00001657 // Adjust the last dimension of the maximal access by one as we want to
1658 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1659 // we test during code generation might now point after the end of the
1660 // allocated array but we will never dereference it anyway.
1661 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1662 "Assumed at least one output dimension");
1663 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1664 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1665 OneAff = isl_aff_zero_on_domain(
1666 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1667 OneAff = isl_aff_add_constant_si(OneAff, 1);
1668 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1669 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1670
1671 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1672
1673 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001674 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001675}
1676
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001677static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1678 isl_set *Domain = MA->getStatement()->getDomain();
1679 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1680 return isl_set_reset_tuple_id(Domain);
1681}
1682
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001683/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1684static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001685 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001686 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001687
1688 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1689 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001690 Locations = isl_union_set_coalesce(Locations);
1691 Locations = isl_union_set_detect_equalities(Locations);
1692 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001693 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001694 isl_union_set_free(Locations);
1695 return Valid;
1696}
1697
Johannes Doerfert96425c22015-08-30 21:13:53 +00001698/// @brief Helper to treat non-affine regions and basic blocks the same.
1699///
1700///{
1701
1702/// @brief Return the block that is the representing block for @p RN.
1703static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1704 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1705 : RN->getNodeAs<BasicBlock>();
1706}
1707
1708/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001709static inline BasicBlock *
1710getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001711 if (RN->isSubRegion()) {
1712 assert(idx == 0);
1713 return RN->getNodeAs<Region>()->getExit();
1714 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001715 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001716}
1717
1718/// @brief Return the smallest loop surrounding @p RN.
1719static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1720 if (!RN->isSubRegion())
1721 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1722
1723 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1724 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1725 while (L && NonAffineSubRegion->contains(L))
1726 L = L->getParentLoop();
1727 return L;
1728}
1729
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001730static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1731 if (!RN->isSubRegion())
1732 return 1;
1733
1734 unsigned NumBlocks = 0;
1735 Region *R = RN->getNodeAs<Region>();
1736 for (auto BB : R->blocks()) {
1737 (void)BB;
1738 NumBlocks++;
1739 }
1740 return NumBlocks;
1741}
1742
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001743static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
1744 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00001745 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001746 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00001747 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001748 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00001749 return true;
1750 return false;
1751}
1752
Johannes Doerfert96425c22015-08-30 21:13:53 +00001753///}
1754
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001755static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1756 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001757 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001758 isl_id *DimId =
1759 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
1760 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
1761}
1762
Johannes Doerfert96425c22015-08-30 21:13:53 +00001763isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1764 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1765 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00001766 return getDomainConditions(BB);
1767}
1768
1769isl_set *Scop::getDomainConditions(BasicBlock *BB) {
1770 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001771 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001772}
1773
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001774void Scop::buildDomains(Region *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001775
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001776 auto *EntryBB = R->getEntry();
1777 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
1778 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001779
1780 Loop *L = LI.getLoopFor(EntryBB);
1781 while (LD-- >= 0) {
1782 S = addDomainDimId(S, LD + 1, L);
1783 L = L->getParentLoop();
1784 }
1785
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001786 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001787
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00001788 if (SD.isNonAffineSubRegion(R, R))
1789 return;
1790
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001791 buildDomainsWithBranchConstraints(R);
1792 propagateDomainConstraints(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001793}
1794
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001795void Scop::buildDomainsWithBranchConstraints(Region *R) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001796 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00001797
1798 // To create the domain for each block in R we iterate over all blocks and
1799 // subregions in R and propagate the conditions under which the current region
1800 // element is executed. To this end we iterate in reverse post order over R as
1801 // it ensures that we first visit all predecessors of a region node (either a
1802 // basic block or a subregion) before we visit the region node itself.
1803 // Initially, only the domain for the SCoP region entry block is set and from
1804 // there we propagate the current domain to all successors, however we add the
1805 // condition that the successor is actually executed next.
1806 // As we are only interested in non-loop carried constraints here we can
1807 // simply skip loop back edges.
1808
1809 ReversePostOrderTraversal<Region *> RTraversal(R);
1810 for (auto *RN : RTraversal) {
1811
1812 // Recurse for affine subregions but go on for basic blocks and non-affine
1813 // subregions.
1814 if (RN->isSubRegion()) {
1815 Region *SubRegion = RN->getNodeAs<Region>();
1816 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001817 buildDomainsWithBranchConstraints(SubRegion);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001818 continue;
1819 }
1820 }
1821
Johannes Doerfertf5673802015-10-01 23:48:18 +00001822 // Error blocks are assumed not to be executed. Therefor they are not
1823 // checked properly in the ScopDetection. Any attempt to generate control
1824 // conditions from them might result in a crash. However, this is only true
1825 // for the first step of the domain generation (this function) where we
1826 // push the control conditions of a block to the successors. In the second
1827 // step (propagateDomainConstraints) we only receive domain constraints from
1828 // the predecessors and can therefor look at the domain of a error block.
1829 // That allows us to generate the assumptions needed for them not to be
1830 // executed at runtime.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001831 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00001832 continue;
1833
Johannes Doerfert96425c22015-08-30 21:13:53 +00001834 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001835 TerminatorInst *TI = BB->getTerminator();
1836
Johannes Doerfertf5673802015-10-01 23:48:18 +00001837 isl_set *Domain = DomainMap.lookup(BB);
1838 if (!Domain) {
1839 DEBUG(dbgs() << "\tSkip: " << BB->getName()
1840 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001841 continue;
1842 }
1843
Johannes Doerfert96425c22015-08-30 21:13:53 +00001844 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001845
1846 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1847 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1848
1849 // Build the condition sets for the successor nodes of the current region
1850 // node. If it is a non-affine subregion we will always execute the single
1851 // exit node, hence the single entry node domain is the condition set. For
1852 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001853 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001854 if (RN->isSubRegion())
1855 ConditionSets.push_back(isl_set_copy(Domain));
1856 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001857 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001858
1859 // Now iterate over the successors and set their initial domain based on
1860 // their condition set. We skip back edges here and have to be careful when
1861 // we leave a loop not to keep constraints over a dimension that doesn't
1862 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001863 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00001864 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001865 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001866 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001867
1868 // Skip back edges.
1869 if (DT.dominates(SuccBB, BB)) {
1870 isl_set_free(CondSet);
1871 continue;
1872 }
1873
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001874 // Do not adjust the number of dimensions if we enter a boxed loop or are
1875 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001876 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001877 Region *SuccRegion = RI.getRegionFor(SuccBB);
Johannes Doerfert634909c2015-10-04 14:57:41 +00001878 if (SD.isNonAffineSubRegion(SuccRegion, &getRegion()))
1879 while (SuccBBLoop && SuccRegion->contains(SuccBBLoop))
1880 SuccBBLoop = SuccBBLoop->getParentLoop();
1881
1882 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001883
1884 // Check if the edge to SuccBB is a loop entry or exit edge. If so
1885 // adjust the dimensionality accordingly. Lastly, if we leave a loop
1886 // and enter a new one we need to drop the old constraints.
1887 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001888 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001889 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001890 CondSet = isl_set_project_out(CondSet, isl_dim_set,
1891 isl_set_n_dim(CondSet) - LoopDepthDiff,
1892 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001893 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001894 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001895 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001896 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001897 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001898 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001899 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
1900 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001901 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001902 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00001903 }
1904
1905 // Set the domain for the successor or merge it with an existing domain in
1906 // case there are multiple paths (without loop back edges) to the
1907 // successor block.
1908 isl_set *&SuccDomain = DomainMap[SuccBB];
1909 if (!SuccDomain)
1910 SuccDomain = CondSet;
1911 else
1912 SuccDomain = isl_set_union(SuccDomain, CondSet);
1913
1914 SuccDomain = isl_set_coalesce(SuccDomain);
Johannes Doerfert634909c2015-10-04 14:57:41 +00001915 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
1916 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001917 }
1918 }
1919}
1920
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001921/// @brief Return the domain for @p BB wrt @p DomainMap.
1922///
1923/// This helper function will lookup @p BB in @p DomainMap but also handle the
1924/// case where @p BB is contained in a non-affine subregion using the region
1925/// tree obtained by @p RI.
1926static __isl_give isl_set *
1927getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
1928 RegionInfo &RI) {
1929 auto DIt = DomainMap.find(BB);
1930 if (DIt != DomainMap.end())
1931 return isl_set_copy(DIt->getSecond());
1932
1933 Region *R = RI.getRegionFor(BB);
1934 while (R->getEntry() == BB)
1935 R = R->getParent();
1936 return getDomainForBlock(R->getEntry(), DomainMap, RI);
1937}
1938
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001939void Scop::propagateDomainConstraints(Region *R) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001940 // Iterate over the region R and propagate the domain constrains from the
1941 // predecessors to the current node. In contrast to the
1942 // buildDomainsWithBranchConstraints function, this one will pull the domain
1943 // information from the predecessors instead of pushing it to the successors.
1944 // Additionally, we assume the domains to be already present in the domain
1945 // map here. However, we iterate again in reverse post order so we know all
1946 // predecessors have been visited before a block or non-affine subregion is
1947 // visited.
1948
1949 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
1950 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
1951
1952 ReversePostOrderTraversal<Region *> RTraversal(R);
1953 for (auto *RN : RTraversal) {
1954
1955 // Recurse for affine subregions but go on for basic blocks and non-affine
1956 // subregions.
1957 if (RN->isSubRegion()) {
1958 Region *SubRegion = RN->getNodeAs<Region>();
1959 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001960 propagateDomainConstraints(SubRegion);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001961 continue;
1962 }
1963 }
1964
Johannes Doerfertf5673802015-10-01 23:48:18 +00001965 // Get the domain for the current block and check if it was initialized or
1966 // not. The only way it was not is if this block is only reachable via error
1967 // blocks, thus will not be executed under the assumptions we make. Such
1968 // blocks have to be skipped as their predecessors might not have domains
1969 // either. It would not benefit us to compute the domain anyway, only the
1970 // domains of the error blocks that are reachable from non-error blocks
1971 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001972 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00001973 isl_set *&Domain = DomainMap[BB];
1974 if (!Domain) {
1975 DEBUG(dbgs() << "\tSkip: " << BB->getName()
1976 << ", it is only reachable from error blocks.\n");
1977 DomainMap.erase(BB);
1978 continue;
1979 }
1980 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
1981
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001982 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1983 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1984
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001985 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
1986 for (auto *PredBB : predecessors(BB)) {
1987
1988 // Skip backedges
1989 if (DT.dominates(BB, PredBB))
1990 continue;
1991
1992 isl_set *PredBBDom = nullptr;
1993
1994 // Handle the SCoP entry block with its outside predecessors.
1995 if (!getRegion().contains(PredBB))
1996 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
1997
1998 if (!PredBBDom) {
1999 // Determine the loop depth of the predecessor and adjust its domain to
2000 // the domain of the current block. This can mean we have to:
2001 // o) Drop a dimension if this block is the exit of a loop, not the
2002 // header of a new loop and the predecessor was part of the loop.
2003 // o) Add an unconstrainted new dimension if this block is the header
2004 // of a loop and the predecessor is not part of it.
2005 // o) Drop the information about the innermost loop dimension when the
2006 // predecessor and the current block are surrounded by different
2007 // loops in the same depth.
2008 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2009 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2010 while (BoxedLoops.count(PredBBLoop))
2011 PredBBLoop = PredBBLoop->getParentLoop();
2012
2013 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002014 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002015 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002016 PredBBDom = isl_set_project_out(
2017 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2018 LoopDepthDiff);
2019 else if (PredBBLoopDepth < BBLoopDepth) {
2020 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002021 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002022 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2023 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002024 PredBBDom = isl_set_drop_constraints_involving_dims(
2025 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002026 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002027 }
2028
2029 PredDom = isl_set_union(PredDom, PredBBDom);
2030 }
2031
2032 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002033 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002034
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002035 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002036 addLoopBoundsToHeaderDomain(BBLoop);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002037
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002038 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002039 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002040 IsOptimized = true;
2041 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2042 addAssumption(isl_set_complement(DomPar));
2043 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002044 }
2045}
2046
2047/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2048/// is incremented by one and all other dimensions are equal, e.g.,
2049/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2050/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2051static __isl_give isl_map *
2052createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2053 auto *MapSpace = isl_space_map_from_set(SetSpace);
2054 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2055 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2056 if (u != Dim)
2057 NextIterationMap =
2058 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2059 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2060 C = isl_constraint_set_constant_si(C, 1);
2061 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2062 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2063 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2064 return NextIterationMap;
2065}
2066
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002067void Scop::addLoopBoundsToHeaderDomain(Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002068 int LoopDepth = getRelativeLoopDepth(L);
2069 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002070
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002071 BasicBlock *HeaderBB = L->getHeader();
2072 assert(DomainMap.count(HeaderBB));
2073 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002074
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002075 isl_map *NextIterationMap =
2076 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002077
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002078 isl_set *UnionBackedgeCondition =
2079 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002080
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002081 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2082 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002083
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002084 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002085
2086 // If the latch is only reachable via error statements we skip it.
2087 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2088 if (!LatchBBDom)
2089 continue;
2090
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002091 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002092
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002093 TerminatorInst *TI = LatchBB->getTerminator();
2094 BranchInst *BI = dyn_cast<BranchInst>(TI);
2095 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002096 BackedgeCondition = isl_set_copy(LatchBBDom);
2097 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002098 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002099 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002100 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002101
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002102 // Free the non back edge condition set as we do not need it.
2103 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002104
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002105 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002106 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002107
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002108 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2109 assert(LatchLoopDepth >= LoopDepth);
2110 BackedgeCondition =
2111 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2112 LatchLoopDepth - LoopDepth);
2113 UnionBackedgeCondition =
2114 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002115 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002116
2117 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2118 for (int i = 0; i < LoopDepth; i++)
2119 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2120
2121 isl_set *UnionBackedgeConditionComplement =
2122 isl_set_complement(UnionBackedgeCondition);
2123 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2124 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2125 UnionBackedgeConditionComplement =
2126 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2127 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2128 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2129
2130 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2131 HeaderBBDom = Parts.second;
2132
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002133 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2134 // the bounded assumptions to the context as they are already implied by the
2135 // <nsw> tag.
2136 if (Affinator.hasNSWAddRecForLoop(L)) {
2137 isl_set_free(Parts.first);
2138 return;
2139 }
2140
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002141 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2142 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfert707a4062015-09-20 16:38:19 +00002143 addAssumption(BoundedCtx);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002144}
2145
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002146void Scop::buildAliasChecks(AliasAnalysis &AA) {
2147 if (!PollyUseRuntimeAliasChecks)
2148 return;
2149
2150 if (buildAliasGroups(AA))
2151 return;
2152
2153 // If a problem occurs while building the alias groups we need to delete
2154 // this SCoP and pretend it wasn't valid in the first place. To this end
2155 // we make the assumed context infeasible.
2156 addAssumption(isl_set_empty(getParamSpace()));
2157
2158 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2159 << " could not be created as the number of parameters involved "
2160 "is too high. The SCoP will be "
2161 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2162 "the maximal number of parameters but be advised that the "
2163 "compile time might increase exponentially.\n\n");
2164}
2165
Johannes Doerfert9143d672014-09-27 11:02:39 +00002166bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002167 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002168 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002169 // for all memory accesses inside the SCoP.
2170 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002171 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002172 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002173 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002174 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002175 // if their access domains intersect, otherwise they are in different
2176 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002177 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002178 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002179 // and maximal accesses to each array of a group in read only and non
2180 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002181 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2182
2183 AliasSetTracker AST(AA);
2184
2185 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002186 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002187 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002188
2189 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002190 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002191 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2192 isl_set_free(StmtDomain);
2193 if (StmtDomainEmpty)
2194 continue;
2195
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002196 for (MemoryAccess *MA : Stmt) {
Michael Kruse8d0b7342015-09-25 21:21:00 +00002197 if (MA->isImplicit())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002198 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002199 if (!MA->isRead())
2200 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002201 Instruction *Acc = MA->getAccessInstruction();
2202 PtrToAcc[getPointerOperand(*Acc)] = MA;
2203 AST.add(Acc);
2204 }
2205 }
2206
2207 SmallVector<AliasGroupTy, 4> AliasGroups;
2208 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002209 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002210 continue;
2211 AliasGroupTy AG;
2212 for (auto PR : AS)
2213 AG.push_back(PtrToAcc[PR.getValue()]);
2214 assert(AG.size() > 1 &&
2215 "Alias groups should contain at least two accesses");
2216 AliasGroups.push_back(std::move(AG));
2217 }
2218
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002219 // Split the alias groups based on their domain.
2220 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2221 AliasGroupTy NewAG;
2222 AliasGroupTy &AG = AliasGroups[u];
2223 AliasGroupTy::iterator AGI = AG.begin();
2224 isl_set *AGDomain = getAccessDomain(*AGI);
2225 while (AGI != AG.end()) {
2226 MemoryAccess *MA = *AGI;
2227 isl_set *MADomain = getAccessDomain(MA);
2228 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2229 NewAG.push_back(MA);
2230 AGI = AG.erase(AGI);
2231 isl_set_free(MADomain);
2232 } else {
2233 AGDomain = isl_set_union(AGDomain, MADomain);
2234 AGI++;
2235 }
2236 }
2237 if (NewAG.size() > 1)
2238 AliasGroups.push_back(std::move(NewAG));
2239 isl_set_free(AGDomain);
2240 }
2241
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002242 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002243 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2244 for (AliasGroupTy &AG : AliasGroups) {
2245 NonReadOnlyBaseValues.clear();
2246 ReadOnlyPairs.clear();
2247
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002248 if (AG.size() < 2) {
2249 AG.clear();
2250 continue;
2251 }
2252
Johannes Doerfert13771732014-10-01 12:40:46 +00002253 for (auto II = AG.begin(); II != AG.end();) {
2254 Value *BaseAddr = (*II)->getBaseAddr();
2255 if (HasWriteAccess.count(BaseAddr)) {
2256 NonReadOnlyBaseValues.insert(BaseAddr);
2257 II++;
2258 } else {
2259 ReadOnlyPairs[BaseAddr].insert(*II);
2260 II = AG.erase(II);
2261 }
2262 }
2263
2264 // If we don't have read only pointers check if there are at least two
2265 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002266 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002267 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002268 continue;
2269 }
2270
2271 // If we don't have non read only pointers clear the alias group.
2272 if (NonReadOnlyBaseValues.empty()) {
2273 AG.clear();
2274 continue;
2275 }
2276
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002277 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002278 MinMaxAliasGroups.emplace_back();
2279 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2280 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2281 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2282 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002283
2284 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002285
2286 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002287 for (MemoryAccess *MA : AG)
2288 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002289
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002290 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2291 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002292
2293 // Bail out if the number of values we need to compare is too large.
2294 // This is important as the number of comparisions grows quadratically with
2295 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002296 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2297 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002298 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002299
2300 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002301 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002302 Accesses = isl_union_map_empty(getParamSpace());
2303
2304 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2305 for (MemoryAccess *MA : ReadOnlyPair.second)
2306 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2307
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002308 Valid =
2309 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002310
2311 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002312 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002313 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002314
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002315 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002316}
2317
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002318static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
2319 Loop *L = LI.getLoopFor(R.getEntry());
2320 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2321}
2322
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002323static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2324 ScopDetection &SD) {
2325
2326 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2327
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002328 unsigned MinLD = INT_MAX, MaxLD = 0;
2329 for (BasicBlock *BB : R.blocks()) {
2330 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002331 if (!R.contains(L))
2332 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002333 if (BoxedLoops && BoxedLoops->count(L))
2334 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002335 unsigned LD = L->getLoopDepth();
2336 MinLD = std::min(MinLD, LD);
2337 MaxLD = std::max(MaxLD, LD);
2338 }
2339 }
2340
2341 // Handle the case that there is no loop in the SCoP first.
2342 if (MaxLD == 0)
2343 return 1;
2344
2345 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2346 assert(MaxLD >= MinLD &&
2347 "Maximal loop depth was smaller than mininaml loop depth?");
2348 return MaxLD - MinLD + 1;
2349}
2350
Johannes Doerfert478a7de2015-10-02 13:09:31 +00002351Scop::Scop(Region &R, AccFuncMapType &AccFuncMap, ScopDetection &SD,
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002352 ScalarEvolution &ScalarEvolution, DominatorTree &DT, LoopInfo &LI,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002353 isl_ctx *Context, unsigned MaxLoopDepth)
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002354 : LI(LI), DT(DT), SE(&ScalarEvolution), SD(SD), R(R),
2355 AccFuncMap(AccFuncMap), IsOptimized(false),
2356 HasSingleExitEdge(R.getExitingBlock()), MaxLoopDepth(MaxLoopDepth),
2357 IslCtx(Context), Context(nullptr), Affinator(this),
2358 AssumedContext(nullptr), BoundaryContext(nullptr), Schedule(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002359
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002360void Scop::init(AliasAnalysis &AA) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002361 buildContext();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002362 buildInvariantEquivalenceClasses();
2363
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002364 buildDomains(&R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002365
Michael Krusecac948e2015-10-02 13:53:07 +00002366 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002367 // Exit early in case there are no executable statements left in this scop.
Michael Krusecac948e2015-10-02 13:53:07 +00002368 simplifySCoP(true);
Michael Kruseafe06702015-10-02 16:33:27 +00002369 if (Stmts.empty())
2370 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002371
Michael Krusecac948e2015-10-02 13:53:07 +00002372 // The ScopStmts now have enough information to initialize themselves.
2373 for (ScopStmt &Stmt : Stmts)
2374 Stmt.init();
2375
2376 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002377 Loop *L = getLoopSurroundingRegion(R, LI);
2378 LoopSchedules[L];
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002379 buildSchedule(&R, LoopSchedules);
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002380 updateAccessDimensionality();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002381 Schedule = LoopSchedules[L].first;
Tobias Grosser75805372011-04-29 06:27:02 +00002382
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002383 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002384 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002385 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002386 buildBoundaryContext();
2387 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002388 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002389
2390 hoistInvariantLoads();
Michael Krusecac948e2015-10-02 13:53:07 +00002391 simplifySCoP(false);
Tobias Grosser75805372011-04-29 06:27:02 +00002392}
2393
2394Scop::~Scop() {
2395 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002396 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002397 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002398 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002399
Johannes Doerfert96425c22015-08-30 21:13:53 +00002400 for (auto It : DomainMap)
2401 isl_set_free(It.second);
2402
Johannes Doerfertb164c792014-09-18 11:17:17 +00002403 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002404 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002405 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002406 isl_pw_multi_aff_free(MMA.first);
2407 isl_pw_multi_aff_free(MMA.second);
2408 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002409 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002410 isl_pw_multi_aff_free(MMA.first);
2411 isl_pw_multi_aff_free(MMA.second);
2412 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002413 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002414
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002415 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002416 isl_set_free(std::get<2>(IAClass));
Tobias Grosser75805372011-04-29 06:27:02 +00002417}
2418
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002419void Scop::updateAccessDimensionality() {
2420 for (auto &Stmt : *this)
2421 for (auto &Access : Stmt)
2422 Access->updateDimensionality();
2423}
2424
Michael Krusecac948e2015-10-02 13:53:07 +00002425void Scop::simplifySCoP(bool RemoveIgnoredStmts) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002426 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2427 ScopStmt &Stmt = *StmtIt;
Michael Krusecac948e2015-10-02 13:53:07 +00002428 RegionNode *RN = Stmt.isRegionStmt()
2429 ? Stmt.getRegion()->getNode()
2430 : getRegion().getBBNode(Stmt.getBasicBlock());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002431
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002432 if (StmtIt->isEmpty() ||
2433 isl_set_is_empty(DomainMap[getRegionNodeBasicBlock(RN)]) ||
2434 (RemoveIgnoredStmts && isIgnored(RN))) {
2435
Michael Krusecac948e2015-10-02 13:53:07 +00002436 // Remove the statement because it is unnecessary.
2437 if (Stmt.isRegionStmt())
2438 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2439 StmtMap.erase(BB);
2440 else
2441 StmtMap.erase(Stmt.getBasicBlock());
2442
2443 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002444 continue;
2445 }
2446
Michael Krusecac948e2015-10-02 13:53:07 +00002447 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002448 }
2449}
2450
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002451const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2452 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2453 if (!LInst)
2454 return nullptr;
2455
2456 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2457 LInst = cast<LoadInst>(Rep);
2458
2459 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2460 for (auto &IAClass : InvariantEquivClasses)
2461 if (PointerSCEV == std::get<0>(IAClass))
2462 return &IAClass;
2463
2464 return nullptr;
2465}
2466
2467void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2468
2469 // Get the context under which the statement is executed.
2470 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2471 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2472 DomainCtx = isl_set_detect_equalities(DomainCtx);
2473 DomainCtx = isl_set_coalesce(DomainCtx);
2474
2475 // Project out all parameters that relate to loads in the statement. Otherwise
2476 // we could have cyclic dependences on the constraints under which the
2477 // hoisted loads are executed and we could not determine an order in which to
2478 // pre-load them. This happens because not only lower bounds are part of the
2479 // domain but also upper bounds.
2480 for (MemoryAccess *MA : InvMAs) {
2481 Instruction *AccInst = MA->getAccessInstruction();
2482 if (SE->isSCEVable(AccInst->getType())) {
2483 isl_id *ParamId = getIdForParam(SE->getSCEV(AccInst));
2484 if (ParamId) {
2485 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2486 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2487 }
2488 isl_id_free(ParamId);
2489 }
2490 }
2491
2492 for (MemoryAccess *MA : InvMAs) {
2493 // Check for another invariant access that accesses the same location as
2494 // MA and if found consolidate them. Otherwise create a new equivalence
2495 // class at the end of InvariantEquivClasses.
2496 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
2497 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2498
2499 bool Consolidated = false;
2500 for (auto &IAClass : InvariantEquivClasses) {
2501 if (PointerSCEV != std::get<0>(IAClass))
2502 continue;
2503
2504 Consolidated = true;
2505
2506 // Add MA to the list of accesses that are in this class.
2507 auto &MAs = std::get<1>(IAClass);
2508 MAs.push_front(MA);
2509
2510 // Unify the execution context of the class and this statement.
2511 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
2512 IAClassDomainCtx = isl_set_coalesce(
2513 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
2514 break;
2515 }
2516
2517 if (Consolidated)
2518 continue;
2519
2520 // If we did not consolidate MA, thus did not find an equivalence class
2521 // for it, we create a new one.
2522 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
2523 isl_set_copy(DomainCtx));
2524 }
2525
2526 isl_set_free(DomainCtx);
2527}
2528
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002529void Scop::hoistInvariantLoads() {
2530 isl_union_map *Writes = getWrites();
2531 for (ScopStmt &Stmt : *this) {
2532
2533 // TODO: Loads that are not loop carried, hence are in a statement with
2534 // zero iterators, are by construction invariant, though we
Johannes Doerfert09e36972015-10-07 20:17:36 +00002535 // currently "hoist" them anyway. This is necessary because we allow
2536 // them to be treated as parameters (e.g., in conditions) and our code
2537 // generation would otherwise use the old value.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002538
Johannes Doerfert8930f482015-10-02 14:51:00 +00002539 BasicBlock *BB = Stmt.isBlockStmt() ? Stmt.getBasicBlock()
2540 : Stmt.getRegion()->getEntry();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002541 isl_set *Domain = Stmt.getDomain();
2542 MemoryAccessList InvMAs;
2543
2544 for (MemoryAccess *MA : Stmt) {
2545 if (MA->isImplicit() || MA->isWrite() || !MA->isAffine())
2546 continue;
2547
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002548 // Skip accesses that have an invariant base pointer which is defined but
2549 // not loaded inside the SCoP. This can happened e.g., if a readnone call
2550 // returns a pointer that is used as a base address. However, as we want
2551 // to hoist indirect pointers, we allow the base pointer to be defined in
Johannes Doerfert654c3282015-10-21 22:14:57 +00002552 // the region if it is also a memory access. Each ScopArrayInfo object
2553 // that has a base pointer origin has a base pointer that is loaded and
2554 // that it is invariant, thus it will be hoisted too. However, if there is
2555 // no bease pointer origin we check that the base pointer is defined
2556 // outside the region.
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002557 const ScopArrayInfo *SAI = MA->getScopArrayInfo();
Johannes Doerfert654c3282015-10-21 22:14:57 +00002558 while (auto *BasePtrOriginSAI = SAI->getBasePtrOriginSAI())
2559 SAI = BasePtrOriginSAI;
2560
2561 if (auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr()))
2562 if (R.contains(BasePtrInst))
2563 continue;
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002564
Johannes Doerfert8930f482015-10-02 14:51:00 +00002565 // Skip accesses in non-affine subregions as they might not be executed
2566 // under the same condition as the entry of the non-affine subregion.
2567 if (BB != MA->getAccessInstruction()->getParent())
2568 continue;
2569
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002570 isl_map *AccessRelation = MA->getAccessRelation();
Johannes Doerfertb864c2c2015-10-18 19:50:18 +00002571
2572 // Skip accesses that have an empty access relation. These can be caused
2573 // by multiple offsets with a type cast in-between that cause the overall
2574 // byte offset to be not divisible by the new types sizes.
2575 if (isl_map_is_empty(AccessRelation)) {
2576 isl_map_free(AccessRelation);
2577 continue;
2578 }
2579
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002580 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
2581 Stmt.getNumIterators())) {
2582 isl_map_free(AccessRelation);
2583 continue;
2584 }
2585
2586 AccessRelation =
2587 isl_map_intersect_domain(AccessRelation, isl_set_copy(Domain));
2588 isl_set *AccessRange = isl_map_range(AccessRelation);
2589
2590 isl_union_map *Written = isl_union_map_intersect_range(
2591 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
2592 bool IsWritten = !isl_union_map_is_empty(Written);
2593 isl_union_map_free(Written);
2594
2595 if (IsWritten)
2596 continue;
2597
2598 InvMAs.push_front(MA);
2599 }
2600
2601 // We inserted invariant accesses always in the front but need them to be
2602 // sorted in a "natural order". The statements are already sorted in reverse
2603 // post order and that suffices for the accesses too. The reason we require
2604 // an order in the first place is the dependences between invariant loads
2605 // that can be caused by indirect loads.
2606 InvMAs.reverse();
2607
2608 // Transfer the memory access from the statement to the SCoP.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002609 Stmt.removeMemoryAccesses(InvMAs);
2610 addInvariantLoads(Stmt, InvMAs);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002611
2612 isl_set_free(Domain);
2613 }
2614 isl_union_map_free(Writes);
2615
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002616 if (!InvariantEquivClasses.empty())
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002617 IsOptimized = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00002618
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002619 auto &ScopRIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert09e36972015-10-07 20:17:36 +00002620 // Check required invariant loads that were tagged during SCoP detection.
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002621 for (LoadInst *LI : ScopRIL) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00002622 assert(LI && getRegion().contains(LI));
2623 ScopStmt *Stmt = getStmtForBasicBlock(LI->getParent());
2624 if (Stmt && Stmt->lookupAccessesFor(LI) != nullptr) {
2625 DEBUG(dbgs() << "\n\nWARNING: Load (" << *LI
2626 << ") is required to be invariant but was not marked as "
2627 "such. SCoP for "
2628 << getRegion() << " will be dropped\n\n");
2629 addAssumption(isl_set_empty(getParamSpace()));
2630 return;
2631 }
2632 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002633}
2634
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002635const ScopArrayInfo *
2636Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Michael Kruse28468772015-09-14 15:45:33 +00002637 ArrayRef<const SCEV *> Sizes, bool IsPHI) {
Tobias Grosser92245222015-07-28 14:53:44 +00002638 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002639 if (!SAI) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002640 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, IsPHI,
2641 this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002642 } else {
2643 if (Sizes.size() > SAI->getNumberOfDimensions())
2644 SAI->updateSizes(Sizes);
2645 }
Tobias Grosserab671442015-05-23 05:58:27 +00002646 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002647}
2648
Tobias Grosser92245222015-07-28 14:53:44 +00002649const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, bool IsPHI) {
2650 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002651 assert(SAI && "No ScopArrayInfo available for this base pointer");
2652 return SAI;
2653}
2654
Tobias Grosser74394f02013-01-14 22:40:23 +00002655std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002656std::string Scop::getAssumedContextStr() const {
2657 return stringFromIslObj(AssumedContext);
2658}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002659std::string Scop::getBoundaryContextStr() const {
2660 return stringFromIslObj(BoundaryContext);
2661}
Tobias Grosser75805372011-04-29 06:27:02 +00002662
2663std::string Scop::getNameStr() const {
2664 std::string ExitName, EntryName;
2665 raw_string_ostream ExitStr(ExitName);
2666 raw_string_ostream EntryStr(EntryName);
2667
Tobias Grosserf240b482014-01-09 10:42:15 +00002668 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002669 EntryStr.str();
2670
2671 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00002672 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002673 ExitStr.str();
2674 } else
2675 ExitName = "FunctionExit";
2676
2677 return EntryName + "---" + ExitName;
2678}
2679
Tobias Grosser74394f02013-01-14 22:40:23 +00002680__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00002681__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002682 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00002683}
2684
Tobias Grossere86109f2013-10-29 21:05:49 +00002685__isl_give isl_set *Scop::getAssumedContext() const {
2686 return isl_set_copy(AssumedContext);
2687}
2688
Johannes Doerfert43788c52015-08-20 05:58:56 +00002689__isl_give isl_set *Scop::getRuntimeCheckContext() const {
2690 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002691 RuntimeCheckContext =
2692 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
2693 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002694 return RuntimeCheckContext;
2695}
2696
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002697bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002698 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002699 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002700 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
2701 isl_set_free(RuntimeCheckContext);
2702 return IsFeasible;
2703}
2704
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002705void Scop::addAssumption(__isl_take isl_set *Set) {
2706 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00002707 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002708}
2709
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002710__isl_give isl_set *Scop::getBoundaryContext() const {
2711 return isl_set_copy(BoundaryContext);
2712}
2713
Tobias Grosser75805372011-04-29 06:27:02 +00002714void Scop::printContext(raw_ostream &OS) const {
2715 OS << "Context:\n";
2716
2717 if (!Context) {
2718 OS.indent(4) << "n/a\n\n";
2719 return;
2720 }
2721
2722 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00002723
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002724 OS.indent(4) << "Assumed Context:\n";
2725 if (!AssumedContext) {
2726 OS.indent(4) << "n/a\n\n";
2727 return;
2728 }
2729
2730 OS.indent(4) << getAssumedContextStr() << "\n";
2731
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002732 OS.indent(4) << "Boundary Context:\n";
2733 if (!BoundaryContext) {
2734 OS.indent(4) << "n/a\n\n";
2735 return;
2736 }
2737
2738 OS.indent(4) << getBoundaryContextStr() << "\n";
2739
Tobias Grosser083d3d32014-06-28 08:59:45 +00002740 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00002741 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00002742 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
2743 }
Tobias Grosser75805372011-04-29 06:27:02 +00002744}
2745
Johannes Doerfertb164c792014-09-18 11:17:17 +00002746void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002747 int noOfGroups = 0;
2748 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002749 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002750 noOfGroups += 1;
2751 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002752 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002753 }
2754
Tobias Grosserbb853c22015-07-25 12:31:03 +00002755 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00002756 if (MinMaxAliasGroups.empty()) {
2757 OS.indent(8) << "n/a\n";
2758 return;
2759 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002760
Tobias Grosserbb853c22015-07-25 12:31:03 +00002761 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002762
2763 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002764 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002765 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002766 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002767 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2768 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002769 }
2770 OS << " ]]\n";
2771 }
2772
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002773 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002774 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00002775 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002776 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002777 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2778 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002779 }
2780 OS << " ]]\n";
2781 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002782 }
2783}
2784
Tobias Grosser75805372011-04-29 06:27:02 +00002785void Scop::printStatements(raw_ostream &OS) const {
2786 OS << "Statements {\n";
2787
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002788 for (const ScopStmt &Stmt : *this)
2789 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00002790
2791 OS.indent(4) << "}\n";
2792}
2793
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002794void Scop::printArrayInfo(raw_ostream &OS) const {
2795 OS << "Arrays {\n";
2796
Tobias Grosserab671442015-05-23 05:58:27 +00002797 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002798 Array.second->print(OS);
2799
2800 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002801
2802 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
2803
2804 for (auto &Array : arrays())
2805 Array.second->print(OS, /* SizeAsPwAff */ true);
2806
2807 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002808}
2809
Tobias Grosser75805372011-04-29 06:27:02 +00002810void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00002811 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
2812 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00002813 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00002814 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002815 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002816 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002817 const auto &MAs = std::get<1>(IAClass);
2818 if (MAs.empty()) {
2819 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002820 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002821 MAs.front()->print(OS);
2822 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002823 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002824 }
2825 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00002826 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002827 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002828 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00002829 printStatements(OS.indent(4));
2830}
2831
2832void Scop::dump() const { print(dbgs()); }
2833
Tobias Grosser9a38ab82011-11-08 15:41:03 +00002834isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00002835
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002836__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
2837 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00002838}
2839
Tobias Grosser808cd692015-07-14 09:33:13 +00002840__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002841 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002842
Tobias Grosser808cd692015-07-14 09:33:13 +00002843 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002844 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002845
2846 return Domain;
2847}
2848
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002849__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002850 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002851
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002852 for (ScopStmt &Stmt : *this) {
2853 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002854 if (!MA->isMustWrite())
2855 continue;
2856
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002857 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002858 isl_map *AccessDomain = MA->getAccessRelation();
2859 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2860 Write = isl_union_map_add_map(Write, AccessDomain);
2861 }
2862 }
2863 return isl_union_map_coalesce(Write);
2864}
2865
2866__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002867 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002868
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002869 for (ScopStmt &Stmt : *this) {
2870 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002871 if (!MA->isMayWrite())
2872 continue;
2873
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002874 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002875 isl_map *AccessDomain = MA->getAccessRelation();
2876 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2877 Write = isl_union_map_add_map(Write, AccessDomain);
2878 }
2879 }
2880 return isl_union_map_coalesce(Write);
2881}
2882
Tobias Grosser37eb4222014-02-20 21:43:54 +00002883__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002884 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002885
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002886 for (ScopStmt &Stmt : *this) {
2887 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002888 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002889 continue;
2890
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002891 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002892 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002893 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2894 Write = isl_union_map_add_map(Write, AccessDomain);
2895 }
2896 }
2897 return isl_union_map_coalesce(Write);
2898}
2899
2900__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002901 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002902
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002903 for (ScopStmt &Stmt : *this) {
2904 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002905 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002906 continue;
2907
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002908 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002909 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002910
2911 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2912 Read = isl_union_map_add_map(Read, AccessDomain);
2913 }
2914 }
2915 return isl_union_map_coalesce(Read);
2916}
2917
Tobias Grosser808cd692015-07-14 09:33:13 +00002918__isl_give isl_union_map *Scop::getSchedule() const {
2919 auto Tree = getScheduleTree();
2920 auto S = isl_schedule_get_map(Tree);
2921 isl_schedule_free(Tree);
2922 return S;
2923}
Tobias Grosser37eb4222014-02-20 21:43:54 +00002924
Tobias Grosser808cd692015-07-14 09:33:13 +00002925__isl_give isl_schedule *Scop::getScheduleTree() const {
2926 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
2927 getDomains());
2928}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002929
Tobias Grosser808cd692015-07-14 09:33:13 +00002930void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
2931 auto *S = isl_schedule_from_domain(getDomains());
2932 S = isl_schedule_insert_partial_schedule(
2933 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
2934 isl_schedule_free(Schedule);
2935 Schedule = S;
2936}
2937
2938void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
2939 isl_schedule_free(Schedule);
2940 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00002941}
2942
2943bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
2944 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002945 for (ScopStmt &Stmt : *this) {
2946 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002947 isl_union_set *NewStmtDomain = isl_union_set_intersect(
2948 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
2949
2950 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
2951 isl_union_set_free(StmtDomain);
2952 isl_union_set_free(NewStmtDomain);
2953 continue;
2954 }
2955
2956 Changed = true;
2957
2958 isl_union_set_free(StmtDomain);
2959 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
2960
2961 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002962 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002963 isl_union_set_free(NewStmtDomain);
2964 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002965 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002966 }
2967 isl_union_set_free(Domain);
2968 return Changed;
2969}
2970
Tobias Grosser75805372011-04-29 06:27:02 +00002971ScalarEvolution *Scop::getSE() const { return SE; }
2972
Johannes Doerfertf5673802015-10-01 23:48:18 +00002973bool Scop::isIgnored(RegionNode *RN) {
2974 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser75805372011-04-29 06:27:02 +00002975
Johannes Doerfertf5673802015-10-01 23:48:18 +00002976 // Check if there are accesses contained.
2977 bool ContainsAccesses = false;
2978 if (!RN->isSubRegion())
2979 ContainsAccesses = getAccessFunctions(BB);
2980 else
2981 for (BasicBlock *RBB : RN->getNodeAs<Region>()->blocks())
2982 ContainsAccesses |= (getAccessFunctions(RBB) != nullptr);
2983 if (!ContainsAccesses)
2984 return true;
2985
2986 // Check for reachability via non-error blocks.
2987 if (!DomainMap.count(BB))
2988 return true;
2989
2990 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002991 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002992 return true;
2993
2994 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00002995}
2996
Tobias Grosser808cd692015-07-14 09:33:13 +00002997struct MapToDimensionDataTy {
2998 int N;
2999 isl_union_pw_multi_aff *Res;
3000};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003001
Tobias Grosser808cd692015-07-14 09:33:13 +00003002// @brief Create a function that maps the elements of 'Set' to its N-th
3003// dimension.
3004//
3005// The result is added to 'User->Res'.
3006//
3007// @param Set The input set.
3008// @param N The dimension to map to.
3009//
3010// @returns Zero if no error occurred, non-zero otherwise.
3011static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3012 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3013 int Dim;
3014 isl_space *Space;
3015 isl_pw_multi_aff *PMA;
3016
3017 Dim = isl_set_dim(Set, isl_dim_set);
3018 Space = isl_set_get_space(Set);
3019 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3020 Dim - Data->N);
3021 if (Data->N > 1)
3022 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3023 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3024
3025 isl_set_free(Set);
3026
3027 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003028}
3029
Tobias Grosser808cd692015-07-14 09:33:13 +00003030// @brief Create a function that maps the elements of Domain to their Nth
3031// dimension.
3032//
3033// @param Domain The set of elements to map.
3034// @param N The dimension to map to.
3035static __isl_give isl_multi_union_pw_aff *
3036mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003037 if (N <= 0 || isl_union_set_is_empty(Domain)) {
3038 isl_union_set_free(Domain);
3039 return nullptr;
3040 }
3041
Tobias Grosser808cd692015-07-14 09:33:13 +00003042 struct MapToDimensionDataTy Data;
3043 isl_space *Space;
3044
3045 Space = isl_union_set_get_space(Domain);
3046 Data.N = N;
3047 Data.Res = isl_union_pw_multi_aff_empty(Space);
3048 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
3049 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
3050
3051 isl_union_set_free(Domain);
3052 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3053}
3054
Michael Kruse9d080092015-09-11 21:41:48 +00003055ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003056 ScopStmt *Stmt;
3057 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003058 Stmts.emplace_back(*this, *BB);
Tobias Grosser808cd692015-07-14 09:33:13 +00003059 Stmt = &Stmts.back();
3060 StmtMap[BB] = Stmt;
3061 } else {
3062 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003063 Stmts.emplace_back(*this, *R);
Tobias Grosser808cd692015-07-14 09:33:13 +00003064 Stmt = &Stmts.back();
3065 for (BasicBlock *BB : R->blocks())
3066 StmtMap[BB] = Stmt;
3067 }
3068 return Stmt;
3069}
3070
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003071void Scop::buildSchedule(
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003072 Region *R,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003073 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00003074
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003075 if (SD.isNonAffineSubRegion(R, &getRegion())) {
Johannes Doerfertc6987c12015-09-26 13:41:43 +00003076 Loop *L = getLoopSurroundingRegion(*R, LI);
3077 auto &LSchedulePair = LoopSchedules[L];
Michael Krusecac948e2015-10-02 13:53:07 +00003078 ScopStmt *Stmt = getStmtForBasicBlock(R->getEntry());
Michael Kruseafe06702015-10-02 16:33:27 +00003079 isl_set *Domain = Stmt->getDomain();
Michael Krusecac948e2015-10-02 13:53:07 +00003080 auto *UDomain = isl_union_set_from_set(Domain);
3081 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003082 LSchedulePair.first = StmtSchedule;
3083 return;
3084 }
3085
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003086 ReversePostOrderTraversal<Region *> RTraversal(R);
3087 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00003088
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003089 if (RN->isSubRegion()) {
3090 Region *SubRegion = RN->getNodeAs<Region>();
3091 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003092 buildSchedule(SubRegion, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003093 continue;
3094 }
Tobias Grosser75805372011-04-29 06:27:02 +00003095 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003096
3097 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert30c22652015-10-18 21:17:11 +00003098 if (!getRegion().contains(L))
3099 L = getLoopSurroundingRegion(getRegion(), LI);
3100
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003101 int LD = getRelativeLoopDepth(L);
3102 auto &LSchedulePair = LoopSchedules[L];
3103 LSchedulePair.second += getNumBlocksInRegionNode(RN);
3104
Michael Krusecac948e2015-10-02 13:53:07 +00003105 BasicBlock *BB = getRegionNodeBasicBlock(RN);
3106 ScopStmt *Stmt = getStmtForBasicBlock(BB);
3107 if (Stmt) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003108 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3109 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
3110 LSchedulePair.first =
3111 combineInSequence(LSchedulePair.first, StmtSchedule);
3112 }
3113
3114 unsigned NumVisited = LSchedulePair.second;
3115 while (L && NumVisited == L->getNumBlocks()) {
3116 auto *LDomain = isl_schedule_get_domain(LSchedulePair.first);
3117 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
3118 LSchedulePair.first =
3119 isl_schedule_insert_partial_schedule(LSchedulePair.first, MUPA);
3120
3121 auto *PL = L->getParentLoop();
3122 assert(LoopSchedules.count(PL));
3123 auto &PSchedulePair = LoopSchedules[PL];
3124 PSchedulePair.first =
3125 combineInSequence(PSchedulePair.first, LSchedulePair.first);
3126 PSchedulePair.second += NumVisited;
3127
3128 L = PL;
3129 NumVisited = PSchedulePair.second;
3130 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003131 }
Tobias Grosser75805372011-04-29 06:27:02 +00003132}
3133
Johannes Doerfert7c494212014-10-31 23:13:39 +00003134ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003135 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003136 if (StmtMapIt == StmtMap.end())
3137 return nullptr;
3138 return StmtMapIt->second;
3139}
3140
Johannes Doerfert96425c22015-08-30 21:13:53 +00003141int Scop::getRelativeLoopDepth(const Loop *L) const {
3142 Loop *OuterLoop =
3143 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3144 if (!OuterLoop)
3145 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003146 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3147}
3148
Michael Krused868b5d2015-09-10 15:25:24 +00003149void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003150 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003151
3152 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3153 // true, are not modeled as ordinary PHI nodes as they are not part of the
3154 // region. However, we model the operands in the predecessor blocks that are
3155 // part of the region as regular scalar accesses.
3156
3157 // If we can synthesize a PHI we can skip it, however only if it is in
3158 // the region. If it is not it can only be in the exit block of the region.
3159 // In this case we model the operands but not the PHI itself.
3160 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3161 return;
3162
3163 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3164 // detection. Hence, the PHI is a load of a new memory location in which the
3165 // incoming value was written at the end of the incoming basic block.
3166 bool OnlyNonAffineSubRegionOperands = true;
3167 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3168 Value *Op = PHI->getIncomingValue(u);
3169 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3170
3171 // Do not build scalar dependences inside a non-affine subregion.
3172 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3173 continue;
3174
3175 OnlyNonAffineSubRegionOperands = false;
3176
3177 if (!R.contains(OpBB))
3178 continue;
3179
3180 Instruction *OpI = dyn_cast<Instruction>(Op);
3181 if (OpI) {
3182 BasicBlock *OpIBB = OpI->getParent();
3183 // As we pretend there is a use (or more precise a write) of OpI in OpBB
3184 // we have to insert a scalar dependence from the definition of OpI to
3185 // OpBB if the definition is not in OpBB.
Michael Kruse668af712015-10-15 14:45:48 +00003186 if (scop->getStmtForBasicBlock(OpIBB) !=
3187 scop->getStmtForBasicBlock(OpBB)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003188 addScalarReadAccess(OpI, PHI, OpBB);
3189 addScalarWriteAccess(OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003190 }
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003191 } else if (ModelReadOnlyScalars && !isa<Constant>(Op)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003192 addScalarReadAccess(Op, PHI, OpBB);
Michael Kruse7bf39442015-09-10 12:46:52 +00003193 }
3194
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003195 addPHIWriteAccess(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003196 }
3197
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003198 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3199 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003200 }
3201}
3202
Michael Krused868b5d2015-09-10 15:25:24 +00003203bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
3204 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003205 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
3206 if (isIgnoredIntrinsic(Inst))
3207 return false;
3208
3209 bool AnyCrossStmtUse = false;
3210 BasicBlock *ParentBB = Inst->getParent();
3211
3212 for (User *U : Inst->users()) {
3213 Instruction *UI = dyn_cast<Instruction>(U);
3214
3215 // Ignore the strange user
3216 if (UI == 0)
3217 continue;
3218
3219 BasicBlock *UseParent = UI->getParent();
3220
Tobias Grosserbaffa092015-10-24 20:55:27 +00003221 // Ignore basic block local uses. A value that is defined in a scop, but
3222 // used in a PHI node in the same basic block does not count as basic block
3223 // local, as for such cases a control flow edge is passed between definition
3224 // and use.
3225 if (UseParent == ParentBB && !isa<PHINode>(UI))
Michael Kruse7bf39442015-09-10 12:46:52 +00003226 continue;
3227
3228 // Do not build scalar dependences inside a non-affine subregion.
3229 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
3230 continue;
3231
Michael Kruse01cb3792015-10-17 21:07:08 +00003232 // Check for PHI nodes in the region exit and skip them, if they will be
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003233 // modeled as PHI nodes.
Michael Kruse01cb3792015-10-17 21:07:08 +00003234 //
3235 // PHI nodes in the region exit that have more than two incoming edges need
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003236 // to be modeled as PHI-Nodes to correctly model the fact that depending on
3237 // the control flow a different value will be assigned to the PHI node. In
3238 // case this is the case, there is no need to create an additional normal
3239 // scalar dependence. Hence, bail out before we register an "out-of-region"
3240 // use for this definition.
Michael Kruse01cb3792015-10-17 21:07:08 +00003241 if (isa<PHINode>(UI) && UI->getParent() == R->getExit() &&
3242 !R->getExitingBlock())
3243 continue;
3244
Michael Kruse7bf39442015-09-10 12:46:52 +00003245 // Check whether or not the use is in the SCoP.
Tobias Grosserc73d8b02015-10-23 22:36:22 +00003246 if (!R->contains(UseParent)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003247 AnyCrossStmtUse = true;
3248 continue;
3249 }
3250
Tobias Grosserbaffa092015-10-24 20:55:27 +00003251 // Uses by PHI nodes in the entry node count as external uses in case the
3252 // use is through an incoming block that is itself not contained in the
3253 // region.
3254 if (R->getEntry() == UseParent) {
3255 if (auto *PHI = dyn_cast<PHINode>(UI)) {
3256 bool ExternalUse = false;
3257 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
3258 if (PHI->getIncomingValue(i) == Inst &&
3259 !R->contains(PHI->getIncomingBlock(i))) {
3260 ExternalUse = true;
3261 break;
3262 }
3263 }
3264
3265 if (ExternalUse) {
3266 AnyCrossStmtUse = true;
3267 continue;
3268 }
3269 }
3270 }
3271
Michael Kruse7bf39442015-09-10 12:46:52 +00003272 // If the instruction can be synthesized and the user is in the region
3273 // we do not need to add scalar dependences.
3274 if (canSynthesizeInst)
3275 continue;
3276
3277 // No need to translate these scalar dependences into polyhedral form,
3278 // because synthesizable scalars can be generated by the code generator.
3279 if (canSynthesize(UI, LI, SE, R))
3280 continue;
3281
3282 // Skip PHI nodes in the region as they handle their operands on their own.
3283 if (isa<PHINode>(UI))
3284 continue;
3285
3286 // Now U is used in another statement.
3287 AnyCrossStmtUse = true;
3288
3289 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00003290 // Use the def instruction as base address of the MemoryAccess, so that it
3291 // will become the name of the scalar access in the polyhedral form.
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003292 addScalarReadAccess(Inst, UI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003293 }
3294
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003295 if (ModelReadOnlyScalars && !isa<PHINode>(Inst)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003296 for (Value *Op : Inst->operands()) {
3297 if (canSynthesize(Op, LI, SE, R))
3298 continue;
3299
3300 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
3301 if (R->contains(OpInst))
3302 continue;
3303
3304 if (isa<Constant>(Op))
3305 continue;
3306
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003307 addScalarReadAccess(Op, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003308 }
3309 }
3310
3311 return AnyCrossStmtUse;
3312}
3313
3314extern MapInsnToMemAcc InsnToMemAcc;
3315
Michael Krusee2bccbb2015-09-18 19:59:43 +00003316void ScopInfo::buildMemoryAccess(
3317 Instruction *Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003318 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3319 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003320 unsigned Size;
3321 Type *SizeType;
3322 Value *Val;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003323 enum MemoryAccess::AccessType Type;
Michael Kruse7bf39442015-09-10 12:46:52 +00003324
3325 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
3326 SizeType = Load->getType();
3327 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003328 Type = MemoryAccess::READ;
Michael Kruse7bf39442015-09-10 12:46:52 +00003329 Val = Load;
3330 } else {
3331 StoreInst *Store = cast<StoreInst>(Inst);
3332 SizeType = Store->getValueOperand()->getType();
3333 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003334 Type = MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003335 Val = Store->getValueOperand();
3336 }
3337
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003338 auto Address = getPointerOperand(*Inst);
3339
3340 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003341 const SCEVUnknown *BasePointer =
3342 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3343
3344 assert(BasePointer && "Could not find base pointer");
3345 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
3346
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003347 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3348 auto NewAddress = Address;
3349 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3350 auto Src = BitCast->getOperand(0);
3351 auto SrcTy = Src->getType();
3352 auto DstTy = BitCast->getType();
3353 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3354 NewAddress = Src;
3355 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003356
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003357 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3358 std::vector<const SCEV *> Subscripts;
3359 std::vector<int> Sizes;
3360 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3361 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003362
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003363 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003364
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003365 bool AllAffineSubcripts = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003366 for (auto Subscript : Subscripts) {
3367 InvariantLoadsSetTy AccessILS;
3368 AllAffineSubcripts =
3369 isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS);
3370
3371 for (LoadInst *LInst : AccessILS)
3372 if (!ScopRIL.count(LInst))
3373 AllAffineSubcripts = false;
3374
3375 if (!AllAffineSubcripts)
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003376 break;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003377 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003378
3379 if (AllAffineSubcripts && Sizes.size() > 0) {
3380 for (auto V : Sizes)
3381 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3382 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003383 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003384 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003385
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003386 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3387 Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00003388 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003389 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003390 }
3391 }
3392
Michael Kruse7bf39442015-09-10 12:46:52 +00003393 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003394 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003395 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3396 AccItr->second.DelinearizedSubscripts,
3397 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003398 return;
3399 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003400
3401 // Check if the access depends on a loop contained in a non-affine subregion.
3402 bool isVariantInNonAffineLoop = false;
3403 if (BoxedLoops) {
3404 SetVector<const Loop *> Loops;
3405 findLoops(AccessFunction, Loops);
3406 for (const Loop *L : Loops)
3407 if (BoxedLoops->count(L))
3408 isVariantInNonAffineLoop = true;
3409 }
3410
Johannes Doerfert09e36972015-10-07 20:17:36 +00003411 InvariantLoadsSetTy AccessILS;
3412 bool IsAffine =
3413 !isVariantInNonAffineLoop &&
3414 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3415
3416 for (LoadInst *LInst : AccessILS)
3417 if (!ScopRIL.count(LInst))
3418 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003419
Michael Krusecaac2b62015-09-26 15:51:44 +00003420 // FIXME: Size of the number of bytes of an array element, not the number of
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003421 // elements as probably intended here.
Tobias Grossera43b6e92015-09-27 17:54:50 +00003422 const SCEV *SizeSCEV =
3423 SE->getConstant(TD->getIntPtrType(Inst->getContext()), Size);
Michael Kruse7bf39442015-09-10 12:46:52 +00003424
Michael Krusee2bccbb2015-09-18 19:59:43 +00003425 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3426 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003427
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003428 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, IsAffine,
3429 ArrayRef<const SCEV *>(AccessFunction),
3430 ArrayRef<const SCEV *>(SizeSCEV), Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003431}
3432
Michael Krused868b5d2015-09-10 15:25:24 +00003433void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003434
3435 if (SD->isNonAffineSubRegion(&SR, &R)) {
3436 for (BasicBlock *BB : SR.blocks())
3437 buildAccessFunctions(R, *BB, &SR);
3438 return;
3439 }
3440
3441 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3442 if (I->isSubRegion())
3443 buildAccessFunctions(R, *I->getNodeAs<Region>());
3444 else
3445 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
3446}
3447
Michael Krusecac948e2015-10-02 13:53:07 +00003448void ScopInfo::buildStmts(Region &SR) {
3449 Region *R = getRegion();
3450
3451 if (SD->isNonAffineSubRegion(&SR, R)) {
3452 scop->addScopStmt(nullptr, &SR);
3453 return;
3454 }
3455
3456 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3457 if (I->isSubRegion())
3458 buildStmts(*I->getNodeAs<Region>());
3459 else
3460 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
3461}
3462
Michael Krused868b5d2015-09-10 15:25:24 +00003463void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
3464 Region *NonAffineSubRegion,
3465 bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003466 Loop *L = LI->getLoopFor(&BB);
3467
3468 // The set of loops contained in non-affine subregions that are part of R.
3469 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3470
Johannes Doerfert09e36972015-10-07 20:17:36 +00003471 // The set of loads that are required to be invariant.
3472 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
3473
Michael Kruse7bf39442015-09-10 12:46:52 +00003474 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
3475 Instruction *Inst = I;
3476
3477 PHINode *PHI = dyn_cast<PHINode>(Inst);
3478 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003479 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003480
3481 // For the exit block we stop modeling after the last PHI node.
3482 if (!PHI && IsExitBlock)
3483 break;
3484
Johannes Doerfert09e36972015-10-07 20:17:36 +00003485 // TODO: At this point we only know that elements of ScopRIL have to be
3486 // invariant and will be hoisted for the SCoP to be processed. Though,
3487 // there might be other invariant accesses that will be hoisted and
3488 // that would allow to make a non-affine access affine.
Michael Kruse7bf39442015-09-10 12:46:52 +00003489 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
Johannes Doerfert09e36972015-10-07 20:17:36 +00003490 buildMemoryAccess(Inst, L, &R, BoxedLoops, ScopRIL);
Michael Kruse7bf39442015-09-10 12:46:52 +00003491
3492 if (isIgnoredIntrinsic(Inst))
3493 continue;
3494
Johannes Doerfert09e36972015-10-07 20:17:36 +00003495 // Do not build scalar dependences for required invariant loads as we will
3496 // hoist them later on anyway or drop the SCoP if we cannot.
3497 if (ScopRIL.count(dyn_cast<LoadInst>(Inst)))
3498 continue;
3499
Michael Kruse7bf39442015-09-10 12:46:52 +00003500 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00003501 if (!isa<StoreInst>(Inst))
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003502 addScalarWriteAccess(Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003503 }
3504 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003505}
Michael Kruse7bf39442015-09-10 12:46:52 +00003506
Michael Kruse2d0ece92015-09-24 11:41:21 +00003507void ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3508 MemoryAccess::AccessType Type,
3509 Value *BaseAddress, unsigned ElemBytes,
3510 bool Affine, Value *AccessValue,
3511 ArrayRef<const SCEV *> Subscripts,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003512 ArrayRef<const SCEV *> Sizes,
3513 MemoryAccess::AccessOrigin Origin) {
Michael Krusecac948e2015-10-02 13:53:07 +00003514 ScopStmt *Stmt = scop->getStmtForBasicBlock(BB);
3515
3516 // Do not create a memory access for anything not in the SCoP. It would be
3517 // ignored anyway.
3518 if (!Stmt)
3519 return;
3520
Michael Krusee2bccbb2015-09-18 19:59:43 +00003521 AccFuncSetType &AccList = AccFuncMap[BB];
3522 size_t Identifier = AccList.size();
Michael Kruse7bf39442015-09-10 12:46:52 +00003523
Michael Krusee2bccbb2015-09-18 19:59:43 +00003524 Value *BaseAddr = BaseAddress;
3525 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3526
3527 std::string IdName = "__polly_array_ref_" + std::to_string(Identifier);
3528 isl_id *Id = isl_id_alloc(ctx, IdName.c_str(), nullptr);
3529
Michael Krusecac948e2015-10-02 13:53:07 +00003530 bool isApproximated =
3531 Stmt->isRegionStmt() && (Stmt->getRegion()->getEntry() != BB);
3532 if (isApproximated && Type == MemoryAccess::MUST_WRITE)
3533 Type = MemoryAccess::MAY_WRITE;
3534
3535 AccList.emplace_back(Stmt, Inst, Id, Type, BaseAddress, ElemBytes, Affine,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003536 Subscripts, Sizes, AccessValue, Origin, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00003537 Stmt->addAccess(&AccList.back());
Michael Kruse7bf39442015-09-10 12:46:52 +00003538}
3539
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003540void ScopInfo::addExplicitAccess(
3541 Instruction *MemAccInst, MemoryAccess::AccessType Type, Value *BaseAddress,
3542 unsigned ElemBytes, bool IsAffine, ArrayRef<const SCEV *> Subscripts,
3543 ArrayRef<const SCEV *> Sizes, Value *AccessValue) {
3544 assert(isa<LoadInst>(MemAccInst) || isa<StoreInst>(MemAccInst));
3545 assert(isa<LoadInst>(MemAccInst) == (Type == MemoryAccess::READ));
3546 addMemoryAccess(MemAccInst->getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003547 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
3548 MemoryAccess::EXPLICIT);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003549}
3550void ScopInfo::addScalarWriteAccess(Instruction *Value) {
3551 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
3552 true, Value, ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003553 ArrayRef<const SCEV *>(), MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003554}
3555void ScopInfo::addScalarReadAccess(Value *Value, Instruction *User) {
3556 assert(!isa<PHINode>(User));
3557 addMemoryAccess(User->getParent(), User, MemoryAccess::READ, Value, 1, true,
3558 Value, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003559 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003560}
3561void ScopInfo::addScalarReadAccess(Value *Value, PHINode *User,
3562 BasicBlock *UserBB) {
3563 addMemoryAccess(UserBB, User, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003564 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3565 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003566}
3567void ScopInfo::addPHIWriteAccess(PHINode *PHI, BasicBlock *IncomingBlock,
3568 Value *IncomingValue, bool IsExitBlock) {
3569 addMemoryAccess(IncomingBlock, IncomingBlock->getTerminator(),
3570 MemoryAccess::MUST_WRITE, PHI, 1, true, IncomingValue,
3571 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003572 IsExitBlock ? MemoryAccess::SCALAR : MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003573}
3574void ScopInfo::addPHIReadAccess(PHINode *PHI) {
3575 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003576 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3577 MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003578}
3579
Michael Kruse76e924d2015-09-30 09:16:07 +00003580void ScopInfo::buildScop(Region &R, DominatorTree &DT) {
Michael Kruse9d080092015-09-11 21:41:48 +00003581 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003582 scop = new Scop(R, AccFuncMap, *SD, *SE, DT, *LI, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00003583
Michael Krusecac948e2015-10-02 13:53:07 +00003584 buildStmts(R);
Michael Kruse7bf39442015-09-10 12:46:52 +00003585 buildAccessFunctions(R, R);
3586
3587 // In case the region does not have an exiting block we will later (during
3588 // code generation) split the exit block. This will move potential PHI nodes
3589 // from the current exit block into the new region exiting block. Hence, PHI
3590 // nodes that are at this point not part of the region will be.
3591 // To handle these PHI nodes later we will now model their operands as scalar
3592 // accesses. Note that we do not model anything in the exit block if we have
3593 // an exiting block in the region, as there will not be any splitting later.
3594 if (!R.getExitingBlock())
3595 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
3596
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003597 scop->init(*AA);
Michael Kruse7bf39442015-09-10 12:46:52 +00003598}
3599
Michael Krused868b5d2015-09-10 15:25:24 +00003600void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00003601 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00003602 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00003603 return;
3604 }
3605
Michael Kruse9d080092015-09-11 21:41:48 +00003606 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00003607}
3608
Michael Krused868b5d2015-09-10 15:25:24 +00003609void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00003610 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00003611 if (scop) {
3612 delete scop;
3613 scop = 0;
3614 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003615}
3616
3617//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00003618ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00003619 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00003620 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00003621}
3622
3623ScopInfo::~ScopInfo() {
3624 clear();
3625 isl_ctx_free(ctx);
3626}
3627
Tobias Grosser75805372011-04-29 06:27:02 +00003628void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00003629 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00003630 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00003631 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00003632 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
3633 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003634 AU.addRequired<AAResultsWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00003635 AU.setPreservesAll();
3636}
3637
3638bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00003639 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00003640
Michael Krused868b5d2015-09-10 15:25:24 +00003641 if (!SD->isMaxRegionInScop(*R))
3642 return false;
3643
3644 Function *F = R->getEntry()->getParent();
3645 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3646 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3647 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3648 TD = &F->getParent()->getDataLayout();
3649 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Krused868b5d2015-09-10 15:25:24 +00003650
Michael Kruse76e924d2015-09-30 09:16:07 +00003651 buildScop(*R, DT);
Tobias Grosser75805372011-04-29 06:27:02 +00003652
Tobias Grosserd6a50b32015-05-30 06:26:21 +00003653 DEBUG(scop->print(dbgs()));
3654
Michael Kruseafe06702015-10-02 16:33:27 +00003655 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003656 delete scop;
3657 scop = nullptr;
3658 return false;
3659 }
3660
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003661 // Statistics.
3662 ++ScopFound;
3663 if (scop->getMaxLoopDepth() > 0)
3664 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00003665 return false;
3666}
3667
3668char ScopInfo::ID = 0;
3669
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003670Pass *polly::createScopInfoPass() { return new ScopInfo(); }
3671
Tobias Grosser73600b82011-10-08 00:30:40 +00003672INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
3673 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003674 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003675INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00003676INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00003677INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00003678INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003679INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003680INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00003681INITIALIZE_PASS_END(ScopInfo, "polly-scops",
3682 "Polly - Create polyhedral description of Scops", false,
3683 false)