blob: d002b52fd73cd60d2ef45ef9728be92d719fd53f [file] [log] [blame]
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001
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//===----------------------------------------------------------------------===//
96/// Helper Classes
97
98void Comparison::print(raw_ostream &OS) const {
99 // Not yet implemented.
100}
101
Michael Kruse046dde42015-08-10 13:01:57 +0000102// Create a sequence of two schedules. Either argument may be null and is
103// interpreted as the empty schedule. Can also return null if both schedules are
104// empty.
105static __isl_give isl_schedule *
106combineInSequence(__isl_take isl_schedule *Prev,
107 __isl_take isl_schedule *Succ) {
108 if (!Prev)
109 return Succ;
110 if (!Succ)
111 return Prev;
112
113 return isl_schedule_sequence(Prev, Succ);
114}
115
Johannes Doerferte7044942015-02-24 11:58:30 +0000116static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
117 const ConstantRange &Range,
118 int dim,
119 enum isl_dim_type type) {
120 isl_val *V;
121 isl_ctx *ctx = isl_set_get_ctx(S);
122
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000123 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
124 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000125 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000126 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
127
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000128 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000129 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000130 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000131 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000132 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
133
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000134 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000135 return isl_set_union(SLB, SUB);
136 else
137 return isl_set_intersect(SLB, SUB);
138}
139
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000140static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
141 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
142 if (!BasePtrLI)
143 return nullptr;
144
145 if (!S->getRegion().contains(BasePtrLI))
146 return nullptr;
147
148 ScalarEvolution &SE = *S->getSE();
149
150 auto *OriginBaseSCEV =
151 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
152 if (!OriginBaseSCEV)
153 return nullptr;
154
155 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
156 if (!OriginBaseSCEVUnknown)
157 return nullptr;
158
159 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue());
160}
161
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000162ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000163 ArrayRef<const SCEV *> Sizes, bool IsPHI, Scop *S)
164 : BasePtr(BasePtr), ElementType(ElementType), IsPHI(IsPHI), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000165 std::string BasePtrName =
166 getIslCompatibleName("MemRef_", BasePtr, IsPHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000167 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000168
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000169 updateSizes(Sizes);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000170 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
171 if (BasePtrOriginSAI)
172 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000173}
174
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000175__isl_give isl_space *ScopArrayInfo::getSpace() const {
176 auto Space =
177 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
178 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
179 return Space;
180}
181
182void ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
183#ifndef NDEBUG
184 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
185 int ExtraDimsNew = NewSizes.size() - SharedDims;
186 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
187 for (int i = 0; i < SharedDims; i++) {
188 assert(NewSizes[i + ExtraDimsNew] == DimensionSizes[i + ExtraDimsOld] &&
189 "Array update with non-matching dimension sizes");
190 }
191#endif
192
193 DimensionSizes.clear();
194 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
195 NewSizes.end());
196 for (isl_pw_aff *Size : DimensionSizesPw)
197 isl_pw_aff_free(Size);
198 DimensionSizesPw.clear();
199 for (const SCEV *Expr : DimensionSizes) {
200 isl_pw_aff *Size = S.getPwAff(Expr);
201 DimensionSizesPw.push_back(Size);
202 }
203}
204
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000205ScopArrayInfo::~ScopArrayInfo() {
206 isl_id_free(Id);
207 for (isl_pw_aff *Size : DimensionSizesPw)
208 isl_pw_aff_free(Size);
209}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000210
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000211std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
212
213int ScopArrayInfo::getElemSizeInBytes() const {
214 return ElementType->getPrimitiveSizeInBits() / 8;
215}
216
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000217isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
218
219void ScopArrayInfo::dump() const { print(errs()); }
220
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000221void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000222 OS.indent(8) << *getElementType() << " " << getName() << "[*]";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000223 for (unsigned u = 0; u < getNumberOfDimensions(); u++) {
224 OS << "[";
225
226 if (SizeAsPwAff)
227 OS << " " << DimensionSizesPw[u] << " ";
228 else
229 OS << *DimensionSizes[u];
230
231 OS << "]";
232 }
233
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000234 if (BasePtrOriginSAI)
235 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
236
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000237 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000238}
239
240const ScopArrayInfo *
241ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
242 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
243 assert(Id && "Output dimension didn't have an ID");
244 return getFromId(Id);
245}
246
247const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
248 void *User = isl_id_get_user(Id);
249 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
250 isl_id_free(Id);
251 return SAI;
252}
253
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000254void MemoryAccess::updateDimensionality() {
255 auto ArraySpace = getScopArrayInfo()->getSpace();
256 auto AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
257
258 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
259 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
260 auto DimsMissing = DimsArray - DimsAccess;
261
262 auto Map = isl_map_from_domain_and_range(isl_set_universe(AccessSpace),
263 isl_set_universe(ArraySpace));
264
265 for (unsigned i = 0; i < DimsMissing; i++)
266 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
267
268 for (unsigned i = DimsMissing; i < DimsArray; i++)
269 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
270
271 AccessRelation = isl_map_apply_range(AccessRelation, Map);
272}
273
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000274const std::string
275MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
276 switch (RT) {
277 case MemoryAccess::RT_NONE:
278 llvm_unreachable("Requested a reduction operator string for a memory "
279 "access which isn't a reduction");
280 case MemoryAccess::RT_ADD:
281 return "+";
282 case MemoryAccess::RT_MUL:
283 return "*";
284 case MemoryAccess::RT_BOR:
285 return "|";
286 case MemoryAccess::RT_BXOR:
287 return "^";
288 case MemoryAccess::RT_BAND:
289 return "&";
290 }
291 llvm_unreachable("Unknown reduction type");
292 return "";
293}
294
Johannes Doerfertf6183392014-07-01 20:52:51 +0000295/// @brief Return the reduction type for a given binary operator
296static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
297 const Instruction *Load) {
298 if (!BinOp)
299 return MemoryAccess::RT_NONE;
300 switch (BinOp->getOpcode()) {
301 case Instruction::FAdd:
302 if (!BinOp->hasUnsafeAlgebra())
303 return MemoryAccess::RT_NONE;
304 // Fall through
305 case Instruction::Add:
306 return MemoryAccess::RT_ADD;
307 case Instruction::Or:
308 return MemoryAccess::RT_BOR;
309 case Instruction::Xor:
310 return MemoryAccess::RT_BXOR;
311 case Instruction::And:
312 return MemoryAccess::RT_BAND;
313 case Instruction::FMul:
314 if (!BinOp->hasUnsafeAlgebra())
315 return MemoryAccess::RT_NONE;
316 // Fall through
317 case Instruction::Mul:
318 if (DisableMultiplicativeReductions)
319 return MemoryAccess::RT_NONE;
320 return MemoryAccess::RT_MUL;
321 default:
322 return MemoryAccess::RT_NONE;
323 }
324}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000325
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000326/// @brief Derive the individual index expressions from a GEP instruction
327///
328/// This function optimistically assumes the GEP references into a fixed size
329/// array. If this is actually true, this function returns a list of array
330/// subscript expressions as SCEV as well as a list of integers describing
331/// the size of the individual array dimensions. Both lists have either equal
332/// length of the size list is one element shorter in case there is no known
333/// size available for the outermost array dimension.
334///
335/// @param GEP The GetElementPtr instruction to analyze.
336///
337/// @return A tuple with the subscript expressions and the dimension sizes.
338static std::tuple<std::vector<const SCEV *>, std::vector<int>>
339getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
340 std::vector<const SCEV *> Subscripts;
341 std::vector<int> Sizes;
342
343 Type *Ty = GEP->getPointerOperandType();
344
345 bool DroppedFirstDim = false;
346
Michael Kruse26ed65e2015-09-24 17:32:49 +0000347 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000348
349 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
350
351 if (i == 1) {
352 if (auto PtrTy = dyn_cast<PointerType>(Ty)) {
353 Ty = PtrTy->getElementType();
354 } else if (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
355 Ty = ArrayTy->getElementType();
356 } else {
357 Subscripts.clear();
358 Sizes.clear();
359 break;
360 }
361 if (auto Const = dyn_cast<SCEVConstant>(Expr))
362 if (Const->getValue()->isZero()) {
363 DroppedFirstDim = true;
364 continue;
365 }
366 Subscripts.push_back(Expr);
367 continue;
368 }
369
370 auto ArrayTy = dyn_cast<ArrayType>(Ty);
371 if (!ArrayTy) {
372 Subscripts.clear();
373 Sizes.clear();
374 break;
375 }
376
377 Subscripts.push_back(Expr);
378 if (!(DroppedFirstDim && i == 2))
379 Sizes.push_back(ArrayTy->getNumElements());
380
381 Ty = ArrayTy->getElementType();
382 }
383
384 return std::make_tuple(Subscripts, Sizes);
385}
386
Tobias Grosser75805372011-04-29 06:27:02 +0000387MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000388 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000389 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000390 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000391}
392
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000393const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
394 isl_id *ArrayId = getArrayId();
395 void *User = isl_id_get_user(ArrayId);
396 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
397 isl_id_free(ArrayId);
398 return SAI;
399}
400
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000401__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000402 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
403}
404
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000405__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
406 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000407 isl_map *Schedule, *ScheduledAccRel;
408 isl_union_set *UDomain;
409
410 UDomain = isl_union_set_from_set(getStatement()->getDomain());
411 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
412 Schedule = isl_map_from_union_map(USchedule);
413 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
414 return isl_pw_multi_aff_from_map(ScheduledAccRel);
415}
416
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000417__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000418 return isl_map_copy(AccessRelation);
419}
420
Johannes Doerferta99130f2014-10-13 12:58:03 +0000421std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000422 return stringFromIslObj(AccessRelation);
423}
424
Johannes Doerferta99130f2014-10-13 12:58:03 +0000425__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000426 return isl_map_get_space(AccessRelation);
427}
428
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000429__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000430 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000431}
432
Tobias Grosser6f730082015-09-05 07:46:47 +0000433std::string MemoryAccess::getNewAccessRelationStr() const {
434 return stringFromIslObj(NewAccessRelation);
435}
436
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000437__isl_give isl_basic_map *
438MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000439 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000440 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000441
Tobias Grosser084d8f72012-05-29 09:29:44 +0000442 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000443 isl_basic_set_universe(Statement->getDomainSpace()),
444 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000445}
446
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000447// Formalize no out-of-bound access assumption
448//
449// When delinearizing array accesses we optimistically assume that the
450// delinearized accesses do not access out of bound locations (the subscript
451// expression of each array evaluates for each statement instance that is
452// executed to a value that is larger than zero and strictly smaller than the
453// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000454// dimension for which we do not need to assume any upper bound. At this point
455// we formalize this assumption to ensure that at code generation time the
456// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000457//
458// To find the set of constraints necessary to avoid out of bound accesses, we
459// first build the set of data locations that are not within array bounds. We
460// then apply the reverse access relation to obtain the set of iterations that
461// may contain invalid accesses and reduce this set of iterations to the ones
462// that are actually executed by intersecting them with the domain of the
463// statement. If we now project out all loop dimensions, we obtain a set of
464// parameters that may cause statement instances to be executed that may
465// possibly yield out of bound memory accesses. The complement of these
466// constraints is the set of constraints that needs to be assumed to ensure such
467// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000468void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000469 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000470 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Michael Krusee2bccbb2015-09-18 19:59:43 +0000471 for (int i = 1, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000472 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
473 isl_pw_aff *Var =
474 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
475 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
476
477 isl_set *DimOutside;
478
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000479 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Michael Krusee2bccbb2015-09-18 19:59:43 +0000480 isl_pw_aff *SizeE = Statement->getPwAff(Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000481
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000482 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
483 Statement->getNumIterators());
484 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
485 isl_space_dim(Space, isl_dim_set));
486 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
487 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000488
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000489 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000490
491 Outside = isl_set_union(Outside, DimOutside);
492 }
493
494 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
495 Outside = isl_set_intersect(Outside, Statement->getDomain());
496 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000497
498 // Remove divs to avoid the construction of overly complicated assumptions.
499 // Doing so increases the set of parameter combinations that are assumed to
500 // not appear. This is always save, but may make the resulting run-time check
501 // bail out more often than strictly necessary.
502 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000503 Outside = isl_set_complement(Outside);
504 Statement->getParent()->addAssumption(Outside);
505 isl_space_free(Space);
506}
507
Johannes Doerferte7044942015-02-24 11:58:30 +0000508void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
509 ScalarEvolution *SE = Statement->getParent()->getSE();
510
511 Value *Ptr = getPointerOperand(*getAccessInstruction());
512 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
513 return;
514
515 auto *PtrSCEV = SE->getSCEV(Ptr);
516 if (isa<SCEVCouldNotCompute>(PtrSCEV))
517 return;
518
519 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
520 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
521 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
522
523 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
524 if (Range.isFullSet())
525 return;
526
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000527 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000528 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000529 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
530 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
531
532 auto Min = LB.sdiv(APInt(BW, ElementSize));
533 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000534
535 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
536 AccessRange =
537 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
538 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
539}
540
Michael Krusee2bccbb2015-09-18 19:59:43 +0000541__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000542 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000543 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000544
545 for (int i = Size - 2; i >= 0; --i) {
546 isl_space *Space;
547 isl_map *MapOne, *MapTwo;
Michael Krusee2bccbb2015-09-18 19:59:43 +0000548 isl_pw_aff *DimSize = Statement->getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000549
550 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
551 isl_pw_aff_free(DimSize);
552 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
553
554 Space = isl_map_get_space(AccessRelation);
555 Space = isl_space_map_from_set(isl_space_range(Space));
556 Space = isl_space_align_params(Space, SpaceSize);
557
558 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
559 isl_id_free(ParamId);
560
561 MapOne = isl_map_universe(isl_space_copy(Space));
562 for (int j = 0; j < Size; ++j)
563 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
564 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
565
566 MapTwo = isl_map_universe(isl_space_copy(Space));
567 for (int j = 0; j < Size; ++j)
568 if (j < i || j > i + 1)
569 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
570
571 isl_local_space *LS = isl_local_space_from_space(Space);
572 isl_constraint *C;
573 C = isl_equality_alloc(isl_local_space_copy(LS));
574 C = isl_constraint_set_constant_si(C, -1);
575 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
576 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
577 MapTwo = isl_map_add_constraint(MapTwo, C);
578 C = isl_equality_alloc(LS);
579 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
580 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
581 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
582 MapTwo = isl_map_add_constraint(MapTwo, C);
583 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
584
585 MapOne = isl_map_union(MapOne, MapTwo);
586 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
587 }
588 return AccessRelation;
589}
590
Michael Krusee2bccbb2015-09-18 19:59:43 +0000591void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
592 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000593
Michael Krusee2bccbb2015-09-18 19:59:43 +0000594 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000595 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000596
Michael Krusee2bccbb2015-09-18 19:59:43 +0000597 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000598 // We overapproximate non-affine accesses with a possible access to the
599 // whole array. For read accesses it does not make a difference, if an
600 // access must or may happen. However, for write accesses it is important to
601 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000602 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000603 AccessRelation =
604 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000605
Michael Krusee2bccbb2015-09-18 19:59:43 +0000606 computeBoundsOnAccessRelation(getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000607 return;
608 }
609
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000610 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000611 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000612
Michael Krusee2bccbb2015-09-18 19:59:43 +0000613 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
614 isl_pw_aff *Affine = Statement->getPwAff(Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000615
Sebastian Pop422e33f2014-06-03 18:16:31 +0000616 if (Size == 1) {
617 // For the non delinearized arrays, divide the access function of the last
618 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000619 //
620 // A stride one array access in C expressed as A[i] is expressed in
621 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
622 // two subsequent values of 'i' index two values that are stored next to
623 // each other in memory. By this division we make this characteristic
624 // obvious again.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000625 isl_val *v = isl_val_int_from_si(Ctx, getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000626 Affine = isl_pw_aff_scale_down_val(Affine, v);
627 }
628
629 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
630
Tobias Grosser79baa212014-04-10 08:38:02 +0000631 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000632 }
633
Michael Krusee2bccbb2015-09-18 19:59:43 +0000634 if (Sizes.size() > 1 && !isa<SCEVConstant>(Sizes[0]))
635 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000636
Tobias Grosser79baa212014-04-10 08:38:02 +0000637 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000638 AccessRelation = isl_map_set_tuple_id(
639 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000640 AccessRelation =
641 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
642
Michael Krusee2bccbb2015-09-18 19:59:43 +0000643 assumeNoOutOfBound();
Tobias Grosseraa660a92015-03-30 00:07:50 +0000644 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000645 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000646}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000647
Michael Krusee2bccbb2015-09-18 19:59:43 +0000648MemoryAccess::MemoryAccess(Instruction *AccessInst, __isl_take isl_id *Id,
649 AccessType Type, Value *BaseAddress,
Michael Kruse2d0ece92015-09-24 11:41:21 +0000650 unsigned ElemBytes, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000651 ArrayRef<const SCEV *> Subscripts,
652 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Michael Kruse8d0b7342015-09-25 21:21:00 +0000653 AccessOrigin Origin, StringRef BaseName)
654 : Id(Id), Origin(Origin), AccType(Type), RedType(RT_NONE),
655 Statement(nullptr), BaseAddr(BaseAddress), BaseName(BaseName),
656 ElemBytes(ElemBytes), Sizes(Sizes.begin(), Sizes.end()),
657 AccessInstruction(AccessInst), AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000658 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
659 NewAccessRelation(nullptr) {}
660
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000661void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000662 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000663 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000664}
665
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000666const std::string MemoryAccess::getReductionOperatorStr() const {
667 return MemoryAccess::getReductionOperatorStr(getReductionType());
668}
669
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000670__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
671
Johannes Doerfertf6183392014-07-01 20:52:51 +0000672raw_ostream &polly::operator<<(raw_ostream &OS,
673 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000674 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000675 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000676 else
677 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000678 return OS;
679}
680
Tobias Grosser75805372011-04-29 06:27:02 +0000681void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000682 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000683 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000684 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000685 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000686 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000687 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000688 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000689 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000690 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000691 break;
692 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000693 OS << "[Reduction Type: " << getReductionType() << "] ";
Michael Kruse8d0b7342015-09-25 21:21:00 +0000694 OS << "[Scalar: " << isImplicit() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000695 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000696 if (hasNewAccessRelation())
697 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000698}
699
Tobias Grosser74394f02013-01-14 22:40:23 +0000700void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000701
702// Create a map in the size of the provided set domain, that maps from the
703// one element of the provided set domain to another element of the provided
704// set domain.
705// The mapping is limited to all points that are equal in all but the last
706// dimension and for which the last dimension of the input is strict smaller
707// than the last dimension of the output.
708//
709// getEqualAndLarger(set[i0, i1, ..., iX]):
710//
711// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
712// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
713//
Tobias Grosserf5338802011-10-06 00:03:35 +0000714static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000715 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000716 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000717 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000718
719 // Set all but the last dimension to be equal for the input and output
720 //
721 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
722 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000723 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000724 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000725
726 // Set the last dimension of the input to be strict smaller than the
727 // last dimension of the output.
728 //
729 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000730 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
731 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000732 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000733}
734
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000735__isl_give isl_set *
736MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000737 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000738 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000739 isl_space *Space = isl_space_range(isl_map_get_space(S));
740 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000741
Sebastian Popa00a0292012-12-18 07:46:06 +0000742 S = isl_map_reverse(S);
743 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000744
Sebastian Popa00a0292012-12-18 07:46:06 +0000745 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
746 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
747 NextScatt = isl_map_apply_domain(NextScatt, S);
748 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000749
Sebastian Popa00a0292012-12-18 07:46:06 +0000750 isl_set *Deltas = isl_map_deltas(NextScatt);
751 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000752}
753
Sebastian Popa00a0292012-12-18 07:46:06 +0000754bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000755 int StrideWidth) const {
756 isl_set *Stride, *StrideX;
757 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000758
Sebastian Popa00a0292012-12-18 07:46:06 +0000759 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000760 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000761 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
762 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
763 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
764 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000765 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000766
Tobias Grosser28dd4862012-01-24 16:42:16 +0000767 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000768 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000769
Tobias Grosser28dd4862012-01-24 16:42:16 +0000770 return IsStrideX;
771}
772
Sebastian Popa00a0292012-12-18 07:46:06 +0000773bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
774 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000775}
776
Sebastian Popa00a0292012-12-18 07:46:06 +0000777bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
778 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000779}
780
Tobias Grosser166c4222015-09-05 07:46:40 +0000781void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
782 isl_map_free(NewAccessRelation);
783 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000784}
Tobias Grosser75805372011-04-29 06:27:02 +0000785
786//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000787
Tobias Grosser808cd692015-07-14 09:33:13 +0000788isl_map *ScopStmt::getSchedule() const {
789 isl_set *Domain = getDomain();
790 if (isl_set_is_empty(Domain)) {
791 isl_set_free(Domain);
792 return isl_map_from_aff(
793 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
794 }
795 auto *Schedule = getParent()->getSchedule();
796 Schedule = isl_union_map_intersect_domain(
797 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
798 if (isl_union_map_is_empty(Schedule)) {
799 isl_set_free(Domain);
800 isl_union_map_free(Schedule);
801 return isl_map_from_aff(
802 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
803 }
804 auto *M = isl_map_from_union_map(Schedule);
805 M = isl_map_coalesce(M);
806 M = isl_map_gist_domain(M, Domain);
807 M = isl_map_coalesce(M);
808 return M;
809}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000810
Johannes Doerfert574182d2015-08-12 10:19:50 +0000811__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000812 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
813 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000814}
815
Tobias Grosser37eb4222014-02-20 21:43:54 +0000816void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
817 assert(isl_set_is_subset(NewDomain, Domain) &&
818 "New domain is not a subset of old domain!");
819 isl_set_free(Domain);
820 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000821}
822
Michael Kruse9d080092015-09-11 21:41:48 +0000823void ScopStmt::buildAccesses(BasicBlock *Block, bool isApproximated) {
824 AccFuncSetType *AFS = Parent.getAccessFunctions(Block);
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000825 if (!AFS)
826 return;
827
Michael Krusee2bccbb2015-09-18 19:59:43 +0000828 for (auto &Access : *AFS) {
829 Instruction *AccessInst = Access.getAccessInstruction();
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000830 Type *ElementType = Access.getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000831
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000832 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Michael Krusee2bccbb2015-09-18 19:59:43 +0000833 Access.getBaseAddr(), ElementType, Access.Sizes, Access.isPHI());
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000834
Michael Krusee2bccbb2015-09-18 19:59:43 +0000835 if (isApproximated && Access.isMustWrite())
836 Access.AccType = MemoryAccess::MAY_WRITE;
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000837
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000838 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
839 if (!MAL)
840 MAL = new MemoryAccessList();
Michael Krusee2bccbb2015-09-18 19:59:43 +0000841 Access.setStatement(this);
842 Access.buildAccessRelation(SAI);
843 MAL->emplace_front(&Access);
844 MemAccs.push_back(MAL->front());
Tobias Grosser75805372011-04-29 06:27:02 +0000845 }
846}
847
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000848void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000849 for (MemoryAccess *MA : *this)
850 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000851
852 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000853}
854
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000855/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
856static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
857 void *User) {
858 isl_set **BoundedParts = static_cast<isl_set **>(User);
859 if (isl_basic_set_is_bounded(BSet))
860 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
861 else
862 isl_basic_set_free(BSet);
863 return isl_stat_ok;
864}
865
866/// @brief Return the bounded parts of @p S.
867static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
868 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
869 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
870 isl_set_free(S);
871 return BoundedParts;
872}
873
874/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
875///
876/// @returns A separation of @p S into first an unbounded then a bounded subset,
877/// both with regards to the dimension @p Dim.
878static std::pair<__isl_give isl_set *, __isl_give isl_set *>
879partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
880
881 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000882 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000883
884 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000885 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000886
887 // Remove dimensions that are greater than Dim as they are not interesting.
888 assert(NumDimsS >= Dim + 1);
889 OnlyDimS =
890 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
891
892 // Create artificial parametric upper bounds for dimensions smaller than Dim
893 // as we are not interested in them.
894 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
895 for (unsigned u = 0; u < Dim; u++) {
896 isl_constraint *C = isl_inequality_alloc(
897 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
898 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
899 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
900 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
901 }
902
903 // Collect all bounded parts of OnlyDimS.
904 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
905
906 // Create the dimensions greater than Dim again.
907 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
908 NumDimsS - Dim - 1);
909
910 // Remove the artificial upper bound parameters again.
911 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
912
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000913 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000914 return std::make_pair(UnboundedParts, BoundedParts);
915}
916
Johannes Doerfert96425c22015-08-30 21:13:53 +0000917static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
918 isl_pw_aff *L, isl_pw_aff *R) {
919 switch (Pred) {
920 case ICmpInst::ICMP_EQ:
921 return isl_pw_aff_eq_set(L, R);
922 case ICmpInst::ICMP_NE:
923 return isl_pw_aff_ne_set(L, R);
924 case ICmpInst::ICMP_SLT:
925 return isl_pw_aff_lt_set(L, R);
926 case ICmpInst::ICMP_SLE:
927 return isl_pw_aff_le_set(L, R);
928 case ICmpInst::ICMP_SGT:
929 return isl_pw_aff_gt_set(L, R);
930 case ICmpInst::ICMP_SGE:
931 return isl_pw_aff_ge_set(L, R);
932 case ICmpInst::ICMP_ULT:
933 return isl_pw_aff_lt_set(L, R);
934 case ICmpInst::ICMP_UGT:
935 return isl_pw_aff_gt_set(L, R);
936 case ICmpInst::ICMP_ULE:
937 return isl_pw_aff_le_set(L, R);
938 case ICmpInst::ICMP_UGE:
939 return isl_pw_aff_ge_set(L, R);
940 default:
941 llvm_unreachable("Non integer predicate not supported");
942 }
943}
944
945/// @brief Build the conditions sets for the branch @p BI in the @p Domain.
946///
947/// This will fill @p ConditionSets with the conditions under which control
948/// will be moved from @p BI to its successors. Hence, @p ConditionSets will
949/// have as many elements as @p BI has successors.
950static void
951buildConditionSets(Scop &S, BranchInst *BI, Loop *L, __isl_keep isl_set *Domain,
952 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
953
954 if (BI->isUnconditional()) {
955 ConditionSets.push_back(isl_set_copy(Domain));
956 return;
957 }
958
959 Value *Condition = BI->getCondition();
960
961 isl_set *ConsequenceCondSet = nullptr;
962 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
963 if (CCond->isZero())
964 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
965 else
966 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
967 } else {
968 auto *ICond = dyn_cast<ICmpInst>(Condition);
969 assert(ICond &&
970 "Condition of exiting branch was neither constant nor ICmp!");
971
972 ScalarEvolution &SE = *S.getSE();
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000973 BasicBlock *BB = BI->getParent();
Johannes Doerfert96425c22015-08-30 21:13:53 +0000974 isl_pw_aff *LHS, *RHS;
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000975 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
976 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
Johannes Doerfert96425c22015-08-30 21:13:53 +0000977 ConsequenceCondSet = buildConditionSet(ICond->getPredicate(), LHS, RHS);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000978
979 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
980 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
981 ConsequenceCondSet =
982 isl_set_set_dim_id(ConsequenceCondSet, isl_dim_set, u, DimId);
983 }
Johannes Doerfert96425c22015-08-30 21:13:53 +0000984 }
985
986 assert(ConsequenceCondSet);
987 isl_set *AlternativeCondSet =
988 isl_set_complement(isl_set_copy(ConsequenceCondSet));
989
990 ConditionSets.push_back(isl_set_coalesce(
991 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
992 ConditionSets.push_back(isl_set_coalesce(
993 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
994}
995
Johannes Doerfert32ae76e2015-09-10 13:12:02 +0000996void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000997 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000998
Tobias Grosser084d8f72012-05-29 09:29:44 +0000999 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1000
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001001 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001002 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001003}
1004
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001005void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001006 isl_ctx *Ctx = Parent.getIslCtx();
1007 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1008 Type *Ty = GEP->getPointerOperandType();
1009 ScalarEvolution &SE = *Parent.getSE();
1010
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001011 std::vector<const SCEV *> Subscripts;
1012 std::vector<int> Sizes;
1013
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001014 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001015
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001016 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001017 Ty = PtrTy->getElementType();
1018 }
1019
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001020 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001021
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001022 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001023
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001024 for (size_t i = 0; i < Sizes.size(); i++) {
1025 auto Expr = Subscripts[i + IndexOffset];
1026 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001027
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001028 if (!isAffineExpr(&Parent.getRegion(), Expr, SE))
1029 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001030
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001031 isl_pw_aff *AccessOffset = getPwAff(Expr);
1032 AccessOffset =
1033 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001034
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001035 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1036 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001037
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001038 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1039 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1040 OutOfBound = isl_set_params(OutOfBound);
1041 isl_set *InBound = isl_set_complement(OutOfBound);
1042 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001043
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001044 // A => B == !A or B
1045 isl_set *InBoundIfExecuted =
1046 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001047
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001048 Parent.addAssumption(InBoundIfExecuted);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001049 }
1050
1051 isl_local_space_free(LSpace);
1052}
1053
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001054void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1055 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001056 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1057 deriveAssumptionsFromGEP(GEP);
1058}
1059
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001060void ScopStmt::collectSurroundingLoops() {
1061 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1062 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1063 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1064 isl_id_free(DimId);
1065 }
1066}
1067
Michael Kruse9d080092015-09-11 21:41:48 +00001068ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001069 : Parent(parent), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001070
Tobias Grosser16c44032015-07-09 07:31:45 +00001071 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001072
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001073 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001074 collectSurroundingLoops();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001075
1076 BasicBlock *EntryBB = R.getEntry();
1077 for (BasicBlock *Block : R.blocks()) {
Michael Kruse9d080092015-09-11 21:41:48 +00001078 buildAccesses(Block, Block != EntryBB);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001079 deriveAssumptions(Block);
1080 }
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001081 if (DetectReductions)
1082 checkForReductions();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001083}
1084
Michael Kruse9d080092015-09-11 21:41:48 +00001085ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001086 : Parent(parent), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001087
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001088 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +00001089
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001090 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001091 collectSurroundingLoops();
Michael Kruse9d080092015-09-11 21:41:48 +00001092 buildAccesses(BB);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001093 deriveAssumptions(BB);
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001094 if (DetectReductions)
1095 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001096}
1097
Johannes Doerferte58a0122014-06-27 20:31:28 +00001098/// @brief Collect loads which might form a reduction chain with @p StoreMA
1099///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001100/// Check if the stored value for @p StoreMA is a binary operator with one or
1101/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001102/// used only once (by @p StoreMA) and its load operands are also used only
1103/// once, we have found a possible reduction chain. It starts at an operand
1104/// load and includes the binary operator and @p StoreMA.
1105///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001106/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001107/// escape this block or into any other store except @p StoreMA.
1108void ScopStmt::collectCandiateReductionLoads(
1109 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1110 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1111 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001112 return;
1113
1114 // Skip if there is not one binary operator between the load and the store
1115 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001116 if (!BinOp)
1117 return;
1118
1119 // Skip if the binary operators has multiple uses
1120 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001121 return;
1122
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001123 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001124 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1125 return;
1126
Johannes Doerfert9890a052014-07-01 00:32:29 +00001127 // Skip if the binary operator is outside the current SCoP
1128 if (BinOp->getParent() != Store->getParent())
1129 return;
1130
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001131 // Skip if it is a multiplicative reduction and we disabled them
1132 if (DisableMultiplicativeReductions &&
1133 (BinOp->getOpcode() == Instruction::Mul ||
1134 BinOp->getOpcode() == Instruction::FMul))
1135 return;
1136
Johannes Doerferte58a0122014-06-27 20:31:28 +00001137 // Check the binary operator operands for a candidate load
1138 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1139 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1140 if (!PossibleLoad0 && !PossibleLoad1)
1141 return;
1142
1143 // A load is only a candidate if it cannot escape (thus has only this use)
1144 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001145 if (PossibleLoad0->getParent() == Store->getParent())
1146 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001147 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001148 if (PossibleLoad1->getParent() == Store->getParent())
1149 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001150}
1151
1152/// @brief Check for reductions in this ScopStmt
1153///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001154/// Iterate over all store memory accesses and check for valid binary reduction
1155/// like chains. For all candidates we check if they have the same base address
1156/// and there are no other accesses which overlap with them. The base address
1157/// check rules out impossible reductions candidates early. The overlap check,
1158/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001159/// guarantees that none of the intermediate results will escape during
1160/// execution of the loop nest. We basically check here that no other memory
1161/// access can access the same memory as the potential reduction.
1162void ScopStmt::checkForReductions() {
1163 SmallVector<MemoryAccess *, 2> Loads;
1164 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1165
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001166 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001167 // stores and collecting possible reduction loads.
1168 for (MemoryAccess *StoreMA : MemAccs) {
1169 if (StoreMA->isRead())
1170 continue;
1171
1172 Loads.clear();
1173 collectCandiateReductionLoads(StoreMA, Loads);
1174 for (MemoryAccess *LoadMA : Loads)
1175 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1176 }
1177
1178 // Then check each possible candidate pair.
1179 for (const auto &CandidatePair : Candidates) {
1180 bool Valid = true;
1181 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1182 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1183
1184 // Skip those with obviously unequal base addresses.
1185 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1186 isl_map_free(LoadAccs);
1187 isl_map_free(StoreAccs);
1188 continue;
1189 }
1190
1191 // And check if the remaining for overlap with other memory accesses.
1192 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1193 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1194 isl_set *AllAccs = isl_map_range(AllAccsRel);
1195
1196 for (MemoryAccess *MA : MemAccs) {
1197 if (MA == CandidatePair.first || MA == CandidatePair.second)
1198 continue;
1199
1200 isl_map *AccRel =
1201 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1202 isl_set *Accs = isl_map_range(AccRel);
1203
1204 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1205 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1206 Valid = Valid && isl_set_is_empty(OverlapAccs);
1207 isl_set_free(OverlapAccs);
1208 }
1209 }
1210
1211 isl_set_free(AllAccs);
1212 if (!Valid)
1213 continue;
1214
Johannes Doerfertf6183392014-07-01 20:52:51 +00001215 const LoadInst *Load =
1216 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1217 MemoryAccess::ReductionType RT =
1218 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1219
Johannes Doerferte58a0122014-06-27 20:31:28 +00001220 // If no overlapping access was found we mark the load and store as
1221 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001222 CandidatePair.first->markAsReductionLike(RT);
1223 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001224 }
Tobias Grosser75805372011-04-29 06:27:02 +00001225}
1226
Tobias Grosser74394f02013-01-14 22:40:23 +00001227std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001228
Tobias Grosser54839312015-04-21 11:37:25 +00001229std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001230 auto *S = getSchedule();
1231 auto Str = stringFromIslObj(S);
1232 isl_map_free(S);
1233 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001234}
1235
Tobias Grosser74394f02013-01-14 22:40:23 +00001236unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001237
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001238unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001239
Tobias Grosser75805372011-04-29 06:27:02 +00001240const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1241
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001242const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001243 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001244}
1245
Tobias Grosser74394f02013-01-14 22:40:23 +00001246isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001247
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001248__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001249
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001250__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001251 return isl_set_get_space(Domain);
1252}
1253
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001254__isl_give isl_id *ScopStmt::getDomainId() const {
1255 return isl_set_get_tuple_id(Domain);
1256}
Tobias Grossercd95b772012-08-30 11:49:38 +00001257
Tobias Grosser75805372011-04-29 06:27:02 +00001258ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001259 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001260 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001261}
1262
1263void ScopStmt::print(raw_ostream &OS) const {
1264 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001265 OS.indent(12) << "Domain :=\n";
1266
1267 if (Domain) {
1268 OS.indent(16) << getDomainStr() << ";\n";
1269 } else
1270 OS.indent(16) << "n/a\n";
1271
Tobias Grosser54839312015-04-21 11:37:25 +00001272 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001273
1274 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001275 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001276 } else
1277 OS.indent(16) << "n/a\n";
1278
Tobias Grosser083d3d32014-06-28 08:59:45 +00001279 for (MemoryAccess *Access : MemAccs)
1280 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001281}
1282
1283void ScopStmt::dump() const { print(dbgs()); }
1284
1285//===----------------------------------------------------------------------===//
1286/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001287
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001288void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001289 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1290 isl_set_free(Context);
1291 Context = NewContext;
1292}
1293
Tobias Grosserabfbe632013-02-05 12:09:06 +00001294void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001295 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001296 Parameter = extractConstantFactor(Parameter, *SE).second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001297 if (ParameterIds.find(Parameter) != ParameterIds.end())
1298 continue;
1299
1300 int dimension = Parameters.size();
1301
1302 Parameters.push_back(Parameter);
1303 ParameterIds[Parameter] = dimension;
1304 }
1305}
1306
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001307__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1308 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001309
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001310 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001311 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001312
Tobias Grosser8f99c162011-11-15 11:38:55 +00001313 std::string ParameterName;
1314
1315 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1316 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001317 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001318 }
1319
1320 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001321 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001322
Tobias Grosser20532b82014-04-11 17:56:49 +00001323 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1324 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001325}
Tobias Grosser75805372011-04-29 06:27:02 +00001326
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001327isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1328 isl_set *DomainContext = isl_union_set_params(getDomains());
1329 return isl_set_intersect_params(C, DomainContext);
1330}
1331
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001332void Scop::buildBoundaryContext() {
1333 BoundaryContext = Affinator.getWrappingContext();
1334 BoundaryContext = isl_set_complement(BoundaryContext);
1335 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
1336}
1337
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001338void Scop::addUserContext() {
1339 if (UserContextStr.empty())
1340 return;
1341
1342 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1343 isl_space *Space = getParamSpace();
1344 if (isl_space_dim(Space, isl_dim_param) !=
1345 isl_set_dim(UserContext, isl_dim_param)) {
1346 auto SpaceStr = isl_space_to_str(Space);
1347 errs() << "Error: the context provided in -polly-context has not the same "
1348 << "number of dimensions than the computed context. Due to this "
1349 << "mismatch, the -polly-context option is ignored. Please provide "
1350 << "the context in the parameter space: " << SpaceStr << ".\n";
1351 free(SpaceStr);
1352 isl_set_free(UserContext);
1353 isl_space_free(Space);
1354 return;
1355 }
1356
1357 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1358 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1359 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1360
1361 if (strcmp(NameContext, NameUserContext) != 0) {
1362 auto SpaceStr = isl_space_to_str(Space);
1363 errs() << "Error: the name of dimension " << i
1364 << " provided in -polly-context "
1365 << "is '" << NameUserContext << "', but the name in the computed "
1366 << "context is '" << NameContext
1367 << "'. Due to this name mismatch, "
1368 << "the -polly-context option is ignored. Please provide "
1369 << "the context in the parameter space: " << SpaceStr << ".\n";
1370 free(SpaceStr);
1371 isl_set_free(UserContext);
1372 isl_space_free(Space);
1373 return;
1374 }
1375
1376 UserContext =
1377 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1378 isl_space_get_dim_id(Space, isl_dim_param, i));
1379 }
1380
1381 Context = isl_set_intersect(Context, UserContext);
1382 isl_space_free(Space);
1383}
1384
Tobias Grosser6be480c2011-11-08 15:41:13 +00001385void Scop::buildContext() {
1386 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001387 Context = isl_set_universe(isl_space_copy(Space));
1388 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001389}
1390
Tobias Grosser18daaca2012-05-22 10:47:27 +00001391void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001392 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001393 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001394
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001395 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001396
Johannes Doerferte7044942015-02-24 11:58:30 +00001397 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001398 }
1399}
1400
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001401void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001402 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001403 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001404
Tobias Grosser083d3d32014-06-28 08:59:45 +00001405 for (const auto &ParamID : ParameterIds) {
1406 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001407 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001408 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001409 }
1410
1411 // Align the parameters of all data structures to the model.
1412 Context = isl_set_align_params(Context, Space);
1413
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001414 for (ScopStmt &Stmt : *this)
1415 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001416}
1417
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001418static __isl_give isl_set *
1419simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1420 const Scop &S) {
1421 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1422 AssumptionContext = isl_set_gist_params(AssumptionContext, DomainParameters);
1423 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1424 return AssumptionContext;
1425}
1426
1427void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001428 // The parameter constraints of the iteration domains give us a set of
1429 // constraints that need to hold for all cases where at least a single
1430 // statement iteration is executed in the whole scop. We now simplify the
1431 // assumed context under the assumption that such constraints hold and at
1432 // least a single statement iteration is executed. For cases where no
1433 // statement instances are executed, the assumptions we have taken about
1434 // the executed code do not matter and can be changed.
1435 //
1436 // WARNING: This only holds if the assumptions we have taken do not reduce
1437 // the set of statement instances that are executed. Otherwise we
1438 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001439 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001440 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001441 // performed. In such a case, modifying the run-time conditions and
1442 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001443 // to not be executed.
1444 //
1445 // Example:
1446 //
1447 // When delinearizing the following code:
1448 //
1449 // for (long i = 0; i < 100; i++)
1450 // for (long j = 0; j < m; j++)
1451 // A[i+p][j] = 1.0;
1452 //
1453 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001454 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001455 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001456 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1457 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001458}
1459
Johannes Doerfertb164c792014-09-18 11:17:17 +00001460/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001461static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001462 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1463 isl_pw_multi_aff *MinPMA, *MaxPMA;
1464 isl_pw_aff *LastDimAff;
1465 isl_aff *OneAff;
1466 unsigned Pos;
1467
Johannes Doerfert9143d672014-09-27 11:02:39 +00001468 // Restrict the number of parameters involved in the access as the lexmin/
1469 // lexmax computation will take too long if this number is high.
1470 //
1471 // Experiments with a simple test case using an i7 4800MQ:
1472 //
1473 // #Parameters involved | Time (in sec)
1474 // 6 | 0.01
1475 // 7 | 0.04
1476 // 8 | 0.12
1477 // 9 | 0.40
1478 // 10 | 1.54
1479 // 11 | 6.78
1480 // 12 | 30.38
1481 //
1482 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1483 unsigned InvolvedParams = 0;
1484 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1485 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1486 InvolvedParams++;
1487
1488 if (InvolvedParams > RunTimeChecksMaxParameters) {
1489 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001490 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001491 }
1492 }
1493
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001494 Set = isl_set_remove_divs(Set);
1495
Johannes Doerfertb164c792014-09-18 11:17:17 +00001496 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1497 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1498
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001499 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1500 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1501
Johannes Doerfertb164c792014-09-18 11:17:17 +00001502 // Adjust the last dimension of the maximal access by one as we want to
1503 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1504 // we test during code generation might now point after the end of the
1505 // allocated array but we will never dereference it anyway.
1506 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1507 "Assumed at least one output dimension");
1508 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1509 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1510 OneAff = isl_aff_zero_on_domain(
1511 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1512 OneAff = isl_aff_add_constant_si(OneAff, 1);
1513 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1514 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1515
1516 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1517
1518 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001519 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001520}
1521
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001522static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1523 isl_set *Domain = MA->getStatement()->getDomain();
1524 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1525 return isl_set_reset_tuple_id(Domain);
1526}
1527
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001528/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1529static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001530 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001531 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001532
1533 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1534 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001535 Locations = isl_union_set_coalesce(Locations);
1536 Locations = isl_union_set_detect_equalities(Locations);
1537 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001538 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001539 isl_union_set_free(Locations);
1540 return Valid;
1541}
1542
Johannes Doerfert96425c22015-08-30 21:13:53 +00001543/// @brief Helper to treat non-affine regions and basic blocks the same.
1544///
1545///{
1546
1547/// @brief Return the block that is the representing block for @p RN.
1548static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1549 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1550 : RN->getNodeAs<BasicBlock>();
1551}
1552
1553/// @brief Return the @p idx'th block that is executed after @p RN.
1554static inline BasicBlock *getRegionNodeSuccessor(RegionNode *RN, BranchInst *BI,
1555 unsigned idx) {
1556 if (RN->isSubRegion()) {
1557 assert(idx == 0);
1558 return RN->getNodeAs<Region>()->getExit();
1559 }
1560 return BI->getSuccessor(idx);
1561}
1562
1563/// @brief Return the smallest loop surrounding @p RN.
1564static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1565 if (!RN->isSubRegion())
1566 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1567
1568 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1569 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1570 while (L && NonAffineSubRegion->contains(L))
1571 L = L->getParentLoop();
1572 return L;
1573}
1574
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001575static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1576 if (!RN->isSubRegion())
1577 return 1;
1578
1579 unsigned NumBlocks = 0;
1580 Region *R = RN->getNodeAs<Region>();
1581 for (auto BB : R->blocks()) {
1582 (void)BB;
1583 NumBlocks++;
1584 }
1585 return NumBlocks;
1586}
1587
Johannes Doerfert96425c22015-08-30 21:13:53 +00001588///}
1589
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001590static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1591 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001592 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001593 isl_id *DimId =
1594 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
1595 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
1596}
1597
Johannes Doerfert96425c22015-08-30 21:13:53 +00001598isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1599 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1600 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00001601 return getDomainConditions(BB);
1602}
1603
1604isl_set *Scop::getDomainConditions(BasicBlock *BB) {
1605 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001606 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001607}
1608
1609void Scop::buildDomains(Region *R, LoopInfo &LI, ScopDetection &SD,
1610 DominatorTree &DT) {
1611
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001612 auto *EntryBB = R->getEntry();
1613 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
1614 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001615
1616 Loop *L = LI.getLoopFor(EntryBB);
1617 while (LD-- >= 0) {
1618 S = addDomainDimId(S, LD + 1, L);
1619 L = L->getParentLoop();
1620 }
1621
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001622 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001623
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00001624 if (SD.isNonAffineSubRegion(R, R))
1625 return;
1626
Johannes Doerfert96425c22015-08-30 21:13:53 +00001627 buildDomainsWithBranchConstraints(R, LI, SD, DT);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001628 propagateDomainConstraints(R, LI, SD, DT);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001629}
1630
1631void Scop::buildDomainsWithBranchConstraints(Region *R, LoopInfo &LI,
1632 ScopDetection &SD,
1633 DominatorTree &DT) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001634 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00001635
1636 // To create the domain for each block in R we iterate over all blocks and
1637 // subregions in R and propagate the conditions under which the current region
1638 // element is executed. To this end we iterate in reverse post order over R as
1639 // it ensures that we first visit all predecessors of a region node (either a
1640 // basic block or a subregion) before we visit the region node itself.
1641 // Initially, only the domain for the SCoP region entry block is set and from
1642 // there we propagate the current domain to all successors, however we add the
1643 // condition that the successor is actually executed next.
1644 // As we are only interested in non-loop carried constraints here we can
1645 // simply skip loop back edges.
1646
1647 ReversePostOrderTraversal<Region *> RTraversal(R);
1648 for (auto *RN : RTraversal) {
1649
1650 // Recurse for affine subregions but go on for basic blocks and non-affine
1651 // subregions.
1652 if (RN->isSubRegion()) {
1653 Region *SubRegion = RN->getNodeAs<Region>();
1654 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
1655 buildDomainsWithBranchConstraints(SubRegion, LI, SD, DT);
1656 continue;
1657 }
1658 }
1659
1660 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001661 TerminatorInst *TI = BB->getTerminator();
1662
1663 // Unreachable instructions do not have successors so we can skip them.
1664 if (isa<UnreachableInst>(TI)) {
1665 // Assume unreachables only in error blocks.
1666 assert(isErrorBlock(*BB));
1667 continue;
1668 }
1669
Johannes Doerfert96425c22015-08-30 21:13:53 +00001670 isl_set *Domain = DomainMap[BB];
1671 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
1672 assert(Domain && "Due to reverse post order traversal of the region all "
1673 "predecessor of the current region node should have been "
1674 "visited and a domain for this region node should have "
1675 "been set.");
1676
1677 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1678 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1679
1680 // Build the condition sets for the successor nodes of the current region
1681 // node. If it is a non-affine subregion we will always execute the single
1682 // exit node, hence the single entry node domain is the condition set. For
1683 // basic blocks we use the helper function buildConditionSets.
1684 SmallVector<isl_set *, 2> ConditionSets;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001685 BranchInst *BI = cast<BranchInst>(TI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001686 if (RN->isSubRegion())
1687 ConditionSets.push_back(isl_set_copy(Domain));
1688 else
1689 buildConditionSets(*this, BI, BBLoop, Domain, ConditionSets);
1690
1691 // Now iterate over the successors and set their initial domain based on
1692 // their condition set. We skip back edges here and have to be careful when
1693 // we leave a loop not to keep constraints over a dimension that doesn't
1694 // exist anymore.
1695 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
1696 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, BI, u);
1697 isl_set *CondSet = ConditionSets[u];
1698
1699 // Skip back edges.
1700 if (DT.dominates(SuccBB, BB)) {
1701 isl_set_free(CondSet);
1702 continue;
1703 }
1704
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001705 // Do not adjust the number of dimensions if we enter a boxed loop or are
1706 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001707 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001708 Region *SuccRegion = RI.getRegionFor(SuccBB);
1709 if (BBLoop != SuccBBLoop && !RN->isSubRegion() &&
1710 !(SD.isNonAffineSubRegion(SuccRegion, &getRegion()) &&
1711 SuccRegion->contains(SuccBBLoop))) {
1712
1713 // Check if the edge to SuccBB is a loop entry or exit edge. If so
1714 // adjust the dimensionality accordingly. Lastly, if we leave a loop
1715 // and enter a new one we need to drop the old constraints.
1716 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001717 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001718 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001719 CondSet = isl_set_project_out(CondSet, isl_dim_set,
1720 isl_set_n_dim(CondSet) - LoopDepthDiff,
1721 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001722 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001723 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001724 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001725 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001726 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001727 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001728 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
1729 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001730 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001731 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00001732 }
1733
1734 // Set the domain for the successor or merge it with an existing domain in
1735 // case there are multiple paths (without loop back edges) to the
1736 // successor block.
1737 isl_set *&SuccDomain = DomainMap[SuccBB];
1738 if (!SuccDomain)
1739 SuccDomain = CondSet;
1740 else
1741 SuccDomain = isl_set_union(SuccDomain, CondSet);
1742
1743 SuccDomain = isl_set_coalesce(SuccDomain);
1744 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : " << Domain
1745 << "\n");
1746 }
1747 }
1748}
1749
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001750/// @brief Return the domain for @p BB wrt @p DomainMap.
1751///
1752/// This helper function will lookup @p BB in @p DomainMap but also handle the
1753/// case where @p BB is contained in a non-affine subregion using the region
1754/// tree obtained by @p RI.
1755static __isl_give isl_set *
1756getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
1757 RegionInfo &RI) {
1758 auto DIt = DomainMap.find(BB);
1759 if (DIt != DomainMap.end())
1760 return isl_set_copy(DIt->getSecond());
1761
1762 Region *R = RI.getRegionFor(BB);
1763 while (R->getEntry() == BB)
1764 R = R->getParent();
1765 return getDomainForBlock(R->getEntry(), DomainMap, RI);
1766}
1767
Johannes Doerferte114dc02015-09-14 11:15:58 +00001768static bool containsErrorBlock(RegionNode *RN) {
1769 if (!RN->isSubRegion())
1770 return isErrorBlock(*RN->getNodeAs<BasicBlock>());
1771 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
1772 if (isErrorBlock(*BB))
1773 return true;
1774 return false;
1775}
1776
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001777void Scop::propagateDomainConstraints(Region *R, LoopInfo &LI,
1778 ScopDetection &SD, DominatorTree &DT) {
1779 // Iterate over the region R and propagate the domain constrains from the
1780 // predecessors to the current node. In contrast to the
1781 // buildDomainsWithBranchConstraints function, this one will pull the domain
1782 // information from the predecessors instead of pushing it to the successors.
1783 // Additionally, we assume the domains to be already present in the domain
1784 // map here. However, we iterate again in reverse post order so we know all
1785 // predecessors have been visited before a block or non-affine subregion is
1786 // visited.
1787
1788 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
1789 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
1790
1791 ReversePostOrderTraversal<Region *> RTraversal(R);
1792 for (auto *RN : RTraversal) {
1793
1794 // Recurse for affine subregions but go on for basic blocks and non-affine
1795 // subregions.
1796 if (RN->isSubRegion()) {
1797 Region *SubRegion = RN->getNodeAs<Region>();
1798 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
1799 propagateDomainConstraints(SubRegion, LI, SD, DT);
1800 continue;
1801 }
1802 }
1803
1804 BasicBlock *BB = getRegionNodeBasicBlock(RN);
1805 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1806 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1807
1808 isl_set *&Domain = DomainMap[BB];
1809 assert(Domain && "Due to reverse post order traversal of the region all "
1810 "predecessor of the current region node should have been "
1811 "visited and a domain for this region node should have "
1812 "been set.");
1813
1814 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
1815 for (auto *PredBB : predecessors(BB)) {
1816
1817 // Skip backedges
1818 if (DT.dominates(BB, PredBB))
1819 continue;
1820
1821 isl_set *PredBBDom = nullptr;
1822
1823 // Handle the SCoP entry block with its outside predecessors.
1824 if (!getRegion().contains(PredBB))
1825 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
1826
1827 if (!PredBBDom) {
1828 // Determine the loop depth of the predecessor and adjust its domain to
1829 // the domain of the current block. This can mean we have to:
1830 // o) Drop a dimension if this block is the exit of a loop, not the
1831 // header of a new loop and the predecessor was part of the loop.
1832 // o) Add an unconstrainted new dimension if this block is the header
1833 // of a loop and the predecessor is not part of it.
1834 // o) Drop the information about the innermost loop dimension when the
1835 // predecessor and the current block are surrounded by different
1836 // loops in the same depth.
1837 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
1838 Loop *PredBBLoop = LI.getLoopFor(PredBB);
1839 while (BoxedLoops.count(PredBBLoop))
1840 PredBBLoop = PredBBLoop->getParentLoop();
1841
1842 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001843 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001844 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001845 PredBBDom = isl_set_project_out(
1846 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
1847 LoopDepthDiff);
1848 else if (PredBBLoopDepth < BBLoopDepth) {
1849 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001850 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001851 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
1852 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001853 PredBBDom = isl_set_drop_constraints_involving_dims(
1854 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001855 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001856 }
1857
1858 PredDom = isl_set_union(PredDom, PredBBDom);
1859 }
1860
1861 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00001862 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001863
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001864 if (BBLoop && BBLoop->getHeader() == BB)
1865 addLoopBoundsToHeaderDomain(BBLoop, LI);
1866
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001867 // Add assumptions for error blocks.
Johannes Doerferte114dc02015-09-14 11:15:58 +00001868 if (containsErrorBlock(RN)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001869 IsOptimized = true;
1870 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
1871 addAssumption(isl_set_complement(DomPar));
1872 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001873 }
1874}
1875
1876/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
1877/// is incremented by one and all other dimensions are equal, e.g.,
1878/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
1879/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
1880static __isl_give isl_map *
1881createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
1882 auto *MapSpace = isl_space_map_from_set(SetSpace);
1883 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
1884 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
1885 if (u != Dim)
1886 NextIterationMap =
1887 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
1888 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
1889 C = isl_constraint_set_constant_si(C, 1);
1890 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
1891 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
1892 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
1893 return NextIterationMap;
1894}
1895
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001896void Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
1897 int LoopDepth = getRelativeLoopDepth(L);
1898 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001899
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001900 BasicBlock *HeaderBB = L->getHeader();
1901 assert(DomainMap.count(HeaderBB));
1902 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001903
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001904 isl_map *NextIterationMap =
1905 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001906
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001907 isl_set *UnionBackedgeCondition =
1908 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001909
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001910 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
1911 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001912
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001913 for (BasicBlock *LatchBB : LatchBlocks) {
1914 assert(DomainMap.count(LatchBB));
1915 isl_set *LatchBBDom = DomainMap[LatchBB];
1916 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001917
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001918 BranchInst *BI = cast<BranchInst>(LatchBB->getTerminator());
1919 if (BI->isUnconditional())
1920 BackedgeCondition = isl_set_copy(LatchBBDom);
1921 else {
1922 SmallVector<isl_set *, 2> ConditionSets;
1923 int idx = BI->getSuccessor(0) != HeaderBB;
1924 buildConditionSets(*this, BI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001925
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001926 // Free the non back edge condition set as we do not need it.
1927 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001928
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001929 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00001930 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001931
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001932 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
1933 assert(LatchLoopDepth >= LoopDepth);
1934 BackedgeCondition =
1935 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
1936 LatchLoopDepth - LoopDepth);
1937 UnionBackedgeCondition =
1938 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001939 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001940
1941 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
1942 for (int i = 0; i < LoopDepth; i++)
1943 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
1944
1945 isl_set *UnionBackedgeConditionComplement =
1946 isl_set_complement(UnionBackedgeCondition);
1947 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
1948 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
1949 UnionBackedgeConditionComplement =
1950 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
1951 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
1952 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
1953
1954 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
1955 HeaderBBDom = Parts.second;
1956
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00001957 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
1958 // the bounded assumptions to the context as they are already implied by the
1959 // <nsw> tag.
1960 if (Affinator.hasNSWAddRecForLoop(L)) {
1961 isl_set_free(Parts.first);
1962 return;
1963 }
1964
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001965 isl_set *UnboundedCtx = isl_set_params(Parts.first);
1966 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfert707a4062015-09-20 16:38:19 +00001967 addAssumption(BoundedCtx);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001968}
1969
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001970void Scop::buildAliasChecks(AliasAnalysis &AA) {
1971 if (!PollyUseRuntimeAliasChecks)
1972 return;
1973
1974 if (buildAliasGroups(AA))
1975 return;
1976
1977 // If a problem occurs while building the alias groups we need to delete
1978 // this SCoP and pretend it wasn't valid in the first place. To this end
1979 // we make the assumed context infeasible.
1980 addAssumption(isl_set_empty(getParamSpace()));
1981
1982 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
1983 << " could not be created as the number of parameters involved "
1984 "is too high. The SCoP will be "
1985 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
1986 "the maximal number of parameters but be advised that the "
1987 "compile time might increase exponentially.\n\n");
1988}
1989
Johannes Doerfert9143d672014-09-27 11:02:39 +00001990bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001991 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001992 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00001993 // for all memory accesses inside the SCoP.
1994 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001995 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00001996 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001997 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001998 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001999 // if their access domains intersect, otherwise they are in different
2000 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002001 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002002 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002003 // and maximal accesses to each array of a group in read only and non
2004 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002005 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2006
2007 AliasSetTracker AST(AA);
2008
2009 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002010 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002011 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002012
2013 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002014 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002015 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2016 isl_set_free(StmtDomain);
2017 if (StmtDomainEmpty)
2018 continue;
2019
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002020 for (MemoryAccess *MA : Stmt) {
Michael Kruse8d0b7342015-09-25 21:21:00 +00002021 if (MA->isImplicit())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002022 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002023 if (!MA->isRead())
2024 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002025 Instruction *Acc = MA->getAccessInstruction();
2026 PtrToAcc[getPointerOperand(*Acc)] = MA;
2027 AST.add(Acc);
2028 }
2029 }
2030
2031 SmallVector<AliasGroupTy, 4> AliasGroups;
2032 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002033 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002034 continue;
2035 AliasGroupTy AG;
2036 for (auto PR : AS)
2037 AG.push_back(PtrToAcc[PR.getValue()]);
2038 assert(AG.size() > 1 &&
2039 "Alias groups should contain at least two accesses");
2040 AliasGroups.push_back(std::move(AG));
2041 }
2042
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002043 // Split the alias groups based on their domain.
2044 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2045 AliasGroupTy NewAG;
2046 AliasGroupTy &AG = AliasGroups[u];
2047 AliasGroupTy::iterator AGI = AG.begin();
2048 isl_set *AGDomain = getAccessDomain(*AGI);
2049 while (AGI != AG.end()) {
2050 MemoryAccess *MA = *AGI;
2051 isl_set *MADomain = getAccessDomain(MA);
2052 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2053 NewAG.push_back(MA);
2054 AGI = AG.erase(AGI);
2055 isl_set_free(MADomain);
2056 } else {
2057 AGDomain = isl_set_union(AGDomain, MADomain);
2058 AGI++;
2059 }
2060 }
2061 if (NewAG.size() > 1)
2062 AliasGroups.push_back(std::move(NewAG));
2063 isl_set_free(AGDomain);
2064 }
2065
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002066 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002067 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2068 for (AliasGroupTy &AG : AliasGroups) {
2069 NonReadOnlyBaseValues.clear();
2070 ReadOnlyPairs.clear();
2071
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002072 if (AG.size() < 2) {
2073 AG.clear();
2074 continue;
2075 }
2076
Johannes Doerfert13771732014-10-01 12:40:46 +00002077 for (auto II = AG.begin(); II != AG.end();) {
2078 Value *BaseAddr = (*II)->getBaseAddr();
2079 if (HasWriteAccess.count(BaseAddr)) {
2080 NonReadOnlyBaseValues.insert(BaseAddr);
2081 II++;
2082 } else {
2083 ReadOnlyPairs[BaseAddr].insert(*II);
2084 II = AG.erase(II);
2085 }
2086 }
2087
2088 // If we don't have read only pointers check if there are at least two
2089 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002090 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002091 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002092 continue;
2093 }
2094
2095 // If we don't have non read only pointers clear the alias group.
2096 if (NonReadOnlyBaseValues.empty()) {
2097 AG.clear();
2098 continue;
2099 }
2100
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002101 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002102 MinMaxAliasGroups.emplace_back();
2103 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2104 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2105 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2106 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002107
2108 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002109
2110 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002111 for (MemoryAccess *MA : AG)
2112 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002113
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002114 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2115 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002116
2117 // Bail out if the number of values we need to compare is too large.
2118 // This is important as the number of comparisions grows quadratically with
2119 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002120 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2121 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002122 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002123
2124 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002125 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002126 Accesses = isl_union_map_empty(getParamSpace());
2127
2128 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2129 for (MemoryAccess *MA : ReadOnlyPair.second)
2130 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2131
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002132 Valid =
2133 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002134
2135 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002136 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002137 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002138
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002139 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002140}
2141
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002142static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
2143 Loop *L = LI.getLoopFor(R.getEntry());
2144 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2145}
2146
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002147static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2148 ScopDetection &SD) {
2149
2150 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2151
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002152 unsigned MinLD = INT_MAX, MaxLD = 0;
2153 for (BasicBlock *BB : R.blocks()) {
2154 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002155 if (!R.contains(L))
2156 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002157 if (BoxedLoops && BoxedLoops->count(L))
2158 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002159 unsigned LD = L->getLoopDepth();
2160 MinLD = std::min(MinLD, LD);
2161 MaxLD = std::max(MaxLD, LD);
2162 }
2163 }
2164
2165 // Handle the case that there is no loop in the SCoP first.
2166 if (MaxLD == 0)
2167 return 1;
2168
2169 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2170 assert(MaxLD >= MinLD &&
2171 "Maximal loop depth was smaller than mininaml loop depth?");
2172 return MaxLD - MinLD + 1;
2173}
2174
Michael Kruse9d080092015-09-11 21:41:48 +00002175Scop::Scop(Region &R, AccFuncMapType &AccFuncMap,
2176 ScalarEvolution &ScalarEvolution, DominatorTree &DT,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002177 isl_ctx *Context, unsigned MaxLoopDepth)
Michael Kruse9d080092015-09-11 21:41:48 +00002178 : DT(DT), SE(&ScalarEvolution), R(R), AccFuncMap(AccFuncMap),
2179 IsOptimized(false), HasSingleExitEdge(R.getExitingBlock()),
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002180 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Affinator(this),
2181 BoundaryContext(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002182
Michael Kruse9d080092015-09-11 21:41:48 +00002183void Scop::init(LoopInfo &LI, ScopDetection &SD, AliasAnalysis &AA) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002184 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00002185
Johannes Doerfert96425c22015-08-30 21:13:53 +00002186 buildDomains(&R, LI, SD, DT);
2187
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002188 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
Tobias Grosser75805372011-04-29 06:27:02 +00002189
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002190 Loop *L = getLoopSurroundingRegion(R, LI);
2191 LoopSchedules[L];
Michael Kruse9d080092015-09-11 21:41:48 +00002192 buildSchedule(&R, LI, SD, LoopSchedules);
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002193 updateAccessDimensionality();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002194 Schedule = LoopSchedules[L].first;
Tobias Grosser75805372011-04-29 06:27:02 +00002195
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002196 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002197 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002198 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002199 buildBoundaryContext();
2200 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002201 buildAliasChecks(AA);
Tobias Grosser75805372011-04-29 06:27:02 +00002202}
2203
2204Scop::~Scop() {
2205 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002206 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002207 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002208 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002209
Johannes Doerfert96425c22015-08-30 21:13:53 +00002210 for (auto It : DomainMap)
2211 isl_set_free(It.second);
2212
Johannes Doerfertb164c792014-09-18 11:17:17 +00002213 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002214 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002215 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002216 isl_pw_multi_aff_free(MMA.first);
2217 isl_pw_multi_aff_free(MMA.second);
2218 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002219 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002220 isl_pw_multi_aff_free(MMA.first);
2221 isl_pw_multi_aff_free(MMA.second);
2222 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002223 }
Tobias Grosser75805372011-04-29 06:27:02 +00002224}
2225
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002226void Scop::updateAccessDimensionality() {
2227 for (auto &Stmt : *this)
2228 for (auto &Access : Stmt)
2229 Access->updateDimensionality();
2230}
2231
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002232const ScopArrayInfo *
2233Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Michael Kruse28468772015-09-14 15:45:33 +00002234 ArrayRef<const SCEV *> Sizes, bool IsPHI) {
Tobias Grosser92245222015-07-28 14:53:44 +00002235 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002236 if (!SAI) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002237 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, IsPHI,
2238 this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002239 } else {
2240 if (Sizes.size() > SAI->getNumberOfDimensions())
2241 SAI->updateSizes(Sizes);
2242 }
Tobias Grosserab671442015-05-23 05:58:27 +00002243 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002244}
2245
Tobias Grosser92245222015-07-28 14:53:44 +00002246const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, bool IsPHI) {
2247 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002248 assert(SAI && "No ScopArrayInfo available for this base pointer");
2249 return SAI;
2250}
2251
Tobias Grosser74394f02013-01-14 22:40:23 +00002252std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002253std::string Scop::getAssumedContextStr() const {
2254 return stringFromIslObj(AssumedContext);
2255}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002256std::string Scop::getBoundaryContextStr() const {
2257 return stringFromIslObj(BoundaryContext);
2258}
Tobias Grosser75805372011-04-29 06:27:02 +00002259
2260std::string Scop::getNameStr() const {
2261 std::string ExitName, EntryName;
2262 raw_string_ostream ExitStr(ExitName);
2263 raw_string_ostream EntryStr(EntryName);
2264
Tobias Grosserf240b482014-01-09 10:42:15 +00002265 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002266 EntryStr.str();
2267
2268 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00002269 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002270 ExitStr.str();
2271 } else
2272 ExitName = "FunctionExit";
2273
2274 return EntryName + "---" + ExitName;
2275}
2276
Tobias Grosser74394f02013-01-14 22:40:23 +00002277__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00002278__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002279 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00002280}
2281
Tobias Grossere86109f2013-10-29 21:05:49 +00002282__isl_give isl_set *Scop::getAssumedContext() const {
2283 return isl_set_copy(AssumedContext);
2284}
2285
Johannes Doerfert43788c52015-08-20 05:58:56 +00002286__isl_give isl_set *Scop::getRuntimeCheckContext() const {
2287 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002288 RuntimeCheckContext =
2289 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
2290 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002291 return RuntimeCheckContext;
2292}
2293
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002294bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002295 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002296 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002297 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
2298 isl_set_free(RuntimeCheckContext);
2299 return IsFeasible;
2300}
2301
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002302void Scop::addAssumption(__isl_take isl_set *Set) {
2303 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00002304 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002305}
2306
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002307__isl_give isl_set *Scop::getBoundaryContext() const {
2308 return isl_set_copy(BoundaryContext);
2309}
2310
Tobias Grosser75805372011-04-29 06:27:02 +00002311void Scop::printContext(raw_ostream &OS) const {
2312 OS << "Context:\n";
2313
2314 if (!Context) {
2315 OS.indent(4) << "n/a\n\n";
2316 return;
2317 }
2318
2319 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00002320
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002321 OS.indent(4) << "Assumed Context:\n";
2322 if (!AssumedContext) {
2323 OS.indent(4) << "n/a\n\n";
2324 return;
2325 }
2326
2327 OS.indent(4) << getAssumedContextStr() << "\n";
2328
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002329 OS.indent(4) << "Boundary Context:\n";
2330 if (!BoundaryContext) {
2331 OS.indent(4) << "n/a\n\n";
2332 return;
2333 }
2334
2335 OS.indent(4) << getBoundaryContextStr() << "\n";
2336
Tobias Grosser083d3d32014-06-28 08:59:45 +00002337 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00002338 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00002339 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
2340 }
Tobias Grosser75805372011-04-29 06:27:02 +00002341}
2342
Johannes Doerfertb164c792014-09-18 11:17:17 +00002343void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002344 int noOfGroups = 0;
2345 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002346 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002347 noOfGroups += 1;
2348 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002349 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002350 }
2351
Tobias Grosserbb853c22015-07-25 12:31:03 +00002352 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00002353 if (MinMaxAliasGroups.empty()) {
2354 OS.indent(8) << "n/a\n";
2355 return;
2356 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002357
Tobias Grosserbb853c22015-07-25 12:31:03 +00002358 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002359
2360 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002361 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002362 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002363 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002364 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2365 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002366 }
2367 OS << " ]]\n";
2368 }
2369
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002370 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002371 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00002372 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002373 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002374 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2375 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002376 }
2377 OS << " ]]\n";
2378 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002379 }
2380}
2381
Tobias Grosser75805372011-04-29 06:27:02 +00002382void Scop::printStatements(raw_ostream &OS) const {
2383 OS << "Statements {\n";
2384
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002385 for (const ScopStmt &Stmt : *this)
2386 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00002387
2388 OS.indent(4) << "}\n";
2389}
2390
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002391void Scop::printArrayInfo(raw_ostream &OS) const {
2392 OS << "Arrays {\n";
2393
Tobias Grosserab671442015-05-23 05:58:27 +00002394 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002395 Array.second->print(OS);
2396
2397 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002398
2399 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
2400
2401 for (auto &Array : arrays())
2402 Array.second->print(OS, /* SizeAsPwAff */ true);
2403
2404 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002405}
2406
Tobias Grosser75805372011-04-29 06:27:02 +00002407void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00002408 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
2409 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00002410 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00002411 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00002412 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002413 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002414 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00002415 printStatements(OS.indent(4));
2416}
2417
2418void Scop::dump() const { print(dbgs()); }
2419
Tobias Grosser9a38ab82011-11-08 15:41:03 +00002420isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00002421
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002422__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
2423 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00002424}
2425
Tobias Grosser808cd692015-07-14 09:33:13 +00002426__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002427 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002428
Tobias Grosser808cd692015-07-14 09:33:13 +00002429 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002430 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002431
2432 return Domain;
2433}
2434
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002435__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002436 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002437
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002438 for (ScopStmt &Stmt : *this) {
2439 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002440 if (!MA->isMustWrite())
2441 continue;
2442
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002443 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002444 isl_map *AccessDomain = MA->getAccessRelation();
2445 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2446 Write = isl_union_map_add_map(Write, AccessDomain);
2447 }
2448 }
2449 return isl_union_map_coalesce(Write);
2450}
2451
2452__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002453 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002454
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002455 for (ScopStmt &Stmt : *this) {
2456 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002457 if (!MA->isMayWrite())
2458 continue;
2459
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002460 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002461 isl_map *AccessDomain = MA->getAccessRelation();
2462 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2463 Write = isl_union_map_add_map(Write, AccessDomain);
2464 }
2465 }
2466 return isl_union_map_coalesce(Write);
2467}
2468
Tobias Grosser37eb4222014-02-20 21:43:54 +00002469__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002470 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002471
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002472 for (ScopStmt &Stmt : *this) {
2473 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002474 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002475 continue;
2476
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002477 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002478 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002479 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2480 Write = isl_union_map_add_map(Write, AccessDomain);
2481 }
2482 }
2483 return isl_union_map_coalesce(Write);
2484}
2485
2486__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002487 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002488
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002489 for (ScopStmt &Stmt : *this) {
2490 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002491 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002492 continue;
2493
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002494 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002495 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002496
2497 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2498 Read = isl_union_map_add_map(Read, AccessDomain);
2499 }
2500 }
2501 return isl_union_map_coalesce(Read);
2502}
2503
Tobias Grosser808cd692015-07-14 09:33:13 +00002504__isl_give isl_union_map *Scop::getSchedule() const {
2505 auto Tree = getScheduleTree();
2506 auto S = isl_schedule_get_map(Tree);
2507 isl_schedule_free(Tree);
2508 return S;
2509}
Tobias Grosser37eb4222014-02-20 21:43:54 +00002510
Tobias Grosser808cd692015-07-14 09:33:13 +00002511__isl_give isl_schedule *Scop::getScheduleTree() const {
2512 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
2513 getDomains());
2514}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002515
Tobias Grosser808cd692015-07-14 09:33:13 +00002516void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
2517 auto *S = isl_schedule_from_domain(getDomains());
2518 S = isl_schedule_insert_partial_schedule(
2519 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
2520 isl_schedule_free(Schedule);
2521 Schedule = S;
2522}
2523
2524void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
2525 isl_schedule_free(Schedule);
2526 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00002527}
2528
2529bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
2530 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002531 for (ScopStmt &Stmt : *this) {
2532 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002533 isl_union_set *NewStmtDomain = isl_union_set_intersect(
2534 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
2535
2536 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
2537 isl_union_set_free(StmtDomain);
2538 isl_union_set_free(NewStmtDomain);
2539 continue;
2540 }
2541
2542 Changed = true;
2543
2544 isl_union_set_free(StmtDomain);
2545 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
2546
2547 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002548 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002549 isl_union_set_free(NewStmtDomain);
2550 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002551 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002552 }
2553 isl_union_set_free(Domain);
2554 return Changed;
2555}
2556
Tobias Grosser75805372011-04-29 06:27:02 +00002557ScalarEvolution *Scop::getSE() const { return SE; }
2558
Michael Kruse9d080092015-09-11 21:41:48 +00002559bool Scop::isTrivialBB(BasicBlock *BB) {
2560 if (getAccessFunctions(BB) && !isErrorBlock(*BB))
Tobias Grosser75805372011-04-29 06:27:02 +00002561 return false;
2562
2563 return true;
2564}
2565
Tobias Grosser808cd692015-07-14 09:33:13 +00002566struct MapToDimensionDataTy {
2567 int N;
2568 isl_union_pw_multi_aff *Res;
2569};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002570
Tobias Grosser808cd692015-07-14 09:33:13 +00002571// @brief Create a function that maps the elements of 'Set' to its N-th
2572// dimension.
2573//
2574// The result is added to 'User->Res'.
2575//
2576// @param Set The input set.
2577// @param N The dimension to map to.
2578//
2579// @returns Zero if no error occurred, non-zero otherwise.
2580static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
2581 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
2582 int Dim;
2583 isl_space *Space;
2584 isl_pw_multi_aff *PMA;
2585
2586 Dim = isl_set_dim(Set, isl_dim_set);
2587 Space = isl_set_get_space(Set);
2588 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
2589 Dim - Data->N);
2590 if (Data->N > 1)
2591 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
2592 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
2593
2594 isl_set_free(Set);
2595
2596 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002597}
2598
Tobias Grosser808cd692015-07-14 09:33:13 +00002599// @brief Create a function that maps the elements of Domain to their Nth
2600// dimension.
2601//
2602// @param Domain The set of elements to map.
2603// @param N The dimension to map to.
2604static __isl_give isl_multi_union_pw_aff *
2605mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002606 if (N <= 0 || isl_union_set_is_empty(Domain)) {
2607 isl_union_set_free(Domain);
2608 return nullptr;
2609 }
2610
Tobias Grosser808cd692015-07-14 09:33:13 +00002611 struct MapToDimensionDataTy Data;
2612 isl_space *Space;
2613
2614 Space = isl_union_set_get_space(Domain);
2615 Data.N = N;
2616 Data.Res = isl_union_pw_multi_aff_empty(Space);
2617 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
2618 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
2619
2620 isl_union_set_free(Domain);
2621 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
2622}
2623
Michael Kruse9d080092015-09-11 21:41:48 +00002624ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00002625 ScopStmt *Stmt;
2626 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00002627 Stmts.emplace_back(*this, *BB);
Tobias Grosser808cd692015-07-14 09:33:13 +00002628 Stmt = &Stmts.back();
2629 StmtMap[BB] = Stmt;
2630 } else {
2631 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00002632 Stmts.emplace_back(*this, *R);
Tobias Grosser808cd692015-07-14 09:33:13 +00002633 Stmt = &Stmts.back();
2634 for (BasicBlock *BB : R->blocks())
2635 StmtMap[BB] = Stmt;
2636 }
2637 return Stmt;
2638}
2639
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002640void Scop::buildSchedule(
Michael Kruse9d080092015-09-11 21:41:48 +00002641 Region *R, LoopInfo &LI, ScopDetection &SD,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002642 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00002643
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002644 if (SD.isNonAffineSubRegion(R, &getRegion())) {
2645 auto *Stmt = addScopStmt(nullptr, R);
2646 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
2647 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Johannes Doerfertc6987c12015-09-26 13:41:43 +00002648 Loop *L = getLoopSurroundingRegion(*R, LI);
2649 auto &LSchedulePair = LoopSchedules[L];
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002650 LSchedulePair.first = StmtSchedule;
2651 return;
2652 }
2653
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002654 ReversePostOrderTraversal<Region *> RTraversal(R);
2655 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00002656
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002657 if (RN->isSubRegion()) {
2658 Region *SubRegion = RN->getNodeAs<Region>();
2659 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Michael Kruse9d080092015-09-11 21:41:48 +00002660 buildSchedule(SubRegion, LI, SD, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002661 continue;
2662 }
Tobias Grosser75805372011-04-29 06:27:02 +00002663 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002664
2665 Loop *L = getRegionNodeLoop(RN, LI);
2666 int LD = getRelativeLoopDepth(L);
2667 auto &LSchedulePair = LoopSchedules[L];
2668 LSchedulePair.second += getNumBlocksInRegionNode(RN);
2669
2670 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Michael Kruse9d080092015-09-11 21:41:48 +00002671 if (RN->isSubRegion() || !isTrivialBB(BB)) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002672
2673 ScopStmt *Stmt;
2674 if (RN->isSubRegion())
Michael Kruse9d080092015-09-11 21:41:48 +00002675 Stmt = addScopStmt(nullptr, RN->getNodeAs<Region>());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002676 else
Michael Kruse9d080092015-09-11 21:41:48 +00002677 Stmt = addScopStmt(BB, nullptr);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002678
2679 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
2680 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
2681 LSchedulePair.first =
2682 combineInSequence(LSchedulePair.first, StmtSchedule);
2683 }
2684
2685 unsigned NumVisited = LSchedulePair.second;
2686 while (L && NumVisited == L->getNumBlocks()) {
2687 auto *LDomain = isl_schedule_get_domain(LSchedulePair.first);
2688 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
2689 LSchedulePair.first =
2690 isl_schedule_insert_partial_schedule(LSchedulePair.first, MUPA);
2691
2692 auto *PL = L->getParentLoop();
2693 assert(LoopSchedules.count(PL));
2694 auto &PSchedulePair = LoopSchedules[PL];
2695 PSchedulePair.first =
2696 combineInSequence(PSchedulePair.first, LSchedulePair.first);
2697 PSchedulePair.second += NumVisited;
2698
2699 L = PL;
2700 NumVisited = PSchedulePair.second;
2701 }
Tobias Grosser808cd692015-07-14 09:33:13 +00002702 }
Tobias Grosser75805372011-04-29 06:27:02 +00002703}
2704
Johannes Doerfert7c494212014-10-31 23:13:39 +00002705ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00002706 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00002707 if (StmtMapIt == StmtMap.end())
2708 return nullptr;
2709 return StmtMapIt->second;
2710}
2711
Johannes Doerfert96425c22015-08-30 21:13:53 +00002712int Scop::getRelativeLoopDepth(const Loop *L) const {
2713 Loop *OuterLoop =
2714 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
2715 if (!OuterLoop)
2716 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00002717 return L->getLoopDepth() - OuterLoop->getLoopDepth();
2718}
2719
Michael Krused868b5d2015-09-10 15:25:24 +00002720void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00002721 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002722
2723 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
2724 // true, are not modeled as ordinary PHI nodes as they are not part of the
2725 // region. However, we model the operands in the predecessor blocks that are
2726 // part of the region as regular scalar accesses.
2727
2728 // If we can synthesize a PHI we can skip it, however only if it is in
2729 // the region. If it is not it can only be in the exit block of the region.
2730 // In this case we model the operands but not the PHI itself.
2731 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
2732 return;
2733
2734 // PHI nodes are modeled as if they had been demoted prior to the SCoP
2735 // detection. Hence, the PHI is a load of a new memory location in which the
2736 // incoming value was written at the end of the incoming basic block.
2737 bool OnlyNonAffineSubRegionOperands = true;
2738 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
2739 Value *Op = PHI->getIncomingValue(u);
2740 BasicBlock *OpBB = PHI->getIncomingBlock(u);
2741
2742 // Do not build scalar dependences inside a non-affine subregion.
2743 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
2744 continue;
2745
2746 OnlyNonAffineSubRegionOperands = false;
2747
2748 if (!R.contains(OpBB))
2749 continue;
2750
2751 Instruction *OpI = dyn_cast<Instruction>(Op);
2752 if (OpI) {
2753 BasicBlock *OpIBB = OpI->getParent();
2754 // As we pretend there is a use (or more precise a write) of OpI in OpBB
2755 // we have to insert a scalar dependence from the definition of OpI to
2756 // OpBB if the definition is not in OpBB.
2757 if (OpIBB != OpBB) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002758 addScalarReadAccess(OpI, PHI, OpBB);
2759 addScalarWriteAccess(OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00002760 }
Tobias Grosserda95a4a2015-09-24 20:59:59 +00002761 } else if (ModelReadOnlyScalars && !isa<Constant>(Op)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002762 addScalarReadAccess(Op, PHI, OpBB);
Michael Kruse7bf39442015-09-10 12:46:52 +00002763 }
2764
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002765 addPHIWriteAccess(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00002766 }
2767
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002768 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
2769 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00002770 }
2771}
2772
Michael Krused868b5d2015-09-10 15:25:24 +00002773bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
2774 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002775 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
2776 if (isIgnoredIntrinsic(Inst))
2777 return false;
2778
2779 bool AnyCrossStmtUse = false;
2780 BasicBlock *ParentBB = Inst->getParent();
2781
2782 for (User *U : Inst->users()) {
2783 Instruction *UI = dyn_cast<Instruction>(U);
2784
2785 // Ignore the strange user
2786 if (UI == 0)
2787 continue;
2788
2789 BasicBlock *UseParent = UI->getParent();
2790
2791 // Ignore the users in the same BB (statement)
2792 if (UseParent == ParentBB)
2793 continue;
2794
2795 // Do not build scalar dependences inside a non-affine subregion.
2796 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
2797 continue;
2798
2799 // Check whether or not the use is in the SCoP.
2800 if (!R->contains(UseParent)) {
2801 AnyCrossStmtUse = true;
2802 continue;
2803 }
2804
2805 // If the instruction can be synthesized and the user is in the region
2806 // we do not need to add scalar dependences.
2807 if (canSynthesizeInst)
2808 continue;
2809
2810 // No need to translate these scalar dependences into polyhedral form,
2811 // because synthesizable scalars can be generated by the code generator.
2812 if (canSynthesize(UI, LI, SE, R))
2813 continue;
2814
2815 // Skip PHI nodes in the region as they handle their operands on their own.
2816 if (isa<PHINode>(UI))
2817 continue;
2818
2819 // Now U is used in another statement.
2820 AnyCrossStmtUse = true;
2821
2822 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00002823 // Use the def instruction as base address of the MemoryAccess, so that it
2824 // will become the name of the scalar access in the polyhedral form.
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002825 addScalarReadAccess(Inst, UI);
Michael Kruse7bf39442015-09-10 12:46:52 +00002826 }
2827
Tobias Grosserda95a4a2015-09-24 20:59:59 +00002828 if (ModelReadOnlyScalars && !isa<PHINode>(Inst)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002829 for (Value *Op : Inst->operands()) {
2830 if (canSynthesize(Op, LI, SE, R))
2831 continue;
2832
2833 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
2834 if (R->contains(OpInst))
2835 continue;
2836
2837 if (isa<Constant>(Op))
2838 continue;
2839
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002840 addScalarReadAccess(Op, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00002841 }
2842 }
2843
2844 return AnyCrossStmtUse;
2845}
2846
2847extern MapInsnToMemAcc InsnToMemAcc;
2848
Michael Krusee2bccbb2015-09-18 19:59:43 +00002849void ScopInfo::buildMemoryAccess(
2850 Instruction *Inst, Loop *L, Region *R,
2851 const ScopDetection::BoxedLoopsSetTy *BoxedLoops) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002852 unsigned Size;
2853 Type *SizeType;
2854 Value *Val;
Michael Krusee2bccbb2015-09-18 19:59:43 +00002855 enum MemoryAccess::AccessType Type;
Michael Kruse7bf39442015-09-10 12:46:52 +00002856
2857 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
2858 SizeType = Load->getType();
2859 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00002860 Type = MemoryAccess::READ;
Michael Kruse7bf39442015-09-10 12:46:52 +00002861 Val = Load;
2862 } else {
2863 StoreInst *Store = cast<StoreInst>(Inst);
2864 SizeType = Store->getValueOperand()->getType();
2865 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00002866 Type = MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00002867 Val = Store->getValueOperand();
2868 }
2869
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002870 auto Address = getPointerOperand(*Inst);
2871
2872 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00002873 const SCEVUnknown *BasePointer =
2874 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
2875
2876 assert(BasePointer && "Could not find base pointer");
2877 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
2878
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002879 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
2880 auto NewAddress = Address;
2881 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
2882 auto Src = BitCast->getOperand(0);
2883 auto SrcTy = Src->getType();
2884 auto DstTy = BitCast->getType();
2885 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
2886 NewAddress = Src;
2887 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002888
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002889 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
2890 std::vector<const SCEV *> Subscripts;
2891 std::vector<int> Sizes;
2892 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
2893 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002894
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002895 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002896
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002897 bool AllAffineSubcripts = true;
2898 for (auto Subscript : Subscripts)
2899 if (!isAffineExpr(R, Subscript, *SE)) {
2900 AllAffineSubcripts = false;
2901 break;
2902 }
2903
2904 if (AllAffineSubcripts && Sizes.size() > 0) {
2905 for (auto V : Sizes)
2906 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
2907 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002908 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002909 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002910
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002911 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
2912 Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00002913 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002914 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002915 }
2916 }
2917
Michael Kruse7bf39442015-09-10 12:46:52 +00002918 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00002919 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002920 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
2921 AccItr->second.DelinearizedSubscripts,
2922 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00002923 return;
2924 }
Michael Kruse7bf39442015-09-10 12:46:52 +00002925
2926 // Check if the access depends on a loop contained in a non-affine subregion.
2927 bool isVariantInNonAffineLoop = false;
2928 if (BoxedLoops) {
2929 SetVector<const Loop *> Loops;
2930 findLoops(AccessFunction, Loops);
2931 for (const Loop *L : Loops)
2932 if (BoxedLoops->count(L))
2933 isVariantInNonAffineLoop = true;
2934 }
2935
2936 bool IsAffine = !isVariantInNonAffineLoop &&
2937 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue());
2938
Michael Krusecaac2b62015-09-26 15:51:44 +00002939 // FIXME: Size of the number of bytes of an array element, not the number of
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002940 // elements as probably intended here.
Tobias Grossera43b6e92015-09-27 17:54:50 +00002941 const SCEV *SizeSCEV =
2942 SE->getConstant(TD->getIntPtrType(Inst->getContext()), Size);
Michael Kruse7bf39442015-09-10 12:46:52 +00002943
Michael Krusee2bccbb2015-09-18 19:59:43 +00002944 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
2945 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00002946
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002947 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, IsAffine,
2948 ArrayRef<const SCEV *>(AccessFunction),
2949 ArrayRef<const SCEV *>(SizeSCEV), Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00002950}
2951
Michael Krused868b5d2015-09-10 15:25:24 +00002952void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002953
2954 if (SD->isNonAffineSubRegion(&SR, &R)) {
2955 for (BasicBlock *BB : SR.blocks())
2956 buildAccessFunctions(R, *BB, &SR);
2957 return;
2958 }
2959
2960 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
2961 if (I->isSubRegion())
2962 buildAccessFunctions(R, *I->getNodeAs<Region>());
2963 else
2964 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
2965}
2966
Michael Krused868b5d2015-09-10 15:25:24 +00002967void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
2968 Region *NonAffineSubRegion,
2969 bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002970 Loop *L = LI->getLoopFor(&BB);
2971
2972 // The set of loops contained in non-affine subregions that are part of R.
2973 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
2974
2975 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
2976 Instruction *Inst = I;
2977
2978 PHINode *PHI = dyn_cast<PHINode>(Inst);
2979 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00002980 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00002981
2982 // For the exit block we stop modeling after the last PHI node.
2983 if (!PHI && IsExitBlock)
2984 break;
2985
2986 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
Michael Krusee2bccbb2015-09-18 19:59:43 +00002987 buildMemoryAccess(Inst, L, &R, BoxedLoops);
Michael Kruse7bf39442015-09-10 12:46:52 +00002988
2989 if (isIgnoredIntrinsic(Inst))
2990 continue;
2991
2992 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00002993 if (!isa<StoreInst>(Inst))
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002994 addScalarWriteAccess(Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00002995 }
2996 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00002997}
Michael Kruse7bf39442015-09-10 12:46:52 +00002998
Michael Kruse2d0ece92015-09-24 11:41:21 +00002999void ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3000 MemoryAccess::AccessType Type,
3001 Value *BaseAddress, unsigned ElemBytes,
3002 bool Affine, Value *AccessValue,
3003 ArrayRef<const SCEV *> Subscripts,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003004 ArrayRef<const SCEV *> Sizes,
3005 MemoryAccess::AccessOrigin Origin) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00003006 AccFuncSetType &AccList = AccFuncMap[BB];
3007 size_t Identifier = AccList.size();
Michael Kruse7bf39442015-09-10 12:46:52 +00003008
Michael Krusee2bccbb2015-09-18 19:59:43 +00003009 Value *BaseAddr = BaseAddress;
3010 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3011
3012 std::string IdName = "__polly_array_ref_" + std::to_string(Identifier);
3013 isl_id *Id = isl_id_alloc(ctx, IdName.c_str(), nullptr);
3014
Michael Kruse2d0ece92015-09-24 11:41:21 +00003015 AccList.emplace_back(Inst, Id, Type, BaseAddress, ElemBytes, Affine,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003016 Subscripts, Sizes, AccessValue, Origin, BaseName);
Michael Kruse7bf39442015-09-10 12:46:52 +00003017}
3018
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003019void ScopInfo::addExplicitAccess(
3020 Instruction *MemAccInst, MemoryAccess::AccessType Type, Value *BaseAddress,
3021 unsigned ElemBytes, bool IsAffine, ArrayRef<const SCEV *> Subscripts,
3022 ArrayRef<const SCEV *> Sizes, Value *AccessValue) {
3023 assert(isa<LoadInst>(MemAccInst) || isa<StoreInst>(MemAccInst));
3024 assert(isa<LoadInst>(MemAccInst) == (Type == MemoryAccess::READ));
3025 addMemoryAccess(MemAccInst->getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003026 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
3027 MemoryAccess::EXPLICIT);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003028}
3029void ScopInfo::addScalarWriteAccess(Instruction *Value) {
3030 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
3031 true, Value, ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003032 ArrayRef<const SCEV *>(), MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003033}
3034void ScopInfo::addScalarReadAccess(Value *Value, Instruction *User) {
3035 assert(!isa<PHINode>(User));
3036 addMemoryAccess(User->getParent(), User, MemoryAccess::READ, Value, 1, true,
3037 Value, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003038 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003039}
3040void ScopInfo::addScalarReadAccess(Value *Value, PHINode *User,
3041 BasicBlock *UserBB) {
3042 addMemoryAccess(UserBB, User, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003043 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3044 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003045}
3046void ScopInfo::addPHIWriteAccess(PHINode *PHI, BasicBlock *IncomingBlock,
3047 Value *IncomingValue, bool IsExitBlock) {
3048 addMemoryAccess(IncomingBlock, IncomingBlock->getTerminator(),
3049 MemoryAccess::MUST_WRITE, PHI, 1, true, IncomingValue,
3050 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003051 IsExitBlock ? MemoryAccess::SCALAR : MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003052}
3053void ScopInfo::addPHIReadAccess(PHINode *PHI) {
3054 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003055 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3056 MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003057}
3058
Michael Kruse9d080092015-09-11 21:41:48 +00003059Scop *ScopInfo::buildScop(Region &R, DominatorTree &DT) {
3060 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
3061 Scop *S = new Scop(R, AccFuncMap, *SE, DT, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00003062
3063 buildAccessFunctions(R, R);
3064
3065 // In case the region does not have an exiting block we will later (during
3066 // code generation) split the exit block. This will move potential PHI nodes
3067 // from the current exit block into the new region exiting block. Hence, PHI
3068 // nodes that are at this point not part of the region will be.
3069 // To handle these PHI nodes later we will now model their operands as scalar
3070 // accesses. Note that we do not model anything in the exit block if we have
3071 // an exiting block in the region, as there will not be any splitting later.
3072 if (!R.getExitingBlock())
3073 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
3074
Michael Kruse9d080092015-09-11 21:41:48 +00003075 S->init(*LI, *SD, *AA);
3076 return S;
Michael Kruse7bf39442015-09-10 12:46:52 +00003077}
3078
Michael Krused868b5d2015-09-10 15:25:24 +00003079void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00003080 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00003081 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00003082 return;
3083 }
3084
Michael Kruse9d080092015-09-11 21:41:48 +00003085 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00003086}
3087
Michael Krused868b5d2015-09-10 15:25:24 +00003088void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00003089 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00003090 if (scop) {
3091 delete scop;
3092 scop = 0;
3093 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003094}
3095
3096//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00003097ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00003098 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00003099 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00003100}
3101
3102ScopInfo::~ScopInfo() {
3103 clear();
3104 isl_ctx_free(ctx);
3105}
3106
Tobias Grosser75805372011-04-29 06:27:02 +00003107void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Michael Krused868b5d2015-09-10 15:25:24 +00003108 AU.addRequiredID(IndependentBlocksID);
Chandler Carruthf5579872015-01-17 14:16:56 +00003109 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00003110 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00003111 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00003112 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
3113 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003114 AU.addRequired<AAResultsWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00003115 AU.setPreservesAll();
3116}
3117
3118bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00003119 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00003120
Michael Krused868b5d2015-09-10 15:25:24 +00003121 if (!SD->isMaxRegionInScop(*R))
3122 return false;
3123
3124 Function *F = R->getEntry()->getParent();
3125 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3126 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3127 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3128 TD = &F->getParent()->getDataLayout();
3129 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Krused868b5d2015-09-10 15:25:24 +00003130
Michael Kruse9d080092015-09-11 21:41:48 +00003131 scop = buildScop(*R, DT);
Tobias Grosser75805372011-04-29 06:27:02 +00003132
Tobias Grosserd6a50b32015-05-30 06:26:21 +00003133 DEBUG(scop->print(dbgs()));
3134
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003135 if (!scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003136 delete scop;
3137 scop = nullptr;
3138 return false;
3139 }
3140
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003141 // Statistics.
3142 ++ScopFound;
3143 if (scop->getMaxLoopDepth() > 0)
3144 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00003145 return false;
3146}
3147
3148char ScopInfo::ID = 0;
3149
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003150Pass *polly::createScopInfoPass() { return new ScopInfo(); }
3151
Tobias Grosser73600b82011-10-08 00:30:40 +00003152INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
3153 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003154 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003155INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00003156INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00003157INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00003158INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003159INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003160INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00003161INITIALIZE_PASS_END(ScopInfo, "polly-scops",
3162 "Polly - Create polyhedral description of Scops", false,
3163 false)