blob: 0a6394d125691b69c5e3fe7cdaa24267c39c9b70 [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"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000021#include "polly/CodeGen/BlockGenerators.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000022#include "polly/Options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000023#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000024#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000025#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000026#include "polly/Support/ScopHelper.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000027#include "llvm/ADT/MapVector.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000028#include "llvm/ADT/PostOrderIterator.h"
29#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000030#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000031#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000032#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000033#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000034#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000035#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000036#include "llvm/Analysis/RegionIterator.h"
37#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser75805372011-04-29 06:27:02 +000038#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000039#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000040#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000041#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000042#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000043#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000044#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000045#include "isl/schedule.h"
46#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000047#include "isl/set.h"
48#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000049#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000050#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000051#include <sstream>
52#include <string>
53#include <vector>
54
55using namespace llvm;
56using namespace polly;
57
Chandler Carruth95fef942014-04-22 03:30:19 +000058#define DEBUG_TYPE "polly-scops"
59
Tobias Grosser74394f02013-01-14 22:40:23 +000060STATISTIC(ScopFound, "Number of valid Scops");
61STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000062
Michael Kruse7bf39442015-09-10 12:46:52 +000063static cl::opt<bool> ModelReadOnlyScalars(
64 "polly-analyze-read-only-scalars",
65 cl::desc("Model read-only scalar values in the scop description"),
66 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
67
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000068// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000069// operations can overflow easily. Additive reductions and bit operations
70// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000071static cl::opt<bool> DisableMultiplicativeReductions(
72 "polly-disable-multiplicative-reductions",
73 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
74 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000075
Johannes Doerfert9143d672014-09-27 11:02:39 +000076static cl::opt<unsigned> RunTimeChecksMaxParameters(
77 "polly-rtc-max-parameters",
78 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
79 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
80
Tobias Grosser71500722015-03-28 15:11:14 +000081static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
82 "polly-rtc-max-arrays-per-group",
83 cl::desc("The maximal number of arrays to compare in each alias group."),
84 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000085static cl::opt<std::string> UserContextStr(
86 "polly-context", cl::value_desc("isl parameter set"),
87 cl::desc("Provide additional constraints on the context parameters"),
88 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000089
Tobias Grosserd83b8a82015-08-20 19:08:11 +000090static cl::opt<bool> DetectReductions("polly-detect-reductions",
91 cl::desc("Detect and exploit reductions"),
92 cl::Hidden, cl::ZeroOrMore,
93 cl::init(true), cl::cat(PollyCategory));
94
Michael Kruse7bf39442015-09-10 12:46:52 +000095//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +000096
Michael Kruse046dde42015-08-10 13:01:57 +000097// Create a sequence of two schedules. Either argument may be null and is
98// interpreted as the empty schedule. Can also return null if both schedules are
99// empty.
100static __isl_give isl_schedule *
101combineInSequence(__isl_take isl_schedule *Prev,
102 __isl_take isl_schedule *Succ) {
103 if (!Prev)
104 return Succ;
105 if (!Succ)
106 return Prev;
107
108 return isl_schedule_sequence(Prev, Succ);
109}
110
Johannes Doerferte7044942015-02-24 11:58:30 +0000111static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
112 const ConstantRange &Range,
113 int dim,
114 enum isl_dim_type type) {
115 isl_val *V;
116 isl_ctx *ctx = isl_set_get_ctx(S);
117
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000118 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
119 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000120 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000121 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
122
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000123 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000124 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000125 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000126 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000127 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
128
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000129 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000130 return isl_set_union(SLB, SUB);
131 else
132 return isl_set_intersect(SLB, SUB);
133}
134
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000135static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
136 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
137 if (!BasePtrLI)
138 return nullptr;
139
140 if (!S->getRegion().contains(BasePtrLI))
141 return nullptr;
142
143 ScalarEvolution &SE = *S->getSE();
144
145 auto *OriginBaseSCEV =
146 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
147 if (!OriginBaseSCEV)
148 return nullptr;
149
150 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
151 if (!OriginBaseSCEVUnknown)
152 return nullptr;
153
154 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue());
155}
156
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000157ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000158 ArrayRef<const SCEV *> Sizes, bool IsPHI, Scop *S)
159 : BasePtr(BasePtr), ElementType(ElementType), IsPHI(IsPHI), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000160 std::string BasePtrName =
161 getIslCompatibleName("MemRef_", BasePtr, IsPHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000162 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000163
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000164 updateSizes(Sizes);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000165 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
166 if (BasePtrOriginSAI)
167 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000168}
169
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000170__isl_give isl_space *ScopArrayInfo::getSpace() const {
171 auto Space =
172 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
173 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
174 return Space;
175}
176
177void ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
178#ifndef NDEBUG
179 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
180 int ExtraDimsNew = NewSizes.size() - SharedDims;
181 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
182 for (int i = 0; i < SharedDims; i++) {
183 assert(NewSizes[i + ExtraDimsNew] == DimensionSizes[i + ExtraDimsOld] &&
184 "Array update with non-matching dimension sizes");
185 }
186#endif
187
188 DimensionSizes.clear();
189 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
190 NewSizes.end());
191 for (isl_pw_aff *Size : DimensionSizesPw)
192 isl_pw_aff_free(Size);
193 DimensionSizesPw.clear();
194 for (const SCEV *Expr : DimensionSizes) {
195 isl_pw_aff *Size = S.getPwAff(Expr);
196 DimensionSizesPw.push_back(Size);
197 }
198}
199
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000200ScopArrayInfo::~ScopArrayInfo() {
201 isl_id_free(Id);
202 for (isl_pw_aff *Size : DimensionSizesPw)
203 isl_pw_aff_free(Size);
204}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000205
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000206std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
207
208int ScopArrayInfo::getElemSizeInBytes() const {
209 return ElementType->getPrimitiveSizeInBits() / 8;
210}
211
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000212isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
213
214void ScopArrayInfo::dump() const { print(errs()); }
215
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000216void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000217 OS.indent(8) << *getElementType() << " " << getName() << "[*]";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000218 for (unsigned u = 0; u < getNumberOfDimensions(); u++) {
219 OS << "[";
220
221 if (SizeAsPwAff)
222 OS << " " << DimensionSizesPw[u] << " ";
223 else
224 OS << *DimensionSizes[u];
225
226 OS << "]";
227 }
228
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000229 if (BasePtrOriginSAI)
230 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
231
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000232 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000233}
234
235const ScopArrayInfo *
236ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
237 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
238 assert(Id && "Output dimension didn't have an ID");
239 return getFromId(Id);
240}
241
242const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
243 void *User = isl_id_get_user(Id);
244 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
245 isl_id_free(Id);
246 return SAI;
247}
248
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000249void MemoryAccess::updateDimensionality() {
250 auto ArraySpace = getScopArrayInfo()->getSpace();
251 auto AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
252
253 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
254 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
255 auto DimsMissing = DimsArray - DimsAccess;
256
257 auto Map = isl_map_from_domain_and_range(isl_set_universe(AccessSpace),
258 isl_set_universe(ArraySpace));
259
260 for (unsigned i = 0; i < DimsMissing; i++)
261 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
262
263 for (unsigned i = DimsMissing; i < DimsArray; i++)
264 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
265
266 AccessRelation = isl_map_apply_range(AccessRelation, Map);
267}
268
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000269const std::string
270MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
271 switch (RT) {
272 case MemoryAccess::RT_NONE:
273 llvm_unreachable("Requested a reduction operator string for a memory "
274 "access which isn't a reduction");
275 case MemoryAccess::RT_ADD:
276 return "+";
277 case MemoryAccess::RT_MUL:
278 return "*";
279 case MemoryAccess::RT_BOR:
280 return "|";
281 case MemoryAccess::RT_BXOR:
282 return "^";
283 case MemoryAccess::RT_BAND:
284 return "&";
285 }
286 llvm_unreachable("Unknown reduction type");
287 return "";
288}
289
Johannes Doerfertf6183392014-07-01 20:52:51 +0000290/// @brief Return the reduction type for a given binary operator
291static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
292 const Instruction *Load) {
293 if (!BinOp)
294 return MemoryAccess::RT_NONE;
295 switch (BinOp->getOpcode()) {
296 case Instruction::FAdd:
297 if (!BinOp->hasUnsafeAlgebra())
298 return MemoryAccess::RT_NONE;
299 // Fall through
300 case Instruction::Add:
301 return MemoryAccess::RT_ADD;
302 case Instruction::Or:
303 return MemoryAccess::RT_BOR;
304 case Instruction::Xor:
305 return MemoryAccess::RT_BXOR;
306 case Instruction::And:
307 return MemoryAccess::RT_BAND;
308 case Instruction::FMul:
309 if (!BinOp->hasUnsafeAlgebra())
310 return MemoryAccess::RT_NONE;
311 // Fall through
312 case Instruction::Mul:
313 if (DisableMultiplicativeReductions)
314 return MemoryAccess::RT_NONE;
315 return MemoryAccess::RT_MUL;
316 default:
317 return MemoryAccess::RT_NONE;
318 }
319}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000320
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000321/// @brief Derive the individual index expressions from a GEP instruction
322///
323/// This function optimistically assumes the GEP references into a fixed size
324/// array. If this is actually true, this function returns a list of array
325/// subscript expressions as SCEV as well as a list of integers describing
326/// the size of the individual array dimensions. Both lists have either equal
327/// length of the size list is one element shorter in case there is no known
328/// size available for the outermost array dimension.
329///
330/// @param GEP The GetElementPtr instruction to analyze.
331///
332/// @return A tuple with the subscript expressions and the dimension sizes.
333static std::tuple<std::vector<const SCEV *>, std::vector<int>>
334getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
335 std::vector<const SCEV *> Subscripts;
336 std::vector<int> Sizes;
337
338 Type *Ty = GEP->getPointerOperandType();
339
340 bool DroppedFirstDim = false;
341
Michael Kruse26ed65e2015-09-24 17:32:49 +0000342 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000343
344 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
345
346 if (i == 1) {
347 if (auto PtrTy = dyn_cast<PointerType>(Ty)) {
348 Ty = PtrTy->getElementType();
349 } else if (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
350 Ty = ArrayTy->getElementType();
351 } else {
352 Subscripts.clear();
353 Sizes.clear();
354 break;
355 }
356 if (auto Const = dyn_cast<SCEVConstant>(Expr))
357 if (Const->getValue()->isZero()) {
358 DroppedFirstDim = true;
359 continue;
360 }
361 Subscripts.push_back(Expr);
362 continue;
363 }
364
365 auto ArrayTy = dyn_cast<ArrayType>(Ty);
366 if (!ArrayTy) {
367 Subscripts.clear();
368 Sizes.clear();
369 break;
370 }
371
372 Subscripts.push_back(Expr);
373 if (!(DroppedFirstDim && i == 2))
374 Sizes.push_back(ArrayTy->getNumElements());
375
376 Ty = ArrayTy->getElementType();
377 }
378
379 return std::make_tuple(Subscripts, Sizes);
380}
381
Tobias Grosser75805372011-04-29 06:27:02 +0000382MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000383 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000384 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000385 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000386}
387
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000388const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
389 isl_id *ArrayId = getArrayId();
390 void *User = isl_id_get_user(ArrayId);
391 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
392 isl_id_free(ArrayId);
393 return SAI;
394}
395
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000396__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000397 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
398}
399
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000400__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
401 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000402 isl_map *Schedule, *ScheduledAccRel;
403 isl_union_set *UDomain;
404
405 UDomain = isl_union_set_from_set(getStatement()->getDomain());
406 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
407 Schedule = isl_map_from_union_map(USchedule);
408 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
409 return isl_pw_multi_aff_from_map(ScheduledAccRel);
410}
411
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000412__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000413 return isl_map_copy(AccessRelation);
414}
415
Johannes Doerferta99130f2014-10-13 12:58:03 +0000416std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000417 return stringFromIslObj(AccessRelation);
418}
419
Johannes Doerferta99130f2014-10-13 12:58:03 +0000420__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000421 return isl_map_get_space(AccessRelation);
422}
423
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000424__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000425 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000426}
427
Tobias Grosser6f730082015-09-05 07:46:47 +0000428std::string MemoryAccess::getNewAccessRelationStr() const {
429 return stringFromIslObj(NewAccessRelation);
430}
431
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000432__isl_give isl_basic_map *
433MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000434 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000435 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000436
Tobias Grosser084d8f72012-05-29 09:29:44 +0000437 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000438 isl_basic_set_universe(Statement->getDomainSpace()),
439 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000440}
441
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000442// Formalize no out-of-bound access assumption
443//
444// When delinearizing array accesses we optimistically assume that the
445// delinearized accesses do not access out of bound locations (the subscript
446// expression of each array evaluates for each statement instance that is
447// executed to a value that is larger than zero and strictly smaller than the
448// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000449// dimension for which we do not need to assume any upper bound. At this point
450// we formalize this assumption to ensure that at code generation time the
451// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000452//
453// To find the set of constraints necessary to avoid out of bound accesses, we
454// first build the set of data locations that are not within array bounds. We
455// then apply the reverse access relation to obtain the set of iterations that
456// may contain invalid accesses and reduce this set of iterations to the ones
457// that are actually executed by intersecting them with the domain of the
458// statement. If we now project out all loop dimensions, we obtain a set of
459// parameters that may cause statement instances to be executed that may
460// possibly yield out of bound memory accesses. The complement of these
461// constraints is the set of constraints that needs to be assumed to ensure such
462// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000463void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000464 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000465 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Michael Krusee2bccbb2015-09-18 19:59:43 +0000466 for (int i = 1, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000467 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
468 isl_pw_aff *Var =
469 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
470 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
471
472 isl_set *DimOutside;
473
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000474 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Michael Krusee2bccbb2015-09-18 19:59:43 +0000475 isl_pw_aff *SizeE = Statement->getPwAff(Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000476
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000477 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
478 Statement->getNumIterators());
479 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
480 isl_space_dim(Space, isl_dim_set));
481 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
482 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000483
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000484 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000485
486 Outside = isl_set_union(Outside, DimOutside);
487 }
488
489 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
490 Outside = isl_set_intersect(Outside, Statement->getDomain());
491 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000492
493 // Remove divs to avoid the construction of overly complicated assumptions.
494 // Doing so increases the set of parameter combinations that are assumed to
495 // not appear. This is always save, but may make the resulting run-time check
496 // bail out more often than strictly necessary.
497 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000498 Outside = isl_set_complement(Outside);
499 Statement->getParent()->addAssumption(Outside);
500 isl_space_free(Space);
501}
502
Johannes Doerferte7044942015-02-24 11:58:30 +0000503void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
504 ScalarEvolution *SE = Statement->getParent()->getSE();
505
506 Value *Ptr = getPointerOperand(*getAccessInstruction());
507 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
508 return;
509
510 auto *PtrSCEV = SE->getSCEV(Ptr);
511 if (isa<SCEVCouldNotCompute>(PtrSCEV))
512 return;
513
514 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
515 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
516 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
517
518 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
519 if (Range.isFullSet())
520 return;
521
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000522 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000523 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000524 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
525 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
526
527 auto Min = LB.sdiv(APInt(BW, ElementSize));
528 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000529
530 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
531 AccessRange =
532 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
533 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
534}
535
Michael Krusee2bccbb2015-09-18 19:59:43 +0000536__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000537 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000538 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000539
540 for (int i = Size - 2; i >= 0; --i) {
541 isl_space *Space;
542 isl_map *MapOne, *MapTwo;
Michael Krusee2bccbb2015-09-18 19:59:43 +0000543 isl_pw_aff *DimSize = Statement->getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000544
545 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
546 isl_pw_aff_free(DimSize);
547 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
548
549 Space = isl_map_get_space(AccessRelation);
550 Space = isl_space_map_from_set(isl_space_range(Space));
551 Space = isl_space_align_params(Space, SpaceSize);
552
553 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
554 isl_id_free(ParamId);
555
556 MapOne = isl_map_universe(isl_space_copy(Space));
557 for (int j = 0; j < Size; ++j)
558 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
559 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
560
561 MapTwo = isl_map_universe(isl_space_copy(Space));
562 for (int j = 0; j < Size; ++j)
563 if (j < i || j > i + 1)
564 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
565
566 isl_local_space *LS = isl_local_space_from_space(Space);
567 isl_constraint *C;
568 C = isl_equality_alloc(isl_local_space_copy(LS));
569 C = isl_constraint_set_constant_si(C, -1);
570 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
571 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
572 MapTwo = isl_map_add_constraint(MapTwo, C);
573 C = isl_equality_alloc(LS);
574 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
575 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
576 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
577 MapTwo = isl_map_add_constraint(MapTwo, C);
578 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
579
580 MapOne = isl_map_union(MapOne, MapTwo);
581 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
582 }
583 return AccessRelation;
584}
585
Michael Krusee2bccbb2015-09-18 19:59:43 +0000586void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
587 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000588
Michael Krusee2bccbb2015-09-18 19:59:43 +0000589 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000590 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000591
Michael Krusee2bccbb2015-09-18 19:59:43 +0000592 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000593 // We overapproximate non-affine accesses with a possible access to the
594 // whole array. For read accesses it does not make a difference, if an
595 // access must or may happen. However, for write accesses it is important to
596 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000597 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000598 AccessRelation =
599 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000600
Michael Krusee2bccbb2015-09-18 19:59:43 +0000601 computeBoundsOnAccessRelation(getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000602 return;
603 }
604
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000605 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000606 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000607
Michael Krusee2bccbb2015-09-18 19:59:43 +0000608 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
609 isl_pw_aff *Affine = Statement->getPwAff(Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000610
Sebastian Pop422e33f2014-06-03 18:16:31 +0000611 if (Size == 1) {
612 // For the non delinearized arrays, divide the access function of the last
613 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000614 //
615 // A stride one array access in C expressed as A[i] is expressed in
616 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
617 // two subsequent values of 'i' index two values that are stored next to
618 // each other in memory. By this division we make this characteristic
619 // obvious again.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000620 isl_val *v = isl_val_int_from_si(Ctx, getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000621 Affine = isl_pw_aff_scale_down_val(Affine, v);
622 }
623
624 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
625
Tobias Grosser79baa212014-04-10 08:38:02 +0000626 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000627 }
628
Michael Krusee2bccbb2015-09-18 19:59:43 +0000629 if (Sizes.size() > 1 && !isa<SCEVConstant>(Sizes[0]))
630 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000631
Tobias Grosser79baa212014-04-10 08:38:02 +0000632 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000633 AccessRelation = isl_map_set_tuple_id(
634 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000635 AccessRelation =
636 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
637
Michael Krusee2bccbb2015-09-18 19:59:43 +0000638 assumeNoOutOfBound();
Tobias Grosseraa660a92015-03-30 00:07:50 +0000639 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000640 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000641}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000642
Michael Krusecac948e2015-10-02 13:53:07 +0000643MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
644 __isl_take isl_id *Id, AccessType Type,
645 Value *BaseAddress, unsigned ElemBytes, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000646 ArrayRef<const SCEV *> Subscripts,
647 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Michael Kruse8d0b7342015-09-25 21:21:00 +0000648 AccessOrigin Origin, StringRef BaseName)
Michael Krusecac948e2015-10-02 13:53:07 +0000649 : Id(Id), Origin(Origin), AccType(Type), RedType(RT_NONE), Statement(Stmt),
650 BaseAddr(BaseAddress), BaseName(BaseName), ElemBytes(ElemBytes),
651 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
652 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000653 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
654 NewAccessRelation(nullptr) {}
655
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000656void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000657 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000658 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000659}
660
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000661const std::string MemoryAccess::getReductionOperatorStr() const {
662 return MemoryAccess::getReductionOperatorStr(getReductionType());
663}
664
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000665__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
666
Johannes Doerfertf6183392014-07-01 20:52:51 +0000667raw_ostream &polly::operator<<(raw_ostream &OS,
668 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000669 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000670 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000671 else
672 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000673 return OS;
674}
675
Tobias Grosser75805372011-04-29 06:27:02 +0000676void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000677 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000678 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000679 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000680 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000681 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000682 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000683 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000684 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000685 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000686 break;
687 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000688 OS << "[Reduction Type: " << getReductionType() << "] ";
Michael Kruse8d0b7342015-09-25 21:21:00 +0000689 OS << "[Scalar: " << isImplicit() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000690 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000691 if (hasNewAccessRelation())
692 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000693}
694
Tobias Grosser74394f02013-01-14 22:40:23 +0000695void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000696
697// Create a map in the size of the provided set domain, that maps from the
698// one element of the provided set domain to another element of the provided
699// set domain.
700// The mapping is limited to all points that are equal in all but the last
701// dimension and for which the last dimension of the input is strict smaller
702// than the last dimension of the output.
703//
704// getEqualAndLarger(set[i0, i1, ..., iX]):
705//
706// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
707// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
708//
Tobias Grosserf5338802011-10-06 00:03:35 +0000709static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000710 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000711 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000712 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000713
714 // Set all but the last dimension to be equal for the input and output
715 //
716 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
717 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000718 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000719 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000720
721 // Set the last dimension of the input to be strict smaller than the
722 // last dimension of the output.
723 //
724 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000725 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
726 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000727 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000728}
729
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000730__isl_give isl_set *
731MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000732 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000733 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000734 isl_space *Space = isl_space_range(isl_map_get_space(S));
735 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000736
Sebastian Popa00a0292012-12-18 07:46:06 +0000737 S = isl_map_reverse(S);
738 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000739
Sebastian Popa00a0292012-12-18 07:46:06 +0000740 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
741 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
742 NextScatt = isl_map_apply_domain(NextScatt, S);
743 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000744
Sebastian Popa00a0292012-12-18 07:46:06 +0000745 isl_set *Deltas = isl_map_deltas(NextScatt);
746 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000747}
748
Sebastian Popa00a0292012-12-18 07:46:06 +0000749bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000750 int StrideWidth) const {
751 isl_set *Stride, *StrideX;
752 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000753
Sebastian Popa00a0292012-12-18 07:46:06 +0000754 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000755 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000756 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
757 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
758 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
759 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000760 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000761
Tobias Grosser28dd4862012-01-24 16:42:16 +0000762 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000763 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000764
Tobias Grosser28dd4862012-01-24 16:42:16 +0000765 return IsStrideX;
766}
767
Sebastian Popa00a0292012-12-18 07:46:06 +0000768bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
769 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000770}
771
Sebastian Popa00a0292012-12-18 07:46:06 +0000772bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
773 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000774}
775
Tobias Grosser166c4222015-09-05 07:46:40 +0000776void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
777 isl_map_free(NewAccessRelation);
778 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000779}
Tobias Grosser75805372011-04-29 06:27:02 +0000780
781//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000782
Tobias Grosser808cd692015-07-14 09:33:13 +0000783isl_map *ScopStmt::getSchedule() const {
784 isl_set *Domain = getDomain();
785 if (isl_set_is_empty(Domain)) {
786 isl_set_free(Domain);
787 return isl_map_from_aff(
788 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
789 }
790 auto *Schedule = getParent()->getSchedule();
791 Schedule = isl_union_map_intersect_domain(
792 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
793 if (isl_union_map_is_empty(Schedule)) {
794 isl_set_free(Domain);
795 isl_union_map_free(Schedule);
796 return isl_map_from_aff(
797 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
798 }
799 auto *M = isl_map_from_union_map(Schedule);
800 M = isl_map_coalesce(M);
801 M = isl_map_gist_domain(M, Domain);
802 M = isl_map_coalesce(M);
803 return M;
804}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000805
Johannes Doerfert574182d2015-08-12 10:19:50 +0000806__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000807 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
808 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000809}
810
Tobias Grosser37eb4222014-02-20 21:43:54 +0000811void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
812 assert(isl_set_is_subset(NewDomain, Domain) &&
813 "New domain is not a subset of old domain!");
814 isl_set_free(Domain);
815 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000816}
817
Michael Krusecac948e2015-10-02 13:53:07 +0000818void ScopStmt::buildAccessRelations() {
819 for (MemoryAccess *Access : MemAccs) {
820 Type *ElementType = Access->getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000821
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000822 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Michael Krusecac948e2015-10-02 13:53:07 +0000823 Access->getBaseAddr(), ElementType, Access->Sizes, Access->isPHI());
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000824
Michael Krusecac948e2015-10-02 13:53:07 +0000825 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +0000826 }
827}
828
Michael Krusecac948e2015-10-02 13:53:07 +0000829void ScopStmt::addAccess(MemoryAccess *Access) {
830 Instruction *AccessInst = Access->getAccessInstruction();
831
832 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
833 if (!MAL)
834 MAL = new MemoryAccessList();
835 MAL->emplace_front(Access);
836 MemAccs.push_back(MAL->front());
837}
838
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000839void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000840 for (MemoryAccess *MA : *this)
841 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000842
843 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000844}
845
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000846/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
847static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
848 void *User) {
849 isl_set **BoundedParts = static_cast<isl_set **>(User);
850 if (isl_basic_set_is_bounded(BSet))
851 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
852 else
853 isl_basic_set_free(BSet);
854 return isl_stat_ok;
855}
856
857/// @brief Return the bounded parts of @p S.
858static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
859 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
860 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
861 isl_set_free(S);
862 return BoundedParts;
863}
864
865/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
866///
867/// @returns A separation of @p S into first an unbounded then a bounded subset,
868/// both with regards to the dimension @p Dim.
869static std::pair<__isl_give isl_set *, __isl_give isl_set *>
870partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
871
872 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000873 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000874
875 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000876 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000877
878 // Remove dimensions that are greater than Dim as they are not interesting.
879 assert(NumDimsS >= Dim + 1);
880 OnlyDimS =
881 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
882
883 // Create artificial parametric upper bounds for dimensions smaller than Dim
884 // as we are not interested in them.
885 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
886 for (unsigned u = 0; u < Dim; u++) {
887 isl_constraint *C = isl_inequality_alloc(
888 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
889 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
890 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
891 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
892 }
893
894 // Collect all bounded parts of OnlyDimS.
895 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
896
897 // Create the dimensions greater than Dim again.
898 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
899 NumDimsS - Dim - 1);
900
901 // Remove the artificial upper bound parameters again.
902 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
903
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000904 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000905 return std::make_pair(UnboundedParts, BoundedParts);
906}
907
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000908/// @brief Set the dimension Ids from @p From in @p To.
909static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
910 __isl_take isl_set *To) {
911 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
912 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
913 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
914 }
915 return To;
916}
917
918/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000919static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000920 __isl_take isl_pw_aff *L,
921 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +0000922 switch (Pred) {
923 case ICmpInst::ICMP_EQ:
924 return isl_pw_aff_eq_set(L, R);
925 case ICmpInst::ICMP_NE:
926 return isl_pw_aff_ne_set(L, R);
927 case ICmpInst::ICMP_SLT:
928 return isl_pw_aff_lt_set(L, R);
929 case ICmpInst::ICMP_SLE:
930 return isl_pw_aff_le_set(L, R);
931 case ICmpInst::ICMP_SGT:
932 return isl_pw_aff_gt_set(L, R);
933 case ICmpInst::ICMP_SGE:
934 return isl_pw_aff_ge_set(L, R);
935 case ICmpInst::ICMP_ULT:
936 return isl_pw_aff_lt_set(L, R);
937 case ICmpInst::ICMP_UGT:
938 return isl_pw_aff_gt_set(L, R);
939 case ICmpInst::ICMP_ULE:
940 return isl_pw_aff_le_set(L, R);
941 case ICmpInst::ICMP_UGE:
942 return isl_pw_aff_ge_set(L, R);
943 default:
944 llvm_unreachable("Non integer predicate not supported");
945 }
946}
947
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000948/// @brief Create the conditions under which @p L @p Pred @p R is true.
949///
950/// Helper function that will make sure the dimensions of the result have the
951/// same isl_id's as the @p Domain.
952static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
953 __isl_take isl_pw_aff *L,
954 __isl_take isl_pw_aff *R,
955 __isl_keep isl_set *Domain) {
956 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
957 return setDimensionIds(Domain, ConsequenceCondSet);
958}
959
960/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000961///
962/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000963/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
964/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000965static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000966buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +0000967 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
968
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000969 Value *Condition = getConditionFromTerminator(SI);
970 assert(Condition && "No condition for switch");
971
972 ScalarEvolution &SE = *S.getSE();
973 BasicBlock *BB = SI->getParent();
974 isl_pw_aff *LHS, *RHS;
975 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
976
977 unsigned NumSuccessors = SI->getNumSuccessors();
978 ConditionSets.resize(NumSuccessors);
979 for (auto &Case : SI->cases()) {
980 unsigned Idx = Case.getSuccessorIndex();
981 ConstantInt *CaseValue = Case.getCaseValue();
982
983 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
984 isl_set *CaseConditionSet =
985 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
986 ConditionSets[Idx] = isl_set_coalesce(
987 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
988 }
989
990 assert(ConditionSets[0] == nullptr && "Default condition set was set");
991 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
992 for (unsigned u = 2; u < NumSuccessors; u++)
993 ConditionSetUnion =
994 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
995 ConditionSets[0] = setDimensionIds(
996 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
997
998 S.markAsOptimized();
999 isl_pw_aff_free(LHS);
1000}
1001
1002/// @brief Build the conditions sets for the terminator @p TI in 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, TerminatorInst *TI, Loop *L,
1009 __isl_keep isl_set *Domain,
1010 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1011
1012 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1013 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1014
1015 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1016
1017 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001018 ConditionSets.push_back(isl_set_copy(Domain));
1019 return;
1020 }
1021
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001022 Value *Condition = getConditionFromTerminator(TI);
1023 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001024
1025 isl_set *ConsequenceCondSet = nullptr;
1026 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1027 if (CCond->isZero())
1028 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1029 else
1030 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1031 } else {
1032 auto *ICond = dyn_cast<ICmpInst>(Condition);
1033 assert(ICond &&
1034 "Condition of exiting branch was neither constant nor ICmp!");
1035
1036 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001037 BasicBlock *BB = TI->getParent();
Johannes Doerfert96425c22015-08-30 21:13:53 +00001038 isl_pw_aff *LHS, *RHS;
Johannes Doerfertcef616f2015-09-15 22:49:04 +00001039 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1040 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001041 ConsequenceCondSet =
1042 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001043 }
1044
1045 assert(ConsequenceCondSet);
1046 isl_set *AlternativeCondSet =
1047 isl_set_complement(isl_set_copy(ConsequenceCondSet));
1048
1049 ConditionSets.push_back(isl_set_coalesce(
1050 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
1051 ConditionSets.push_back(isl_set_coalesce(
1052 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
1053}
1054
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001055void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +00001056 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +00001057
Tobias Grosser084d8f72012-05-29 09:29:44 +00001058 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1059
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001060 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001061 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001062}
1063
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001064void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001065 isl_ctx *Ctx = Parent.getIslCtx();
1066 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1067 Type *Ty = GEP->getPointerOperandType();
1068 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001069 ScopDetection &SD = Parent.getSD();
1070
1071 // The set of loads that are required to be invariant.
1072 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001073
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001074 std::vector<const SCEV *> Subscripts;
1075 std::vector<int> Sizes;
1076
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001077 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001078
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001079 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001080 Ty = PtrTy->getElementType();
1081 }
1082
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001083 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001084
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001085 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001086
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001087 for (size_t i = 0; i < Sizes.size(); i++) {
1088 auto Expr = Subscripts[i + IndexOffset];
1089 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001090
Johannes Doerfert09e36972015-10-07 20:17:36 +00001091 InvariantLoadsSetTy AccessILS;
1092 if (!isAffineExpr(&Parent.getRegion(), Expr, SE, nullptr, &AccessILS))
1093 continue;
1094
1095 bool NonAffine = false;
1096 for (LoadInst *LInst : AccessILS)
1097 if (!ScopRIL.count(LInst))
1098 NonAffine = true;
1099
1100 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001101 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001102
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001103 isl_pw_aff *AccessOffset = getPwAff(Expr);
1104 AccessOffset =
1105 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001106
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001107 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1108 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001109
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001110 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1111 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1112 OutOfBound = isl_set_params(OutOfBound);
1113 isl_set *InBound = isl_set_complement(OutOfBound);
1114 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001115
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001116 // A => B == !A or B
1117 isl_set *InBoundIfExecuted =
1118 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001119
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001120 Parent.addAssumption(InBoundIfExecuted);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001121 }
1122
1123 isl_local_space_free(LSpace);
1124}
1125
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001126void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1127 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001128 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1129 deriveAssumptionsFromGEP(GEP);
1130}
1131
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001132void ScopStmt::collectSurroundingLoops() {
1133 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1134 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1135 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1136 isl_id_free(DimId);
1137 }
1138}
1139
Michael Kruse9d080092015-09-11 21:41:48 +00001140ScopStmt::ScopStmt(Scop &parent, Region &R)
Michael Krusecac948e2015-10-02 13:53:07 +00001141 : Parent(parent), Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001142
Tobias Grosser16c44032015-07-09 07:31:45 +00001143 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001144}
1145
Michael Kruse9d080092015-09-11 21:41:48 +00001146ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Michael Krusecac948e2015-10-02 13:53:07 +00001147 : Parent(parent), Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001148
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001149 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001150}
1151
1152void ScopStmt::init() {
1153 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001154
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001155 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001156 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001157 buildAccessRelations();
1158
1159 if (BB) {
1160 deriveAssumptions(BB);
1161 } else {
1162 for (BasicBlock *Block : R->blocks()) {
1163 deriveAssumptions(Block);
1164 }
1165 }
1166
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001167 if (DetectReductions)
1168 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001169}
1170
Johannes Doerferte58a0122014-06-27 20:31:28 +00001171/// @brief Collect loads which might form a reduction chain with @p StoreMA
1172///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001173/// Check if the stored value for @p StoreMA is a binary operator with one or
1174/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001175/// used only once (by @p StoreMA) and its load operands are also used only
1176/// once, we have found a possible reduction chain. It starts at an operand
1177/// load and includes the binary operator and @p StoreMA.
1178///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001179/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001180/// escape this block or into any other store except @p StoreMA.
1181void ScopStmt::collectCandiateReductionLoads(
1182 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1183 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1184 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001185 return;
1186
1187 // Skip if there is not one binary operator between the load and the store
1188 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001189 if (!BinOp)
1190 return;
1191
1192 // Skip if the binary operators has multiple uses
1193 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001194 return;
1195
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001196 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001197 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1198 return;
1199
Johannes Doerfert9890a052014-07-01 00:32:29 +00001200 // Skip if the binary operator is outside the current SCoP
1201 if (BinOp->getParent() != Store->getParent())
1202 return;
1203
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001204 // Skip if it is a multiplicative reduction and we disabled them
1205 if (DisableMultiplicativeReductions &&
1206 (BinOp->getOpcode() == Instruction::Mul ||
1207 BinOp->getOpcode() == Instruction::FMul))
1208 return;
1209
Johannes Doerferte58a0122014-06-27 20:31:28 +00001210 // Check the binary operator operands for a candidate load
1211 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1212 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1213 if (!PossibleLoad0 && !PossibleLoad1)
1214 return;
1215
1216 // A load is only a candidate if it cannot escape (thus has only this use)
1217 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001218 if (PossibleLoad0->getParent() == Store->getParent())
1219 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001220 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001221 if (PossibleLoad1->getParent() == Store->getParent())
1222 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001223}
1224
1225/// @brief Check for reductions in this ScopStmt
1226///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001227/// Iterate over all store memory accesses and check for valid binary reduction
1228/// like chains. For all candidates we check if they have the same base address
1229/// and there are no other accesses which overlap with them. The base address
1230/// check rules out impossible reductions candidates early. The overlap check,
1231/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001232/// guarantees that none of the intermediate results will escape during
1233/// execution of the loop nest. We basically check here that no other memory
1234/// access can access the same memory as the potential reduction.
1235void ScopStmt::checkForReductions() {
1236 SmallVector<MemoryAccess *, 2> Loads;
1237 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1238
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001239 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001240 // stores and collecting possible reduction loads.
1241 for (MemoryAccess *StoreMA : MemAccs) {
1242 if (StoreMA->isRead())
1243 continue;
1244
1245 Loads.clear();
1246 collectCandiateReductionLoads(StoreMA, Loads);
1247 for (MemoryAccess *LoadMA : Loads)
1248 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1249 }
1250
1251 // Then check each possible candidate pair.
1252 for (const auto &CandidatePair : Candidates) {
1253 bool Valid = true;
1254 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1255 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1256
1257 // Skip those with obviously unequal base addresses.
1258 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1259 isl_map_free(LoadAccs);
1260 isl_map_free(StoreAccs);
1261 continue;
1262 }
1263
1264 // And check if the remaining for overlap with other memory accesses.
1265 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1266 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1267 isl_set *AllAccs = isl_map_range(AllAccsRel);
1268
1269 for (MemoryAccess *MA : MemAccs) {
1270 if (MA == CandidatePair.first || MA == CandidatePair.second)
1271 continue;
1272
1273 isl_map *AccRel =
1274 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1275 isl_set *Accs = isl_map_range(AccRel);
1276
1277 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1278 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1279 Valid = Valid && isl_set_is_empty(OverlapAccs);
1280 isl_set_free(OverlapAccs);
1281 }
1282 }
1283
1284 isl_set_free(AllAccs);
1285 if (!Valid)
1286 continue;
1287
Johannes Doerfertf6183392014-07-01 20:52:51 +00001288 const LoadInst *Load =
1289 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1290 MemoryAccess::ReductionType RT =
1291 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1292
Johannes Doerferte58a0122014-06-27 20:31:28 +00001293 // If no overlapping access was found we mark the load and store as
1294 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001295 CandidatePair.first->markAsReductionLike(RT);
1296 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001297 }
Tobias Grosser75805372011-04-29 06:27:02 +00001298}
1299
Tobias Grosser74394f02013-01-14 22:40:23 +00001300std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001301
Tobias Grosser54839312015-04-21 11:37:25 +00001302std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001303 auto *S = getSchedule();
1304 auto Str = stringFromIslObj(S);
1305 isl_map_free(S);
1306 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001307}
1308
Tobias Grosser74394f02013-01-14 22:40:23 +00001309unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001310
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001311unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001312
Tobias Grosser75805372011-04-29 06:27:02 +00001313const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1314
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001315const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001316 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001317}
1318
Tobias Grosser74394f02013-01-14 22:40:23 +00001319isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001320
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001321__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001322
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001323__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001324 return isl_set_get_space(Domain);
1325}
1326
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001327__isl_give isl_id *ScopStmt::getDomainId() const {
1328 return isl_set_get_tuple_id(Domain);
1329}
Tobias Grossercd95b772012-08-30 11:49:38 +00001330
Tobias Grosser75805372011-04-29 06:27:02 +00001331ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001332 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001333 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001334}
1335
1336void ScopStmt::print(raw_ostream &OS) const {
1337 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001338 OS.indent(12) << "Domain :=\n";
1339
1340 if (Domain) {
1341 OS.indent(16) << getDomainStr() << ";\n";
1342 } else
1343 OS.indent(16) << "n/a\n";
1344
Tobias Grosser54839312015-04-21 11:37:25 +00001345 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001346
1347 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001348 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001349 } else
1350 OS.indent(16) << "n/a\n";
1351
Tobias Grosser083d3d32014-06-28 08:59:45 +00001352 for (MemoryAccess *Access : MemAccs)
1353 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001354}
1355
1356void ScopStmt::dump() const { print(dbgs()); }
1357
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001358void ScopStmt::hoistMemoryAccesses(MemoryAccessList &InvMAs,
1359 InvariantAccessesTy &TargetList) {
1360
1361 // Remove all memory accesses in @p InvMAs from this statement together
1362 // with all scalar accesses that were caused by them. The tricky iteration
1363 // order uses is needed because the MemAccs is a vector and the order in
1364 // which the accesses of each memory access list (MAL) are stored in this
1365 // vector is reversed.
1366 for (MemoryAccess *MA : InvMAs) {
1367 auto &MAL = *lookupAccessesFor(MA->getAccessInstruction());
1368 MAL.reverse();
1369
1370 auto MALIt = MAL.begin();
1371 auto MALEnd = MAL.end();
1372 auto MemAccsIt = MemAccs.begin();
1373 while (MALIt != MALEnd) {
1374 while (*MemAccsIt != *MALIt)
1375 MemAccsIt++;
1376
1377 MALIt++;
1378 MemAccs.erase(MemAccsIt);
1379 }
1380
1381 InstructionToAccess.erase(MA->getAccessInstruction());
1382 delete &MAL;
1383 }
1384
1385 // Get the context under which this statement, hence the memory accesses, are
1386 // executed.
1387 isl_set *DomainCtx = isl_set_params(getDomain());
1388 DomainCtx = isl_set_remove_redundancies(DomainCtx);
1389 DomainCtx = isl_set_detect_equalities(DomainCtx);
1390 DomainCtx = isl_set_coalesce(DomainCtx);
1391
Johannes Doerfertf7e29672015-10-08 11:05:57 +00001392 Scop &S = *getParent();
1393 ScalarEvolution &SE = *S.getSE();
1394
1395 // Project out all parameters that relate to loads in this statement that
1396 // we will hoist. Otherwise we would have cyclic dependences on the
1397 // constraints under which the hoisted loads are executed and we could not
1398 // determine an order in which to preload them. This happens because not only
1399 // lower bounds are part of the domain but also upper bounds.
1400 for (MemoryAccess *MA : InvMAs) {
1401 Instruction *AccInst = MA->getAccessInstruction();
1402 if (SE.isSCEVable(AccInst->getType())) {
1403 isl_id *ParamId = S.getIdForParam(SE.getSCEV(AccInst));
1404 if (ParamId) {
1405 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
1406 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
1407 }
1408 isl_id_free(ParamId);
1409 }
1410 }
1411
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001412 for (MemoryAccess *MA : InvMAs)
1413 TargetList.push_back(std::make_pair(MA, isl_set_copy(DomainCtx)));
1414
1415 isl_set_free(DomainCtx);
1416}
1417
Tobias Grosser75805372011-04-29 06:27:02 +00001418//===----------------------------------------------------------------------===//
1419/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001420
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001421void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001422 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1423 isl_set_free(Context);
1424 Context = NewContext;
1425}
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;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001430 if (ParameterIds.find(Parameter) != ParameterIds.end())
1431 continue;
1432
1433 int dimension = Parameters.size();
1434
1435 Parameters.push_back(Parameter);
1436 ParameterIds[Parameter] = dimension;
1437 }
1438}
1439
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001440__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1441 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001442
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001443 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001444 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001445
Tobias Grosser8f99c162011-11-15 11:38:55 +00001446 std::string ParameterName;
1447
1448 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1449 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001450 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001451 }
1452
1453 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001454 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001455
Tobias Grosser20532b82014-04-11 17:56:49 +00001456 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1457 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001458}
Tobias Grosser75805372011-04-29 06:27:02 +00001459
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001460isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1461 isl_set *DomainContext = isl_union_set_params(getDomains());
1462 return isl_set_intersect_params(C, DomainContext);
1463}
1464
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001465void Scop::buildBoundaryContext() {
1466 BoundaryContext = Affinator.getWrappingContext();
1467 BoundaryContext = isl_set_complement(BoundaryContext);
1468 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
1469}
1470
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001471void Scop::addUserContext() {
1472 if (UserContextStr.empty())
1473 return;
1474
1475 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1476 isl_space *Space = getParamSpace();
1477 if (isl_space_dim(Space, isl_dim_param) !=
1478 isl_set_dim(UserContext, isl_dim_param)) {
1479 auto SpaceStr = isl_space_to_str(Space);
1480 errs() << "Error: the context provided in -polly-context has not the same "
1481 << "number of dimensions than the computed context. Due to this "
1482 << "mismatch, the -polly-context option is ignored. Please provide "
1483 << "the context in the parameter space: " << SpaceStr << ".\n";
1484 free(SpaceStr);
1485 isl_set_free(UserContext);
1486 isl_space_free(Space);
1487 return;
1488 }
1489
1490 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1491 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1492 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1493
1494 if (strcmp(NameContext, NameUserContext) != 0) {
1495 auto SpaceStr = isl_space_to_str(Space);
1496 errs() << "Error: the name of dimension " << i
1497 << " provided in -polly-context "
1498 << "is '" << NameUserContext << "', but the name in the computed "
1499 << "context is '" << NameContext
1500 << "'. Due to this name mismatch, "
1501 << "the -polly-context option is ignored. Please provide "
1502 << "the context in the parameter space: " << SpaceStr << ".\n";
1503 free(SpaceStr);
1504 isl_set_free(UserContext);
1505 isl_space_free(Space);
1506 return;
1507 }
1508
1509 UserContext =
1510 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1511 isl_space_get_dim_id(Space, isl_dim_param, i));
1512 }
1513
1514 Context = isl_set_intersect(Context, UserContext);
1515 isl_space_free(Space);
1516}
1517
Tobias Grosser6be480c2011-11-08 15:41:13 +00001518void Scop::buildContext() {
1519 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001520 Context = isl_set_universe(isl_space_copy(Space));
1521 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001522}
1523
Tobias Grosser18daaca2012-05-22 10:47:27 +00001524void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001525 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001526 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001527
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001528 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001529
Johannes Doerferte7044942015-02-24 11:58:30 +00001530 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001531 }
1532}
1533
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001534void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001535 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001536 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001537
Tobias Grosser083d3d32014-06-28 08:59:45 +00001538 for (const auto &ParamID : ParameterIds) {
1539 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001540 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001541 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001542 }
1543
1544 // Align the parameters of all data structures to the model.
1545 Context = isl_set_align_params(Context, Space);
1546
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001547 for (ScopStmt &Stmt : *this)
1548 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001549}
1550
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001551static __isl_give isl_set *
1552simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1553 const Scop &S) {
1554 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1555 AssumptionContext = isl_set_gist_params(AssumptionContext, DomainParameters);
1556 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1557 return AssumptionContext;
1558}
1559
1560void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001561 // The parameter constraints of the iteration domains give us a set of
1562 // constraints that need to hold for all cases where at least a single
1563 // statement iteration is executed in the whole scop. We now simplify the
1564 // assumed context under the assumption that such constraints hold and at
1565 // least a single statement iteration is executed. For cases where no
1566 // statement instances are executed, the assumptions we have taken about
1567 // the executed code do not matter and can be changed.
1568 //
1569 // WARNING: This only holds if the assumptions we have taken do not reduce
1570 // the set of statement instances that are executed. Otherwise we
1571 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001572 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001573 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001574 // performed. In such a case, modifying the run-time conditions and
1575 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001576 // to not be executed.
1577 //
1578 // Example:
1579 //
1580 // When delinearizing the following code:
1581 //
1582 // for (long i = 0; i < 100; i++)
1583 // for (long j = 0; j < m; j++)
1584 // A[i+p][j] = 1.0;
1585 //
1586 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001587 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001588 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001589 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1590 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001591}
1592
Johannes Doerfertb164c792014-09-18 11:17:17 +00001593/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001594static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001595 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1596 isl_pw_multi_aff *MinPMA, *MaxPMA;
1597 isl_pw_aff *LastDimAff;
1598 isl_aff *OneAff;
1599 unsigned Pos;
1600
Johannes Doerfert9143d672014-09-27 11:02:39 +00001601 // Restrict the number of parameters involved in the access as the lexmin/
1602 // lexmax computation will take too long if this number is high.
1603 //
1604 // Experiments with a simple test case using an i7 4800MQ:
1605 //
1606 // #Parameters involved | Time (in sec)
1607 // 6 | 0.01
1608 // 7 | 0.04
1609 // 8 | 0.12
1610 // 9 | 0.40
1611 // 10 | 1.54
1612 // 11 | 6.78
1613 // 12 | 30.38
1614 //
1615 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1616 unsigned InvolvedParams = 0;
1617 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1618 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1619 InvolvedParams++;
1620
1621 if (InvolvedParams > RunTimeChecksMaxParameters) {
1622 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001623 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001624 }
1625 }
1626
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001627 Set = isl_set_remove_divs(Set);
1628
Johannes Doerfertb164c792014-09-18 11:17:17 +00001629 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1630 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1631
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001632 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1633 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1634
Johannes Doerfertb164c792014-09-18 11:17:17 +00001635 // Adjust the last dimension of the maximal access by one as we want to
1636 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1637 // we test during code generation might now point after the end of the
1638 // allocated array but we will never dereference it anyway.
1639 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1640 "Assumed at least one output dimension");
1641 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1642 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1643 OneAff = isl_aff_zero_on_domain(
1644 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1645 OneAff = isl_aff_add_constant_si(OneAff, 1);
1646 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1647 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1648
1649 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1650
1651 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001652 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001653}
1654
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001655static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1656 isl_set *Domain = MA->getStatement()->getDomain();
1657 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1658 return isl_set_reset_tuple_id(Domain);
1659}
1660
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001661/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1662static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001663 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001664 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001665
1666 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1667 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001668 Locations = isl_union_set_coalesce(Locations);
1669 Locations = isl_union_set_detect_equalities(Locations);
1670 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001671 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001672 isl_union_set_free(Locations);
1673 return Valid;
1674}
1675
Johannes Doerfert96425c22015-08-30 21:13:53 +00001676/// @brief Helper to treat non-affine regions and basic blocks the same.
1677///
1678///{
1679
1680/// @brief Return the block that is the representing block for @p RN.
1681static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1682 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1683 : RN->getNodeAs<BasicBlock>();
1684}
1685
1686/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001687static inline BasicBlock *
1688getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001689 if (RN->isSubRegion()) {
1690 assert(idx == 0);
1691 return RN->getNodeAs<Region>()->getExit();
1692 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001693 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001694}
1695
1696/// @brief Return the smallest loop surrounding @p RN.
1697static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1698 if (!RN->isSubRegion())
1699 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1700
1701 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1702 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1703 while (L && NonAffineSubRegion->contains(L))
1704 L = L->getParentLoop();
1705 return L;
1706}
1707
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001708static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1709 if (!RN->isSubRegion())
1710 return 1;
1711
1712 unsigned NumBlocks = 0;
1713 Region *R = RN->getNodeAs<Region>();
1714 for (auto BB : R->blocks()) {
1715 (void)BB;
1716 NumBlocks++;
1717 }
1718 return NumBlocks;
1719}
1720
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001721static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
1722 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00001723 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001724 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00001725 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001726 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00001727 return true;
1728 return false;
1729}
1730
Johannes Doerfert96425c22015-08-30 21:13:53 +00001731///}
1732
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001733static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1734 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001735 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001736 isl_id *DimId =
1737 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
1738 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
1739}
1740
Johannes Doerfert96425c22015-08-30 21:13:53 +00001741isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1742 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1743 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00001744 return getDomainConditions(BB);
1745}
1746
1747isl_set *Scop::getDomainConditions(BasicBlock *BB) {
1748 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001749 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001750}
1751
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001752void Scop::buildDomains(Region *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001753
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001754 auto *EntryBB = R->getEntry();
1755 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
1756 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001757
1758 Loop *L = LI.getLoopFor(EntryBB);
1759 while (LD-- >= 0) {
1760 S = addDomainDimId(S, LD + 1, L);
1761 L = L->getParentLoop();
1762 }
1763
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001764 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001765
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00001766 if (SD.isNonAffineSubRegion(R, R))
1767 return;
1768
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001769 buildDomainsWithBranchConstraints(R);
1770 propagateDomainConstraints(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001771}
1772
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001773void Scop::buildDomainsWithBranchConstraints(Region *R) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001774 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00001775
1776 // To create the domain for each block in R we iterate over all blocks and
1777 // subregions in R and propagate the conditions under which the current region
1778 // element is executed. To this end we iterate in reverse post order over R as
1779 // it ensures that we first visit all predecessors of a region node (either a
1780 // basic block or a subregion) before we visit the region node itself.
1781 // Initially, only the domain for the SCoP region entry block is set and from
1782 // there we propagate the current domain to all successors, however we add the
1783 // condition that the successor is actually executed next.
1784 // As we are only interested in non-loop carried constraints here we can
1785 // simply skip loop back edges.
1786
1787 ReversePostOrderTraversal<Region *> RTraversal(R);
1788 for (auto *RN : RTraversal) {
1789
1790 // Recurse for affine subregions but go on for basic blocks and non-affine
1791 // subregions.
1792 if (RN->isSubRegion()) {
1793 Region *SubRegion = RN->getNodeAs<Region>();
1794 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001795 buildDomainsWithBranchConstraints(SubRegion);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001796 continue;
1797 }
1798 }
1799
Johannes Doerfertf5673802015-10-01 23:48:18 +00001800 // Error blocks are assumed not to be executed. Therefor they are not
1801 // checked properly in the ScopDetection. Any attempt to generate control
1802 // conditions from them might result in a crash. However, this is only true
1803 // for the first step of the domain generation (this function) where we
1804 // push the control conditions of a block to the successors. In the second
1805 // step (propagateDomainConstraints) we only receive domain constraints from
1806 // the predecessors and can therefor look at the domain of a error block.
1807 // That allows us to generate the assumptions needed for them not to be
1808 // executed at runtime.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001809 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00001810 continue;
1811
Johannes Doerfert96425c22015-08-30 21:13:53 +00001812 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001813 TerminatorInst *TI = BB->getTerminator();
1814
Johannes Doerfertf5673802015-10-01 23:48:18 +00001815 isl_set *Domain = DomainMap.lookup(BB);
1816 if (!Domain) {
1817 DEBUG(dbgs() << "\tSkip: " << BB->getName()
1818 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001819 continue;
1820 }
1821
Johannes Doerfert96425c22015-08-30 21:13:53 +00001822 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001823
1824 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1825 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1826
1827 // Build the condition sets for the successor nodes of the current region
1828 // node. If it is a non-affine subregion we will always execute the single
1829 // exit node, hence the single entry node domain is the condition set. For
1830 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001831 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001832 if (RN->isSubRegion())
1833 ConditionSets.push_back(isl_set_copy(Domain));
1834 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001835 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001836
1837 // Now iterate over the successors and set their initial domain based on
1838 // their condition set. We skip back edges here and have to be careful when
1839 // we leave a loop not to keep constraints over a dimension that doesn't
1840 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001841 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00001842 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001843 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001844 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001845
1846 // Skip back edges.
1847 if (DT.dominates(SuccBB, BB)) {
1848 isl_set_free(CondSet);
1849 continue;
1850 }
1851
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001852 // Do not adjust the number of dimensions if we enter a boxed loop or are
1853 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001854 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001855 Region *SuccRegion = RI.getRegionFor(SuccBB);
Johannes Doerfert634909c2015-10-04 14:57:41 +00001856 if (SD.isNonAffineSubRegion(SuccRegion, &getRegion()))
1857 while (SuccBBLoop && SuccRegion->contains(SuccBBLoop))
1858 SuccBBLoop = SuccBBLoop->getParentLoop();
1859
1860 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001861
1862 // Check if the edge to SuccBB is a loop entry or exit edge. If so
1863 // adjust the dimensionality accordingly. Lastly, if we leave a loop
1864 // and enter a new one we need to drop the old constraints.
1865 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001866 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001867 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001868 CondSet = isl_set_project_out(CondSet, isl_dim_set,
1869 isl_set_n_dim(CondSet) - LoopDepthDiff,
1870 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001871 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001872 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001873 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001874 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001875 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001876 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001877 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
1878 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001879 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001880 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00001881 }
1882
1883 // Set the domain for the successor or merge it with an existing domain in
1884 // case there are multiple paths (without loop back edges) to the
1885 // successor block.
1886 isl_set *&SuccDomain = DomainMap[SuccBB];
1887 if (!SuccDomain)
1888 SuccDomain = CondSet;
1889 else
1890 SuccDomain = isl_set_union(SuccDomain, CondSet);
1891
1892 SuccDomain = isl_set_coalesce(SuccDomain);
Johannes Doerfert634909c2015-10-04 14:57:41 +00001893 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
1894 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001895 }
1896 }
1897}
1898
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001899/// @brief Return the domain for @p BB wrt @p DomainMap.
1900///
1901/// This helper function will lookup @p BB in @p DomainMap but also handle the
1902/// case where @p BB is contained in a non-affine subregion using the region
1903/// tree obtained by @p RI.
1904static __isl_give isl_set *
1905getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
1906 RegionInfo &RI) {
1907 auto DIt = DomainMap.find(BB);
1908 if (DIt != DomainMap.end())
1909 return isl_set_copy(DIt->getSecond());
1910
1911 Region *R = RI.getRegionFor(BB);
1912 while (R->getEntry() == BB)
1913 R = R->getParent();
1914 return getDomainForBlock(R->getEntry(), DomainMap, RI);
1915}
1916
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001917void Scop::propagateDomainConstraints(Region *R) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001918 // Iterate over the region R and propagate the domain constrains from the
1919 // predecessors to the current node. In contrast to the
1920 // buildDomainsWithBranchConstraints function, this one will pull the domain
1921 // information from the predecessors instead of pushing it to the successors.
1922 // Additionally, we assume the domains to be already present in the domain
1923 // map here. However, we iterate again in reverse post order so we know all
1924 // predecessors have been visited before a block or non-affine subregion is
1925 // visited.
1926
1927 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
1928 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
1929
1930 ReversePostOrderTraversal<Region *> RTraversal(R);
1931 for (auto *RN : RTraversal) {
1932
1933 // Recurse for affine subregions but go on for basic blocks and non-affine
1934 // subregions.
1935 if (RN->isSubRegion()) {
1936 Region *SubRegion = RN->getNodeAs<Region>();
1937 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001938 propagateDomainConstraints(SubRegion);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001939 continue;
1940 }
1941 }
1942
Johannes Doerfertf5673802015-10-01 23:48:18 +00001943 // Get the domain for the current block and check if it was initialized or
1944 // not. The only way it was not is if this block is only reachable via error
1945 // blocks, thus will not be executed under the assumptions we make. Such
1946 // blocks have to be skipped as their predecessors might not have domains
1947 // either. It would not benefit us to compute the domain anyway, only the
1948 // domains of the error blocks that are reachable from non-error blocks
1949 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001950 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00001951 isl_set *&Domain = DomainMap[BB];
1952 if (!Domain) {
1953 DEBUG(dbgs() << "\tSkip: " << BB->getName()
1954 << ", it is only reachable from error blocks.\n");
1955 DomainMap.erase(BB);
1956 continue;
1957 }
1958 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
1959
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001960 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1961 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1962
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001963 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
1964 for (auto *PredBB : predecessors(BB)) {
1965
1966 // Skip backedges
1967 if (DT.dominates(BB, PredBB))
1968 continue;
1969
1970 isl_set *PredBBDom = nullptr;
1971
1972 // Handle the SCoP entry block with its outside predecessors.
1973 if (!getRegion().contains(PredBB))
1974 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
1975
1976 if (!PredBBDom) {
1977 // Determine the loop depth of the predecessor and adjust its domain to
1978 // the domain of the current block. This can mean we have to:
1979 // o) Drop a dimension if this block is the exit of a loop, not the
1980 // header of a new loop and the predecessor was part of the loop.
1981 // o) Add an unconstrainted new dimension if this block is the header
1982 // of a loop and the predecessor is not part of it.
1983 // o) Drop the information about the innermost loop dimension when the
1984 // predecessor and the current block are surrounded by different
1985 // loops in the same depth.
1986 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
1987 Loop *PredBBLoop = LI.getLoopFor(PredBB);
1988 while (BoxedLoops.count(PredBBLoop))
1989 PredBBLoop = PredBBLoop->getParentLoop();
1990
1991 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001992 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001993 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001994 PredBBDom = isl_set_project_out(
1995 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
1996 LoopDepthDiff);
1997 else if (PredBBLoopDepth < BBLoopDepth) {
1998 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001999 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002000 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2001 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002002 PredBBDom = isl_set_drop_constraints_involving_dims(
2003 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002004 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002005 }
2006
2007 PredDom = isl_set_union(PredDom, PredBBDom);
2008 }
2009
2010 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002011 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002012
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002013 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002014 addLoopBoundsToHeaderDomain(BBLoop);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002015
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002016 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002017 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002018 IsOptimized = true;
2019 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2020 addAssumption(isl_set_complement(DomPar));
2021 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002022 }
2023}
2024
2025/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2026/// is incremented by one and all other dimensions are equal, e.g.,
2027/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2028/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2029static __isl_give isl_map *
2030createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2031 auto *MapSpace = isl_space_map_from_set(SetSpace);
2032 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2033 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2034 if (u != Dim)
2035 NextIterationMap =
2036 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2037 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2038 C = isl_constraint_set_constant_si(C, 1);
2039 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2040 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2041 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2042 return NextIterationMap;
2043}
2044
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002045void Scop::addLoopBoundsToHeaderDomain(Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002046 int LoopDepth = getRelativeLoopDepth(L);
2047 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002048
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002049 BasicBlock *HeaderBB = L->getHeader();
2050 assert(DomainMap.count(HeaderBB));
2051 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002052
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002053 isl_map *NextIterationMap =
2054 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002055
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002056 isl_set *UnionBackedgeCondition =
2057 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002058
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002059 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2060 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002061
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002062 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002063
2064 // If the latch is only reachable via error statements we skip it.
2065 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2066 if (!LatchBBDom)
2067 continue;
2068
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002069 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002070
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002071 TerminatorInst *TI = LatchBB->getTerminator();
2072 BranchInst *BI = dyn_cast<BranchInst>(TI);
2073 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002074 BackedgeCondition = isl_set_copy(LatchBBDom);
2075 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002076 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002077 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002078 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002079
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002080 // Free the non back edge condition set as we do not need it.
2081 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002082
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002083 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002084 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002085
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002086 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2087 assert(LatchLoopDepth >= LoopDepth);
2088 BackedgeCondition =
2089 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2090 LatchLoopDepth - LoopDepth);
2091 UnionBackedgeCondition =
2092 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002093 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002094
2095 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2096 for (int i = 0; i < LoopDepth; i++)
2097 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2098
2099 isl_set *UnionBackedgeConditionComplement =
2100 isl_set_complement(UnionBackedgeCondition);
2101 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2102 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2103 UnionBackedgeConditionComplement =
2104 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2105 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2106 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2107
2108 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2109 HeaderBBDom = Parts.second;
2110
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002111 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2112 // the bounded assumptions to the context as they are already implied by the
2113 // <nsw> tag.
2114 if (Affinator.hasNSWAddRecForLoop(L)) {
2115 isl_set_free(Parts.first);
2116 return;
2117 }
2118
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002119 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2120 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfert707a4062015-09-20 16:38:19 +00002121 addAssumption(BoundedCtx);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002122}
2123
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002124void Scop::buildAliasChecks(AliasAnalysis &AA) {
2125 if (!PollyUseRuntimeAliasChecks)
2126 return;
2127
2128 if (buildAliasGroups(AA))
2129 return;
2130
2131 // If a problem occurs while building the alias groups we need to delete
2132 // this SCoP and pretend it wasn't valid in the first place. To this end
2133 // we make the assumed context infeasible.
2134 addAssumption(isl_set_empty(getParamSpace()));
2135
2136 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2137 << " could not be created as the number of parameters involved "
2138 "is too high. The SCoP will be "
2139 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2140 "the maximal number of parameters but be advised that the "
2141 "compile time might increase exponentially.\n\n");
2142}
2143
Johannes Doerfert9143d672014-09-27 11:02:39 +00002144bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002145 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002146 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002147 // for all memory accesses inside the SCoP.
2148 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002149 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002150 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002151 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002152 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002153 // if their access domains intersect, otherwise they are in different
2154 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002155 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002156 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002157 // and maximal accesses to each array of a group in read only and non
2158 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002159 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2160
2161 AliasSetTracker AST(AA);
2162
2163 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002164 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002165 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002166
2167 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002168 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002169 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2170 isl_set_free(StmtDomain);
2171 if (StmtDomainEmpty)
2172 continue;
2173
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002174 for (MemoryAccess *MA : Stmt) {
Michael Kruse8d0b7342015-09-25 21:21:00 +00002175 if (MA->isImplicit())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002176 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002177 if (!MA->isRead())
2178 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002179 Instruction *Acc = MA->getAccessInstruction();
2180 PtrToAcc[getPointerOperand(*Acc)] = MA;
2181 AST.add(Acc);
2182 }
2183 }
2184
2185 SmallVector<AliasGroupTy, 4> AliasGroups;
2186 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002187 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002188 continue;
2189 AliasGroupTy AG;
2190 for (auto PR : AS)
2191 AG.push_back(PtrToAcc[PR.getValue()]);
2192 assert(AG.size() > 1 &&
2193 "Alias groups should contain at least two accesses");
2194 AliasGroups.push_back(std::move(AG));
2195 }
2196
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002197 // Split the alias groups based on their domain.
2198 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2199 AliasGroupTy NewAG;
2200 AliasGroupTy &AG = AliasGroups[u];
2201 AliasGroupTy::iterator AGI = AG.begin();
2202 isl_set *AGDomain = getAccessDomain(*AGI);
2203 while (AGI != AG.end()) {
2204 MemoryAccess *MA = *AGI;
2205 isl_set *MADomain = getAccessDomain(MA);
2206 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2207 NewAG.push_back(MA);
2208 AGI = AG.erase(AGI);
2209 isl_set_free(MADomain);
2210 } else {
2211 AGDomain = isl_set_union(AGDomain, MADomain);
2212 AGI++;
2213 }
2214 }
2215 if (NewAG.size() > 1)
2216 AliasGroups.push_back(std::move(NewAG));
2217 isl_set_free(AGDomain);
2218 }
2219
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002220 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002221 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2222 for (AliasGroupTy &AG : AliasGroups) {
2223 NonReadOnlyBaseValues.clear();
2224 ReadOnlyPairs.clear();
2225
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002226 if (AG.size() < 2) {
2227 AG.clear();
2228 continue;
2229 }
2230
Johannes Doerfert13771732014-10-01 12:40:46 +00002231 for (auto II = AG.begin(); II != AG.end();) {
2232 Value *BaseAddr = (*II)->getBaseAddr();
2233 if (HasWriteAccess.count(BaseAddr)) {
2234 NonReadOnlyBaseValues.insert(BaseAddr);
2235 II++;
2236 } else {
2237 ReadOnlyPairs[BaseAddr].insert(*II);
2238 II = AG.erase(II);
2239 }
2240 }
2241
2242 // If we don't have read only pointers check if there are at least two
2243 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002244 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002245 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002246 continue;
2247 }
2248
2249 // If we don't have non read only pointers clear the alias group.
2250 if (NonReadOnlyBaseValues.empty()) {
2251 AG.clear();
2252 continue;
2253 }
2254
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002255 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002256 MinMaxAliasGroups.emplace_back();
2257 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2258 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2259 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2260 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002261
2262 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002263
2264 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002265 for (MemoryAccess *MA : AG)
2266 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002267
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002268 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2269 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002270
2271 // Bail out if the number of values we need to compare is too large.
2272 // This is important as the number of comparisions grows quadratically with
2273 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002274 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2275 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002276 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002277
2278 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002279 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002280 Accesses = isl_union_map_empty(getParamSpace());
2281
2282 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2283 for (MemoryAccess *MA : ReadOnlyPair.second)
2284 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2285
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002286 Valid =
2287 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002288
2289 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002290 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002291 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002292
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002293 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002294}
2295
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002296static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
2297 Loop *L = LI.getLoopFor(R.getEntry());
2298 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2299}
2300
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002301static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2302 ScopDetection &SD) {
2303
2304 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2305
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002306 unsigned MinLD = INT_MAX, MaxLD = 0;
2307 for (BasicBlock *BB : R.blocks()) {
2308 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002309 if (!R.contains(L))
2310 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002311 if (BoxedLoops && BoxedLoops->count(L))
2312 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002313 unsigned LD = L->getLoopDepth();
2314 MinLD = std::min(MinLD, LD);
2315 MaxLD = std::max(MaxLD, LD);
2316 }
2317 }
2318
2319 // Handle the case that there is no loop in the SCoP first.
2320 if (MaxLD == 0)
2321 return 1;
2322
2323 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2324 assert(MaxLD >= MinLD &&
2325 "Maximal loop depth was smaller than mininaml loop depth?");
2326 return MaxLD - MinLD + 1;
2327}
2328
Johannes Doerfert478a7de2015-10-02 13:09:31 +00002329Scop::Scop(Region &R, AccFuncMapType &AccFuncMap, ScopDetection &SD,
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002330 ScalarEvolution &ScalarEvolution, DominatorTree &DT, LoopInfo &LI,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002331 isl_ctx *Context, unsigned MaxLoopDepth)
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002332 : LI(LI), DT(DT), SE(&ScalarEvolution), SD(SD), R(R),
2333 AccFuncMap(AccFuncMap), IsOptimized(false),
2334 HasSingleExitEdge(R.getExitingBlock()), MaxLoopDepth(MaxLoopDepth),
2335 IslCtx(Context), Context(nullptr), Affinator(this),
2336 AssumedContext(nullptr), BoundaryContext(nullptr), Schedule(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002337
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002338void Scop::init(AliasAnalysis &AA) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002339 buildContext();
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002340 buildDomains(&R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002341
Michael Krusecac948e2015-10-02 13:53:07 +00002342 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002343 // Exit early in case there are no executable statements left in this scop.
Michael Krusecac948e2015-10-02 13:53:07 +00002344 simplifySCoP(true);
Michael Kruseafe06702015-10-02 16:33:27 +00002345 if (Stmts.empty())
2346 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002347
Michael Krusecac948e2015-10-02 13:53:07 +00002348 // The ScopStmts now have enough information to initialize themselves.
2349 for (ScopStmt &Stmt : Stmts)
2350 Stmt.init();
2351
2352 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002353 Loop *L = getLoopSurroundingRegion(R, LI);
2354 LoopSchedules[L];
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002355 buildSchedule(&R, LoopSchedules);
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002356 updateAccessDimensionality();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002357 Schedule = LoopSchedules[L].first;
Tobias Grosser75805372011-04-29 06:27:02 +00002358
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002359 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002360 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002361 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002362 buildBoundaryContext();
2363 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002364 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002365
2366 hoistInvariantLoads();
Michael Krusecac948e2015-10-02 13:53:07 +00002367 simplifySCoP(false);
Tobias Grosser75805372011-04-29 06:27:02 +00002368}
2369
2370Scop::~Scop() {
2371 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002372 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002373 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002374 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002375
Johannes Doerfert96425c22015-08-30 21:13:53 +00002376 for (auto It : DomainMap)
2377 isl_set_free(It.second);
2378
Johannes Doerfertb164c792014-09-18 11:17:17 +00002379 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002380 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002381 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002382 isl_pw_multi_aff_free(MMA.first);
2383 isl_pw_multi_aff_free(MMA.second);
2384 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002385 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002386 isl_pw_multi_aff_free(MMA.first);
2387 isl_pw_multi_aff_free(MMA.second);
2388 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002389 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002390
2391 for (const auto &IA : InvariantAccesses)
2392 isl_set_free(IA.second);
Tobias Grosser75805372011-04-29 06:27:02 +00002393}
2394
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002395void Scop::updateAccessDimensionality() {
2396 for (auto &Stmt : *this)
2397 for (auto &Access : Stmt)
2398 Access->updateDimensionality();
2399}
2400
Michael Krusecac948e2015-10-02 13:53:07 +00002401void Scop::simplifySCoP(bool RemoveIgnoredStmts) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002402 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2403 ScopStmt &Stmt = *StmtIt;
Michael Krusecac948e2015-10-02 13:53:07 +00002404 RegionNode *RN = Stmt.isRegionStmt()
2405 ? Stmt.getRegion()->getNode()
2406 : getRegion().getBBNode(Stmt.getBasicBlock());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002407
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002408 if (StmtIt->isEmpty() ||
2409 isl_set_is_empty(DomainMap[getRegionNodeBasicBlock(RN)]) ||
2410 (RemoveIgnoredStmts && isIgnored(RN))) {
2411
Michael Krusecac948e2015-10-02 13:53:07 +00002412 // Remove the statement because it is unnecessary.
2413 if (Stmt.isRegionStmt())
2414 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2415 StmtMap.erase(BB);
2416 else
2417 StmtMap.erase(Stmt.getBasicBlock());
2418
2419 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002420 continue;
2421 }
2422
Michael Krusecac948e2015-10-02 13:53:07 +00002423 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002424 }
2425}
2426
2427void Scop::hoistInvariantLoads() {
2428 isl_union_map *Writes = getWrites();
2429 for (ScopStmt &Stmt : *this) {
2430
2431 // TODO: Loads that are not loop carried, hence are in a statement with
2432 // zero iterators, are by construction invariant, though we
Johannes Doerfert09e36972015-10-07 20:17:36 +00002433 // currently "hoist" them anyway. This is necessary because we allow
2434 // them to be treated as parameters (e.g., in conditions) and our code
2435 // generation would otherwise use the old value.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002436
Johannes Doerfert8930f482015-10-02 14:51:00 +00002437 BasicBlock *BB = Stmt.isBlockStmt() ? Stmt.getBasicBlock()
2438 : Stmt.getRegion()->getEntry();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002439 isl_set *Domain = Stmt.getDomain();
2440 MemoryAccessList InvMAs;
2441
2442 for (MemoryAccess *MA : Stmt) {
2443 if (MA->isImplicit() || MA->isWrite() || !MA->isAffine())
2444 continue;
2445
Johannes Doerfert8930f482015-10-02 14:51:00 +00002446 // Skip accesses in non-affine subregions as they might not be executed
2447 // under the same condition as the entry of the non-affine subregion.
2448 if (BB != MA->getAccessInstruction()->getParent())
2449 continue;
2450
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002451 isl_map *AccessRelation = MA->getAccessRelation();
2452 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
2453 Stmt.getNumIterators())) {
2454 isl_map_free(AccessRelation);
2455 continue;
2456 }
2457
2458 AccessRelation =
2459 isl_map_intersect_domain(AccessRelation, isl_set_copy(Domain));
2460 isl_set *AccessRange = isl_map_range(AccessRelation);
2461
2462 isl_union_map *Written = isl_union_map_intersect_range(
2463 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
2464 bool IsWritten = !isl_union_map_is_empty(Written);
2465 isl_union_map_free(Written);
2466
2467 if (IsWritten)
2468 continue;
2469
2470 InvMAs.push_front(MA);
2471 }
2472
2473 // We inserted invariant accesses always in the front but need them to be
2474 // sorted in a "natural order". The statements are already sorted in reverse
2475 // post order and that suffices for the accesses too. The reason we require
2476 // an order in the first place is the dependences between invariant loads
2477 // that can be caused by indirect loads.
2478 InvMAs.reverse();
2479
2480 // Transfer the memory access from the statement to the SCoP.
2481 Stmt.hoistMemoryAccesses(InvMAs, InvariantAccesses);
2482
2483 isl_set_free(Domain);
2484 }
2485 isl_union_map_free(Writes);
2486
2487 if (!InvariantAccesses.empty())
2488 IsOptimized = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00002489
2490 // Check required invariant loads that were tagged during SCoP detection.
2491 for (LoadInst *LI : *SD.getRequiredInvariantLoads(&getRegion())) {
2492 assert(LI && getRegion().contains(LI));
2493 ScopStmt *Stmt = getStmtForBasicBlock(LI->getParent());
2494 if (Stmt && Stmt->lookupAccessesFor(LI) != nullptr) {
2495 DEBUG(dbgs() << "\n\nWARNING: Load (" << *LI
2496 << ") is required to be invariant but was not marked as "
2497 "such. SCoP for "
2498 << getRegion() << " will be dropped\n\n");
2499 addAssumption(isl_set_empty(getParamSpace()));
2500 return;
2501 }
2502 }
2503
2504 // We want invariant accesses to be sorted in a "natural order" because there
2505 // might be dependences between invariant loads. These can be caused by
2506 // indirect loads but also because an invariant load is only conditionally
2507 // executed and the condition is dependent on another invariant load. As we
2508 // want to do code generation in a straight forward way, e.g., preload the
2509 // accesses in the list one after another, we sort them such that the
2510 // preloaded values needed in the conditions will always be in front. Before
2511 // we already ordered the accesses such that indirect loads can be resolved,
2512 // thus we use a stable sort here.
2513
2514 auto compareInvariantAccesses = [this](const InvariantAccessTy &IA0,
2515 const InvariantAccessTy &IA1) {
2516 Instruction *AI0 = IA0.first->getAccessInstruction();
2517 Instruction *AI1 = IA1.first->getAccessInstruction();
2518
2519 const SCEV *S0 =
2520 SE->isSCEVable(AI0->getType()) ? SE->getSCEV(AI0) : nullptr;
2521 const SCEV *S1 =
2522 SE->isSCEVable(AI1->getType()) ? SE->getSCEV(AI1) : nullptr;
2523
2524 isl_id *Id0 = getIdForParam(S0);
2525 isl_id *Id1 = getIdForParam(S1);
2526
2527 if (Id0 && !Id1) {
2528 isl_id_free(Id0);
2529 isl_id_free(Id1);
2530 return true;
2531 }
2532
2533 if (!Id0) {
2534 isl_id_free(Id0);
2535 isl_id_free(Id1);
2536 return false;
2537 }
2538
2539 assert(Id0 && Id1);
2540
2541 isl_set *Dom0 = IA0.second;
2542 isl_set *Dom1 = IA1.second;
2543
2544 int Dim0 = isl_set_find_dim_by_id(Dom0, isl_dim_param, Id0);
2545 int Dim1 = isl_set_find_dim_by_id(Dom0, isl_dim_param, Id1);
2546
2547 bool Involves0Id1 = isl_set_involves_dims(Dom0, isl_dim_param, Dim1, 1);
2548 bool Involves1Id0 = isl_set_involves_dims(Dom1, isl_dim_param, Dim0, 1);
2549 assert(!(Involves0Id1 && Involves1Id0));
2550
2551 isl_id_free(Id0);
2552 isl_id_free(Id1);
2553
2554 return Involves1Id0;
2555 };
2556
2557 std::stable_sort(InvariantAccesses.begin(), InvariantAccesses.end(),
2558 compareInvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002559}
2560
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002561const ScopArrayInfo *
2562Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Michael Kruse28468772015-09-14 15:45:33 +00002563 ArrayRef<const SCEV *> Sizes, bool IsPHI) {
Tobias Grosser92245222015-07-28 14:53:44 +00002564 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002565 if (!SAI) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002566 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, IsPHI,
2567 this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002568 } else {
2569 if (Sizes.size() > SAI->getNumberOfDimensions())
2570 SAI->updateSizes(Sizes);
2571 }
Tobias Grosserab671442015-05-23 05:58:27 +00002572 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002573}
2574
Tobias Grosser92245222015-07-28 14:53:44 +00002575const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, bool IsPHI) {
2576 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002577 assert(SAI && "No ScopArrayInfo available for this base pointer");
2578 return SAI;
2579}
2580
Tobias Grosser74394f02013-01-14 22:40:23 +00002581std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002582std::string Scop::getAssumedContextStr() const {
2583 return stringFromIslObj(AssumedContext);
2584}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002585std::string Scop::getBoundaryContextStr() const {
2586 return stringFromIslObj(BoundaryContext);
2587}
Tobias Grosser75805372011-04-29 06:27:02 +00002588
2589std::string Scop::getNameStr() const {
2590 std::string ExitName, EntryName;
2591 raw_string_ostream ExitStr(ExitName);
2592 raw_string_ostream EntryStr(EntryName);
2593
Tobias Grosserf240b482014-01-09 10:42:15 +00002594 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002595 EntryStr.str();
2596
2597 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00002598 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002599 ExitStr.str();
2600 } else
2601 ExitName = "FunctionExit";
2602
2603 return EntryName + "---" + ExitName;
2604}
2605
Tobias Grosser74394f02013-01-14 22:40:23 +00002606__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00002607__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002608 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00002609}
2610
Tobias Grossere86109f2013-10-29 21:05:49 +00002611__isl_give isl_set *Scop::getAssumedContext() const {
2612 return isl_set_copy(AssumedContext);
2613}
2614
Johannes Doerfert43788c52015-08-20 05:58:56 +00002615__isl_give isl_set *Scop::getRuntimeCheckContext() const {
2616 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002617 RuntimeCheckContext =
2618 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
2619 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002620 return RuntimeCheckContext;
2621}
2622
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002623bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002624 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002625 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002626 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
2627 isl_set_free(RuntimeCheckContext);
2628 return IsFeasible;
2629}
2630
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002631void Scop::addAssumption(__isl_take isl_set *Set) {
2632 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00002633 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002634}
2635
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002636__isl_give isl_set *Scop::getBoundaryContext() const {
2637 return isl_set_copy(BoundaryContext);
2638}
2639
Tobias Grosser75805372011-04-29 06:27:02 +00002640void Scop::printContext(raw_ostream &OS) const {
2641 OS << "Context:\n";
2642
2643 if (!Context) {
2644 OS.indent(4) << "n/a\n\n";
2645 return;
2646 }
2647
2648 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00002649
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002650 OS.indent(4) << "Assumed Context:\n";
2651 if (!AssumedContext) {
2652 OS.indent(4) << "n/a\n\n";
2653 return;
2654 }
2655
2656 OS.indent(4) << getAssumedContextStr() << "\n";
2657
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002658 OS.indent(4) << "Boundary Context:\n";
2659 if (!BoundaryContext) {
2660 OS.indent(4) << "n/a\n\n";
2661 return;
2662 }
2663
2664 OS.indent(4) << getBoundaryContextStr() << "\n";
2665
Tobias Grosser083d3d32014-06-28 08:59:45 +00002666 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00002667 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00002668 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
2669 }
Tobias Grosser75805372011-04-29 06:27:02 +00002670}
2671
Johannes Doerfertb164c792014-09-18 11:17:17 +00002672void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002673 int noOfGroups = 0;
2674 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002675 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002676 noOfGroups += 1;
2677 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002678 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002679 }
2680
Tobias Grosserbb853c22015-07-25 12:31:03 +00002681 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00002682 if (MinMaxAliasGroups.empty()) {
2683 OS.indent(8) << "n/a\n";
2684 return;
2685 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002686
Tobias Grosserbb853c22015-07-25 12:31:03 +00002687 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002688
2689 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002690 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002691 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002692 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002693 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2694 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002695 }
2696 OS << " ]]\n";
2697 }
2698
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002699 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002700 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00002701 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002702 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002703 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2704 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002705 }
2706 OS << " ]]\n";
2707 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002708 }
2709}
2710
Tobias Grosser75805372011-04-29 06:27:02 +00002711void Scop::printStatements(raw_ostream &OS) const {
2712 OS << "Statements {\n";
2713
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002714 for (const ScopStmt &Stmt : *this)
2715 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00002716
2717 OS.indent(4) << "}\n";
2718}
2719
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002720void Scop::printArrayInfo(raw_ostream &OS) const {
2721 OS << "Arrays {\n";
2722
Tobias Grosserab671442015-05-23 05:58:27 +00002723 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002724 Array.second->print(OS);
2725
2726 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002727
2728 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
2729
2730 for (auto &Array : arrays())
2731 Array.second->print(OS, /* SizeAsPwAff */ true);
2732
2733 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002734}
2735
Tobias Grosser75805372011-04-29 06:27:02 +00002736void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00002737 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
2738 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00002739 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00002740 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002741 OS.indent(4) << "Invariant Accesses: {\n";
2742 for (const auto &IA : InvariantAccesses) {
2743 IA.first->print(OS);
2744 OS.indent(12) << "Execution Context: " << IA.second << "\n";
2745 }
2746 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00002747 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002748 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002749 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00002750 printStatements(OS.indent(4));
2751}
2752
2753void Scop::dump() const { print(dbgs()); }
2754
Tobias Grosser9a38ab82011-11-08 15:41:03 +00002755isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00002756
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002757__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
2758 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00002759}
2760
Tobias Grosser808cd692015-07-14 09:33:13 +00002761__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002762 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002763
Tobias Grosser808cd692015-07-14 09:33:13 +00002764 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002765 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002766
2767 return Domain;
2768}
2769
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002770__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002771 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002772
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002773 for (ScopStmt &Stmt : *this) {
2774 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002775 if (!MA->isMustWrite())
2776 continue;
2777
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002778 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002779 isl_map *AccessDomain = MA->getAccessRelation();
2780 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2781 Write = isl_union_map_add_map(Write, AccessDomain);
2782 }
2783 }
2784 return isl_union_map_coalesce(Write);
2785}
2786
2787__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002788 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002789
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002790 for (ScopStmt &Stmt : *this) {
2791 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002792 if (!MA->isMayWrite())
2793 continue;
2794
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002795 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002796 isl_map *AccessDomain = MA->getAccessRelation();
2797 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2798 Write = isl_union_map_add_map(Write, AccessDomain);
2799 }
2800 }
2801 return isl_union_map_coalesce(Write);
2802}
2803
Tobias Grosser37eb4222014-02-20 21:43:54 +00002804__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002805 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002806
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002807 for (ScopStmt &Stmt : *this) {
2808 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002809 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002810 continue;
2811
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002812 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002813 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002814 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2815 Write = isl_union_map_add_map(Write, AccessDomain);
2816 }
2817 }
2818 return isl_union_map_coalesce(Write);
2819}
2820
2821__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002822 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002823
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002824 for (ScopStmt &Stmt : *this) {
2825 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002826 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002827 continue;
2828
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002829 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002830 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002831
2832 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2833 Read = isl_union_map_add_map(Read, AccessDomain);
2834 }
2835 }
2836 return isl_union_map_coalesce(Read);
2837}
2838
Tobias Grosser808cd692015-07-14 09:33:13 +00002839__isl_give isl_union_map *Scop::getSchedule() const {
2840 auto Tree = getScheduleTree();
2841 auto S = isl_schedule_get_map(Tree);
2842 isl_schedule_free(Tree);
2843 return S;
2844}
Tobias Grosser37eb4222014-02-20 21:43:54 +00002845
Tobias Grosser808cd692015-07-14 09:33:13 +00002846__isl_give isl_schedule *Scop::getScheduleTree() const {
2847 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
2848 getDomains());
2849}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002850
Tobias Grosser808cd692015-07-14 09:33:13 +00002851void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
2852 auto *S = isl_schedule_from_domain(getDomains());
2853 S = isl_schedule_insert_partial_schedule(
2854 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
2855 isl_schedule_free(Schedule);
2856 Schedule = S;
2857}
2858
2859void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
2860 isl_schedule_free(Schedule);
2861 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00002862}
2863
2864bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
2865 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002866 for (ScopStmt &Stmt : *this) {
2867 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002868 isl_union_set *NewStmtDomain = isl_union_set_intersect(
2869 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
2870
2871 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
2872 isl_union_set_free(StmtDomain);
2873 isl_union_set_free(NewStmtDomain);
2874 continue;
2875 }
2876
2877 Changed = true;
2878
2879 isl_union_set_free(StmtDomain);
2880 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
2881
2882 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002883 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002884 isl_union_set_free(NewStmtDomain);
2885 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002886 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002887 }
2888 isl_union_set_free(Domain);
2889 return Changed;
2890}
2891
Tobias Grosser75805372011-04-29 06:27:02 +00002892ScalarEvolution *Scop::getSE() const { return SE; }
2893
Johannes Doerfertf5673802015-10-01 23:48:18 +00002894bool Scop::isIgnored(RegionNode *RN) {
2895 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser75805372011-04-29 06:27:02 +00002896
Johannes Doerfertf5673802015-10-01 23:48:18 +00002897 // Check if there are accesses contained.
2898 bool ContainsAccesses = false;
2899 if (!RN->isSubRegion())
2900 ContainsAccesses = getAccessFunctions(BB);
2901 else
2902 for (BasicBlock *RBB : RN->getNodeAs<Region>()->blocks())
2903 ContainsAccesses |= (getAccessFunctions(RBB) != nullptr);
2904 if (!ContainsAccesses)
2905 return true;
2906
2907 // Check for reachability via non-error blocks.
2908 if (!DomainMap.count(BB))
2909 return true;
2910
2911 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002912 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002913 return true;
2914
2915 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00002916}
2917
Tobias Grosser808cd692015-07-14 09:33:13 +00002918struct MapToDimensionDataTy {
2919 int N;
2920 isl_union_pw_multi_aff *Res;
2921};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002922
Tobias Grosser808cd692015-07-14 09:33:13 +00002923// @brief Create a function that maps the elements of 'Set' to its N-th
2924// dimension.
2925//
2926// The result is added to 'User->Res'.
2927//
2928// @param Set The input set.
2929// @param N The dimension to map to.
2930//
2931// @returns Zero if no error occurred, non-zero otherwise.
2932static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
2933 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
2934 int Dim;
2935 isl_space *Space;
2936 isl_pw_multi_aff *PMA;
2937
2938 Dim = isl_set_dim(Set, isl_dim_set);
2939 Space = isl_set_get_space(Set);
2940 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
2941 Dim - Data->N);
2942 if (Data->N > 1)
2943 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
2944 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
2945
2946 isl_set_free(Set);
2947
2948 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002949}
2950
Tobias Grosser808cd692015-07-14 09:33:13 +00002951// @brief Create a function that maps the elements of Domain to their Nth
2952// dimension.
2953//
2954// @param Domain The set of elements to map.
2955// @param N The dimension to map to.
2956static __isl_give isl_multi_union_pw_aff *
2957mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002958 if (N <= 0 || isl_union_set_is_empty(Domain)) {
2959 isl_union_set_free(Domain);
2960 return nullptr;
2961 }
2962
Tobias Grosser808cd692015-07-14 09:33:13 +00002963 struct MapToDimensionDataTy Data;
2964 isl_space *Space;
2965
2966 Space = isl_union_set_get_space(Domain);
2967 Data.N = N;
2968 Data.Res = isl_union_pw_multi_aff_empty(Space);
2969 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
2970 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
2971
2972 isl_union_set_free(Domain);
2973 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
2974}
2975
Michael Kruse9d080092015-09-11 21:41:48 +00002976ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00002977 ScopStmt *Stmt;
2978 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00002979 Stmts.emplace_back(*this, *BB);
Tobias Grosser808cd692015-07-14 09:33:13 +00002980 Stmt = &Stmts.back();
2981 StmtMap[BB] = Stmt;
2982 } else {
2983 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00002984 Stmts.emplace_back(*this, *R);
Tobias Grosser808cd692015-07-14 09:33:13 +00002985 Stmt = &Stmts.back();
2986 for (BasicBlock *BB : R->blocks())
2987 StmtMap[BB] = Stmt;
2988 }
2989 return Stmt;
2990}
2991
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002992void Scop::buildSchedule(
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002993 Region *R,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002994 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00002995
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002996 if (SD.isNonAffineSubRegion(R, &getRegion())) {
Johannes Doerfertc6987c12015-09-26 13:41:43 +00002997 Loop *L = getLoopSurroundingRegion(*R, LI);
2998 auto &LSchedulePair = LoopSchedules[L];
Michael Krusecac948e2015-10-02 13:53:07 +00002999 ScopStmt *Stmt = getStmtForBasicBlock(R->getEntry());
Michael Kruseafe06702015-10-02 16:33:27 +00003000 isl_set *Domain = Stmt->getDomain();
Michael Krusecac948e2015-10-02 13:53:07 +00003001 auto *UDomain = isl_union_set_from_set(Domain);
3002 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003003 LSchedulePair.first = StmtSchedule;
3004 return;
3005 }
3006
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003007 ReversePostOrderTraversal<Region *> RTraversal(R);
3008 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00003009
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003010 if (RN->isSubRegion()) {
3011 Region *SubRegion = RN->getNodeAs<Region>();
3012 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003013 buildSchedule(SubRegion, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003014 continue;
3015 }
Tobias Grosser75805372011-04-29 06:27:02 +00003016 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003017
3018 Loop *L = getRegionNodeLoop(RN, LI);
3019 int LD = getRelativeLoopDepth(L);
3020 auto &LSchedulePair = LoopSchedules[L];
3021 LSchedulePair.second += getNumBlocksInRegionNode(RN);
3022
Michael Krusecac948e2015-10-02 13:53:07 +00003023 BasicBlock *BB = getRegionNodeBasicBlock(RN);
3024 ScopStmt *Stmt = getStmtForBasicBlock(BB);
3025 if (Stmt) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003026 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3027 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
3028 LSchedulePair.first =
3029 combineInSequence(LSchedulePair.first, StmtSchedule);
3030 }
3031
3032 unsigned NumVisited = LSchedulePair.second;
3033 while (L && NumVisited == L->getNumBlocks()) {
3034 auto *LDomain = isl_schedule_get_domain(LSchedulePair.first);
3035 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
3036 LSchedulePair.first =
3037 isl_schedule_insert_partial_schedule(LSchedulePair.first, MUPA);
3038
3039 auto *PL = L->getParentLoop();
3040 assert(LoopSchedules.count(PL));
3041 auto &PSchedulePair = LoopSchedules[PL];
3042 PSchedulePair.first =
3043 combineInSequence(PSchedulePair.first, LSchedulePair.first);
3044 PSchedulePair.second += NumVisited;
3045
3046 L = PL;
3047 NumVisited = PSchedulePair.second;
3048 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003049 }
Tobias Grosser75805372011-04-29 06:27:02 +00003050}
3051
Johannes Doerfert7c494212014-10-31 23:13:39 +00003052ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003053 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003054 if (StmtMapIt == StmtMap.end())
3055 return nullptr;
3056 return StmtMapIt->second;
3057}
3058
Johannes Doerfert96425c22015-08-30 21:13:53 +00003059int Scop::getRelativeLoopDepth(const Loop *L) const {
3060 Loop *OuterLoop =
3061 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3062 if (!OuterLoop)
3063 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003064 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3065}
3066
Michael Krused868b5d2015-09-10 15:25:24 +00003067void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003068 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003069
3070 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3071 // true, are not modeled as ordinary PHI nodes as they are not part of the
3072 // region. However, we model the operands in the predecessor blocks that are
3073 // part of the region as regular scalar accesses.
3074
3075 // If we can synthesize a PHI we can skip it, however only if it is in
3076 // the region. If it is not it can only be in the exit block of the region.
3077 // In this case we model the operands but not the PHI itself.
3078 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3079 return;
3080
3081 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3082 // detection. Hence, the PHI is a load of a new memory location in which the
3083 // incoming value was written at the end of the incoming basic block.
3084 bool OnlyNonAffineSubRegionOperands = true;
3085 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3086 Value *Op = PHI->getIncomingValue(u);
3087 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3088
3089 // Do not build scalar dependences inside a non-affine subregion.
3090 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3091 continue;
3092
3093 OnlyNonAffineSubRegionOperands = false;
3094
3095 if (!R.contains(OpBB))
3096 continue;
3097
3098 Instruction *OpI = dyn_cast<Instruction>(Op);
3099 if (OpI) {
3100 BasicBlock *OpIBB = OpI->getParent();
3101 // As we pretend there is a use (or more precise a write) of OpI in OpBB
3102 // we have to insert a scalar dependence from the definition of OpI to
3103 // OpBB if the definition is not in OpBB.
3104 if (OpIBB != OpBB) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003105 addScalarReadAccess(OpI, PHI, OpBB);
3106 addScalarWriteAccess(OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003107 }
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003108 } else if (ModelReadOnlyScalars && !isa<Constant>(Op)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003109 addScalarReadAccess(Op, PHI, OpBB);
Michael Kruse7bf39442015-09-10 12:46:52 +00003110 }
3111
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003112 addPHIWriteAccess(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003113 }
3114
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003115 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3116 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003117 }
3118}
3119
Michael Krused868b5d2015-09-10 15:25:24 +00003120bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
3121 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003122 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
3123 if (isIgnoredIntrinsic(Inst))
3124 return false;
3125
3126 bool AnyCrossStmtUse = false;
3127 BasicBlock *ParentBB = Inst->getParent();
3128
3129 for (User *U : Inst->users()) {
3130 Instruction *UI = dyn_cast<Instruction>(U);
3131
3132 // Ignore the strange user
3133 if (UI == 0)
3134 continue;
3135
3136 BasicBlock *UseParent = UI->getParent();
3137
3138 // Ignore the users in the same BB (statement)
3139 if (UseParent == ParentBB)
3140 continue;
3141
3142 // Do not build scalar dependences inside a non-affine subregion.
3143 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
3144 continue;
3145
3146 // Check whether or not the use is in the SCoP.
3147 if (!R->contains(UseParent)) {
3148 AnyCrossStmtUse = true;
3149 continue;
3150 }
3151
3152 // If the instruction can be synthesized and the user is in the region
3153 // we do not need to add scalar dependences.
3154 if (canSynthesizeInst)
3155 continue;
3156
3157 // No need to translate these scalar dependences into polyhedral form,
3158 // because synthesizable scalars can be generated by the code generator.
3159 if (canSynthesize(UI, LI, SE, R))
3160 continue;
3161
3162 // Skip PHI nodes in the region as they handle their operands on their own.
3163 if (isa<PHINode>(UI))
3164 continue;
3165
3166 // Now U is used in another statement.
3167 AnyCrossStmtUse = true;
3168
3169 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00003170 // Use the def instruction as base address of the MemoryAccess, so that it
3171 // will become the name of the scalar access in the polyhedral form.
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003172 addScalarReadAccess(Inst, UI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003173 }
3174
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003175 if (ModelReadOnlyScalars && !isa<PHINode>(Inst)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003176 for (Value *Op : Inst->operands()) {
3177 if (canSynthesize(Op, LI, SE, R))
3178 continue;
3179
3180 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
3181 if (R->contains(OpInst))
3182 continue;
3183
3184 if (isa<Constant>(Op))
3185 continue;
3186
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003187 addScalarReadAccess(Op, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003188 }
3189 }
3190
3191 return AnyCrossStmtUse;
3192}
3193
3194extern MapInsnToMemAcc InsnToMemAcc;
3195
Michael Krusee2bccbb2015-09-18 19:59:43 +00003196void ScopInfo::buildMemoryAccess(
3197 Instruction *Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003198 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3199 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003200 unsigned Size;
3201 Type *SizeType;
3202 Value *Val;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003203 enum MemoryAccess::AccessType Type;
Michael Kruse7bf39442015-09-10 12:46:52 +00003204
3205 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
3206 SizeType = Load->getType();
3207 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003208 Type = MemoryAccess::READ;
Michael Kruse7bf39442015-09-10 12:46:52 +00003209 Val = Load;
3210 } else {
3211 StoreInst *Store = cast<StoreInst>(Inst);
3212 SizeType = Store->getValueOperand()->getType();
3213 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003214 Type = MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003215 Val = Store->getValueOperand();
3216 }
3217
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003218 auto Address = getPointerOperand(*Inst);
3219
3220 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003221 const SCEVUnknown *BasePointer =
3222 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3223
3224 assert(BasePointer && "Could not find base pointer");
3225 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
3226
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003227 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3228 auto NewAddress = Address;
3229 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3230 auto Src = BitCast->getOperand(0);
3231 auto SrcTy = Src->getType();
3232 auto DstTy = BitCast->getType();
3233 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3234 NewAddress = Src;
3235 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003236
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003237 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3238 std::vector<const SCEV *> Subscripts;
3239 std::vector<int> Sizes;
3240 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3241 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003242
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003243 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003244
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003245 bool AllAffineSubcripts = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003246 for (auto Subscript : Subscripts) {
3247 InvariantLoadsSetTy AccessILS;
3248 AllAffineSubcripts =
3249 isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS);
3250
3251 for (LoadInst *LInst : AccessILS)
3252 if (!ScopRIL.count(LInst))
3253 AllAffineSubcripts = false;
3254
3255 if (!AllAffineSubcripts)
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003256 break;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003257 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003258
3259 if (AllAffineSubcripts && Sizes.size() > 0) {
3260 for (auto V : Sizes)
3261 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3262 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003263 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003264 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003265
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003266 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3267 Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00003268 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003269 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003270 }
3271 }
3272
Michael Kruse7bf39442015-09-10 12:46:52 +00003273 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003274 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003275 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3276 AccItr->second.DelinearizedSubscripts,
3277 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003278 return;
3279 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003280
3281 // Check if the access depends on a loop contained in a non-affine subregion.
3282 bool isVariantInNonAffineLoop = false;
3283 if (BoxedLoops) {
3284 SetVector<const Loop *> Loops;
3285 findLoops(AccessFunction, Loops);
3286 for (const Loop *L : Loops)
3287 if (BoxedLoops->count(L))
3288 isVariantInNonAffineLoop = true;
3289 }
3290
Johannes Doerfert09e36972015-10-07 20:17:36 +00003291 InvariantLoadsSetTy AccessILS;
3292 bool IsAffine =
3293 !isVariantInNonAffineLoop &&
3294 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3295
3296 for (LoadInst *LInst : AccessILS)
3297 if (!ScopRIL.count(LInst))
3298 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003299
Michael Krusecaac2b62015-09-26 15:51:44 +00003300 // FIXME: Size of the number of bytes of an array element, not the number of
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003301 // elements as probably intended here.
Tobias Grossera43b6e92015-09-27 17:54:50 +00003302 const SCEV *SizeSCEV =
3303 SE->getConstant(TD->getIntPtrType(Inst->getContext()), Size);
Michael Kruse7bf39442015-09-10 12:46:52 +00003304
Michael Krusee2bccbb2015-09-18 19:59:43 +00003305 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3306 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003307
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003308 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, IsAffine,
3309 ArrayRef<const SCEV *>(AccessFunction),
3310 ArrayRef<const SCEV *>(SizeSCEV), Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003311}
3312
Michael Krused868b5d2015-09-10 15:25:24 +00003313void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003314
3315 if (SD->isNonAffineSubRegion(&SR, &R)) {
3316 for (BasicBlock *BB : SR.blocks())
3317 buildAccessFunctions(R, *BB, &SR);
3318 return;
3319 }
3320
3321 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3322 if (I->isSubRegion())
3323 buildAccessFunctions(R, *I->getNodeAs<Region>());
3324 else
3325 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
3326}
3327
Michael Krusecac948e2015-10-02 13:53:07 +00003328void ScopInfo::buildStmts(Region &SR) {
3329 Region *R = getRegion();
3330
3331 if (SD->isNonAffineSubRegion(&SR, R)) {
3332 scop->addScopStmt(nullptr, &SR);
3333 return;
3334 }
3335
3336 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3337 if (I->isSubRegion())
3338 buildStmts(*I->getNodeAs<Region>());
3339 else
3340 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
3341}
3342
Michael Krused868b5d2015-09-10 15:25:24 +00003343void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
3344 Region *NonAffineSubRegion,
3345 bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003346 Loop *L = LI->getLoopFor(&BB);
3347
3348 // The set of loops contained in non-affine subregions that are part of R.
3349 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3350
Johannes Doerfert09e36972015-10-07 20:17:36 +00003351 // The set of loads that are required to be invariant.
3352 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
3353
Michael Kruse7bf39442015-09-10 12:46:52 +00003354 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
3355 Instruction *Inst = I;
3356
3357 PHINode *PHI = dyn_cast<PHINode>(Inst);
3358 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003359 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003360
3361 // For the exit block we stop modeling after the last PHI node.
3362 if (!PHI && IsExitBlock)
3363 break;
3364
Johannes Doerfert09e36972015-10-07 20:17:36 +00003365 // TODO: At this point we only know that elements of ScopRIL have to be
3366 // invariant and will be hoisted for the SCoP to be processed. Though,
3367 // there might be other invariant accesses that will be hoisted and
3368 // that would allow to make a non-affine access affine.
Michael Kruse7bf39442015-09-10 12:46:52 +00003369 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
Johannes Doerfert09e36972015-10-07 20:17:36 +00003370 buildMemoryAccess(Inst, L, &R, BoxedLoops, ScopRIL);
Michael Kruse7bf39442015-09-10 12:46:52 +00003371
3372 if (isIgnoredIntrinsic(Inst))
3373 continue;
3374
Johannes Doerfert09e36972015-10-07 20:17:36 +00003375 // Do not build scalar dependences for required invariant loads as we will
3376 // hoist them later on anyway or drop the SCoP if we cannot.
3377 if (ScopRIL.count(dyn_cast<LoadInst>(Inst)))
3378 continue;
3379
Michael Kruse7bf39442015-09-10 12:46:52 +00003380 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00003381 if (!isa<StoreInst>(Inst))
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003382 addScalarWriteAccess(Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003383 }
3384 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003385}
Michael Kruse7bf39442015-09-10 12:46:52 +00003386
Michael Kruse2d0ece92015-09-24 11:41:21 +00003387void ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3388 MemoryAccess::AccessType Type,
3389 Value *BaseAddress, unsigned ElemBytes,
3390 bool Affine, Value *AccessValue,
3391 ArrayRef<const SCEV *> Subscripts,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003392 ArrayRef<const SCEV *> Sizes,
3393 MemoryAccess::AccessOrigin Origin) {
Michael Krusecac948e2015-10-02 13:53:07 +00003394 ScopStmt *Stmt = scop->getStmtForBasicBlock(BB);
3395
3396 // Do not create a memory access for anything not in the SCoP. It would be
3397 // ignored anyway.
3398 if (!Stmt)
3399 return;
3400
Michael Krusee2bccbb2015-09-18 19:59:43 +00003401 AccFuncSetType &AccList = AccFuncMap[BB];
3402 size_t Identifier = AccList.size();
Michael Kruse7bf39442015-09-10 12:46:52 +00003403
Michael Krusee2bccbb2015-09-18 19:59:43 +00003404 Value *BaseAddr = BaseAddress;
3405 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3406
3407 std::string IdName = "__polly_array_ref_" + std::to_string(Identifier);
3408 isl_id *Id = isl_id_alloc(ctx, IdName.c_str(), nullptr);
3409
Michael Krusecac948e2015-10-02 13:53:07 +00003410 bool isApproximated =
3411 Stmt->isRegionStmt() && (Stmt->getRegion()->getEntry() != BB);
3412 if (isApproximated && Type == MemoryAccess::MUST_WRITE)
3413 Type = MemoryAccess::MAY_WRITE;
3414
3415 AccList.emplace_back(Stmt, Inst, Id, Type, BaseAddress, ElemBytes, Affine,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003416 Subscripts, Sizes, AccessValue, Origin, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00003417 Stmt->addAccess(&AccList.back());
Michael Kruse7bf39442015-09-10 12:46:52 +00003418}
3419
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003420void ScopInfo::addExplicitAccess(
3421 Instruction *MemAccInst, MemoryAccess::AccessType Type, Value *BaseAddress,
3422 unsigned ElemBytes, bool IsAffine, ArrayRef<const SCEV *> Subscripts,
3423 ArrayRef<const SCEV *> Sizes, Value *AccessValue) {
3424 assert(isa<LoadInst>(MemAccInst) || isa<StoreInst>(MemAccInst));
3425 assert(isa<LoadInst>(MemAccInst) == (Type == MemoryAccess::READ));
3426 addMemoryAccess(MemAccInst->getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003427 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
3428 MemoryAccess::EXPLICIT);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003429}
3430void ScopInfo::addScalarWriteAccess(Instruction *Value) {
3431 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
3432 true, Value, ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003433 ArrayRef<const SCEV *>(), MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003434}
3435void ScopInfo::addScalarReadAccess(Value *Value, Instruction *User) {
3436 assert(!isa<PHINode>(User));
3437 addMemoryAccess(User->getParent(), User, MemoryAccess::READ, Value, 1, true,
3438 Value, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003439 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003440}
3441void ScopInfo::addScalarReadAccess(Value *Value, PHINode *User,
3442 BasicBlock *UserBB) {
3443 addMemoryAccess(UserBB, User, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003444 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3445 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003446}
3447void ScopInfo::addPHIWriteAccess(PHINode *PHI, BasicBlock *IncomingBlock,
3448 Value *IncomingValue, bool IsExitBlock) {
3449 addMemoryAccess(IncomingBlock, IncomingBlock->getTerminator(),
3450 MemoryAccess::MUST_WRITE, PHI, 1, true, IncomingValue,
3451 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003452 IsExitBlock ? MemoryAccess::SCALAR : MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003453}
3454void ScopInfo::addPHIReadAccess(PHINode *PHI) {
3455 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003456 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3457 MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003458}
3459
Michael Kruse76e924d2015-09-30 09:16:07 +00003460void ScopInfo::buildScop(Region &R, DominatorTree &DT) {
Michael Kruse9d080092015-09-11 21:41:48 +00003461 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003462 scop = new Scop(R, AccFuncMap, *SD, *SE, DT, *LI, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00003463
Michael Krusecac948e2015-10-02 13:53:07 +00003464 buildStmts(R);
Michael Kruse7bf39442015-09-10 12:46:52 +00003465 buildAccessFunctions(R, R);
3466
3467 // In case the region does not have an exiting block we will later (during
3468 // code generation) split the exit block. This will move potential PHI nodes
3469 // from the current exit block into the new region exiting block. Hence, PHI
3470 // nodes that are at this point not part of the region will be.
3471 // To handle these PHI nodes later we will now model their operands as scalar
3472 // accesses. Note that we do not model anything in the exit block if we have
3473 // an exiting block in the region, as there will not be any splitting later.
3474 if (!R.getExitingBlock())
3475 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
3476
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003477 scop->init(*AA);
Michael Kruse7bf39442015-09-10 12:46:52 +00003478}
3479
Michael Krused868b5d2015-09-10 15:25:24 +00003480void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00003481 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00003482 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00003483 return;
3484 }
3485
Michael Kruse9d080092015-09-11 21:41:48 +00003486 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00003487}
3488
Michael Krused868b5d2015-09-10 15:25:24 +00003489void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00003490 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00003491 if (scop) {
3492 delete scop;
3493 scop = 0;
3494 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003495}
3496
3497//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00003498ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00003499 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00003500 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00003501}
3502
3503ScopInfo::~ScopInfo() {
3504 clear();
3505 isl_ctx_free(ctx);
3506}
3507
Tobias Grosser75805372011-04-29 06:27:02 +00003508void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Michael Krused868b5d2015-09-10 15:25:24 +00003509 AU.addRequiredID(IndependentBlocksID);
Chandler Carruthf5579872015-01-17 14:16:56 +00003510 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00003511 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00003512 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00003513 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
3514 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003515 AU.addRequired<AAResultsWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00003516 AU.setPreservesAll();
3517}
3518
3519bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00003520 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00003521
Michael Krused868b5d2015-09-10 15:25:24 +00003522 if (!SD->isMaxRegionInScop(*R))
3523 return false;
3524
3525 Function *F = R->getEntry()->getParent();
3526 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3527 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3528 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3529 TD = &F->getParent()->getDataLayout();
3530 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Krused868b5d2015-09-10 15:25:24 +00003531
Michael Kruse76e924d2015-09-30 09:16:07 +00003532 buildScop(*R, DT);
Tobias Grosser75805372011-04-29 06:27:02 +00003533
Tobias Grosserd6a50b32015-05-30 06:26:21 +00003534 DEBUG(scop->print(dbgs()));
3535
Michael Kruseafe06702015-10-02 16:33:27 +00003536 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003537 delete scop;
3538 scop = nullptr;
3539 return false;
3540 }
3541
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003542 // Statistics.
3543 ++ScopFound;
3544 if (scop->getMaxLoopDepth() > 0)
3545 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00003546 return false;
3547}
3548
3549char ScopInfo::ID = 0;
3550
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003551Pass *polly::createScopInfoPass() { return new ScopInfo(); }
3552
Tobias Grosser73600b82011-10-08 00:30:40 +00003553INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
3554 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003555 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003556INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00003557INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00003558INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00003559INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003560INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003561INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00003562INITIALIZE_PASS_END(ScopInfo, "polly-scops",
3563 "Polly - Create polyhedral description of Scops", false,
3564 false)