blob: eb9bff873cdd776fc77d20745b588d15792dbcc2 [file] [log] [blame]
Johannes Doerfert58a7c752015-09-28 09:48:53 +00001//===--------- ScopInfo.cpp - Create Scops from LLVM IR ------------------===//
Tobias Grosser75805372011-04-29 06:27:02 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Create a polyhedral description for a static control flow region.
11//
12// The pass creates a polyhedral description of the Scops detected by the Scop
13// detection derived from their LLVM-IR code.
14//
Tobias Grossera5605d32014-10-29 19:58:28 +000015// This representation is shared among several tools in the polyhedral
Tobias Grosser75805372011-04-29 06:27:02 +000016// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
Tobias Grosser75805372011-04-29 06:27:02 +000020#include "polly/LinkAllPasses.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000021#include "polly/CodeGen/BlockGenerators.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000022#include "polly/Options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000023#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000024#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000025#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000026#include "polly/Support/ScopHelper.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000027#include "llvm/ADT/MapVector.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000028#include "llvm/ADT/PostOrderIterator.h"
29#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000030#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000031#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000032#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000033#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000034#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000035#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000036#include "llvm/Analysis/RegionIterator.h"
37#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser75805372011-04-29 06:27:02 +000038#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000039#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000040#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000041#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000042#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000043#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000044#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000045#include "isl/schedule.h"
46#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000047#include "isl/set.h"
48#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000049#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000050#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000051#include <sstream>
52#include <string>
53#include <vector>
54
55using namespace llvm;
56using namespace polly;
57
Chandler Carruth95fef942014-04-22 03:30:19 +000058#define DEBUG_TYPE "polly-scops"
59
Tobias Grosser74394f02013-01-14 22:40:23 +000060STATISTIC(ScopFound, "Number of valid Scops");
61STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000062
Michael Kruse7bf39442015-09-10 12:46:52 +000063static cl::opt<bool> ModelReadOnlyScalars(
64 "polly-analyze-read-only-scalars",
65 cl::desc("Model read-only scalar values in the scop description"),
66 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
67
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000068// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000069// operations can overflow easily. Additive reductions and bit operations
70// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000071static cl::opt<bool> DisableMultiplicativeReductions(
72 "polly-disable-multiplicative-reductions",
73 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
74 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000075
Johannes Doerfert9143d672014-09-27 11:02:39 +000076static cl::opt<unsigned> RunTimeChecksMaxParameters(
77 "polly-rtc-max-parameters",
78 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
79 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
80
Tobias Grosser71500722015-03-28 15:11:14 +000081static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
82 "polly-rtc-max-arrays-per-group",
83 cl::desc("The maximal number of arrays to compare in each alias group."),
84 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000085static cl::opt<std::string> UserContextStr(
86 "polly-context", cl::value_desc("isl parameter set"),
87 cl::desc("Provide additional constraints on the context parameters"),
88 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000089
Tobias Grosserd83b8a82015-08-20 19:08:11 +000090static cl::opt<bool> DetectReductions("polly-detect-reductions",
91 cl::desc("Detect and exploit reductions"),
92 cl::Hidden, cl::ZeroOrMore,
93 cl::init(true), cl::cat(PollyCategory));
94
Michael Kruse7bf39442015-09-10 12:46:52 +000095//===----------------------------------------------------------------------===//
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 Doerfert9a132f32015-09-28 09:33:22 +0000917/// @brief Set the dimension Ids from @p From in @p To.
918static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
919 __isl_take isl_set *To) {
920 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
921 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
922 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
923 }
924 return To;
925}
926
927/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000928static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000929 __isl_take isl_pw_aff *L,
930 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +0000931 switch (Pred) {
932 case ICmpInst::ICMP_EQ:
933 return isl_pw_aff_eq_set(L, R);
934 case ICmpInst::ICMP_NE:
935 return isl_pw_aff_ne_set(L, R);
936 case ICmpInst::ICMP_SLT:
937 return isl_pw_aff_lt_set(L, R);
938 case ICmpInst::ICMP_SLE:
939 return isl_pw_aff_le_set(L, R);
940 case ICmpInst::ICMP_SGT:
941 return isl_pw_aff_gt_set(L, R);
942 case ICmpInst::ICMP_SGE:
943 return isl_pw_aff_ge_set(L, R);
944 case ICmpInst::ICMP_ULT:
945 return isl_pw_aff_lt_set(L, R);
946 case ICmpInst::ICMP_UGT:
947 return isl_pw_aff_gt_set(L, R);
948 case ICmpInst::ICMP_ULE:
949 return isl_pw_aff_le_set(L, R);
950 case ICmpInst::ICMP_UGE:
951 return isl_pw_aff_ge_set(L, R);
952 default:
953 llvm_unreachable("Non integer predicate not supported");
954 }
955}
956
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000957/// @brief Create the conditions under which @p L @p Pred @p R is true.
958///
959/// Helper function that will make sure the dimensions of the result have the
960/// same isl_id's as the @p Domain.
961static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
962 __isl_take isl_pw_aff *L,
963 __isl_take isl_pw_aff *R,
964 __isl_keep isl_set *Domain) {
965 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
966 return setDimensionIds(Domain, ConsequenceCondSet);
967}
968
969/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000970///
971/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000972/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
973/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000974static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000975buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +0000976 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
977
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000978 Value *Condition = getConditionFromTerminator(SI);
979 assert(Condition && "No condition for switch");
980
981 ScalarEvolution &SE = *S.getSE();
982 BasicBlock *BB = SI->getParent();
983 isl_pw_aff *LHS, *RHS;
984 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
985
986 unsigned NumSuccessors = SI->getNumSuccessors();
987 ConditionSets.resize(NumSuccessors);
988 for (auto &Case : SI->cases()) {
989 unsigned Idx = Case.getSuccessorIndex();
990 ConstantInt *CaseValue = Case.getCaseValue();
991
992 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
993 isl_set *CaseConditionSet =
994 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
995 ConditionSets[Idx] = isl_set_coalesce(
996 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
997 }
998
999 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1000 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1001 for (unsigned u = 2; u < NumSuccessors; u++)
1002 ConditionSetUnion =
1003 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1004 ConditionSets[0] = setDimensionIds(
1005 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1006
1007 S.markAsOptimized();
1008 isl_pw_aff_free(LHS);
1009}
1010
1011/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1012///
1013/// This will fill @p ConditionSets with the conditions under which control
1014/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1015/// have as many elements as @p TI has successors.
1016static void
1017buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1018 __isl_keep isl_set *Domain,
1019 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1020
1021 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1022 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1023
1024 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1025
1026 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001027 ConditionSets.push_back(isl_set_copy(Domain));
1028 return;
1029 }
1030
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001031 Value *Condition = getConditionFromTerminator(TI);
1032 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001033
1034 isl_set *ConsequenceCondSet = nullptr;
1035 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1036 if (CCond->isZero())
1037 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1038 else
1039 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1040 } else {
1041 auto *ICond = dyn_cast<ICmpInst>(Condition);
1042 assert(ICond &&
1043 "Condition of exiting branch was neither constant nor ICmp!");
1044
1045 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001046 BasicBlock *BB = TI->getParent();
Johannes Doerfert96425c22015-08-30 21:13:53 +00001047 isl_pw_aff *LHS, *RHS;
Johannes Doerfertcef616f2015-09-15 22:49:04 +00001048 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1049 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001050 ConsequenceCondSet =
1051 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001052 }
1053
1054 assert(ConsequenceCondSet);
1055 isl_set *AlternativeCondSet =
1056 isl_set_complement(isl_set_copy(ConsequenceCondSet));
1057
1058 ConditionSets.push_back(isl_set_coalesce(
1059 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
1060 ConditionSets.push_back(isl_set_coalesce(
1061 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
1062}
1063
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001064void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +00001065 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +00001066
Tobias Grosser084d8f72012-05-29 09:29:44 +00001067 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1068
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001069 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001070 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001071}
1072
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001073void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001074 isl_ctx *Ctx = Parent.getIslCtx();
1075 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1076 Type *Ty = GEP->getPointerOperandType();
1077 ScalarEvolution &SE = *Parent.getSE();
1078
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001079 std::vector<const SCEV *> Subscripts;
1080 std::vector<int> Sizes;
1081
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001082 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001083
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001084 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001085 Ty = PtrTy->getElementType();
1086 }
1087
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001088 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001089
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001090 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001091
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001092 for (size_t i = 0; i < Sizes.size(); i++) {
1093 auto Expr = Subscripts[i + IndexOffset];
1094 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001095
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001096 if (!isAffineExpr(&Parent.getRegion(), Expr, SE))
1097 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001098
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001099 isl_pw_aff *AccessOffset = getPwAff(Expr);
1100 AccessOffset =
1101 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001102
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001103 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1104 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001105
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001106 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1107 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1108 OutOfBound = isl_set_params(OutOfBound);
1109 isl_set *InBound = isl_set_complement(OutOfBound);
1110 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001111
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001112 // A => B == !A or B
1113 isl_set *InBoundIfExecuted =
1114 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001115
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001116 Parent.addAssumption(InBoundIfExecuted);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001117 }
1118
1119 isl_local_space_free(LSpace);
1120}
1121
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001122void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1123 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001124 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1125 deriveAssumptionsFromGEP(GEP);
1126}
1127
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001128void ScopStmt::collectSurroundingLoops() {
1129 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1130 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1131 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1132 isl_id_free(DimId);
1133 }
1134}
1135
Michael Kruse9d080092015-09-11 21:41:48 +00001136ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001137 : Parent(parent), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001138
Tobias Grosser16c44032015-07-09 07:31:45 +00001139 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001140
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001141 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001142 collectSurroundingLoops();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001143
1144 BasicBlock *EntryBB = R.getEntry();
1145 for (BasicBlock *Block : R.blocks()) {
Michael Kruse9d080092015-09-11 21:41:48 +00001146 buildAccesses(Block, Block != EntryBB);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001147 deriveAssumptions(Block);
1148 }
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001149 if (DetectReductions)
1150 checkForReductions();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001151}
1152
Michael Kruse9d080092015-09-11 21:41:48 +00001153ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001154 : Parent(parent), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001155
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001156 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +00001157
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001158 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001159 collectSurroundingLoops();
Michael Kruse9d080092015-09-11 21:41:48 +00001160 buildAccesses(BB);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001161 deriveAssumptions(BB);
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001162 if (DetectReductions)
1163 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001164}
1165
Johannes Doerferte58a0122014-06-27 20:31:28 +00001166/// @brief Collect loads which might form a reduction chain with @p StoreMA
1167///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001168/// Check if the stored value for @p StoreMA is a binary operator with one or
1169/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001170/// used only once (by @p StoreMA) and its load operands are also used only
1171/// once, we have found a possible reduction chain. It starts at an operand
1172/// load and includes the binary operator and @p StoreMA.
1173///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001174/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001175/// escape this block or into any other store except @p StoreMA.
1176void ScopStmt::collectCandiateReductionLoads(
1177 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1178 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1179 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001180 return;
1181
1182 // Skip if there is not one binary operator between the load and the store
1183 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001184 if (!BinOp)
1185 return;
1186
1187 // Skip if the binary operators has multiple uses
1188 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001189 return;
1190
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001191 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001192 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1193 return;
1194
Johannes Doerfert9890a052014-07-01 00:32:29 +00001195 // Skip if the binary operator is outside the current SCoP
1196 if (BinOp->getParent() != Store->getParent())
1197 return;
1198
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001199 // Skip if it is a multiplicative reduction and we disabled them
1200 if (DisableMultiplicativeReductions &&
1201 (BinOp->getOpcode() == Instruction::Mul ||
1202 BinOp->getOpcode() == Instruction::FMul))
1203 return;
1204
Johannes Doerferte58a0122014-06-27 20:31:28 +00001205 // Check the binary operator operands for a candidate load
1206 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1207 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1208 if (!PossibleLoad0 && !PossibleLoad1)
1209 return;
1210
1211 // A load is only a candidate if it cannot escape (thus has only this use)
1212 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001213 if (PossibleLoad0->getParent() == Store->getParent())
1214 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001215 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001216 if (PossibleLoad1->getParent() == Store->getParent())
1217 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001218}
1219
1220/// @brief Check for reductions in this ScopStmt
1221///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001222/// Iterate over all store memory accesses and check for valid binary reduction
1223/// like chains. For all candidates we check if they have the same base address
1224/// and there are no other accesses which overlap with them. The base address
1225/// check rules out impossible reductions candidates early. The overlap check,
1226/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001227/// guarantees that none of the intermediate results will escape during
1228/// execution of the loop nest. We basically check here that no other memory
1229/// access can access the same memory as the potential reduction.
1230void ScopStmt::checkForReductions() {
1231 SmallVector<MemoryAccess *, 2> Loads;
1232 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1233
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001234 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001235 // stores and collecting possible reduction loads.
1236 for (MemoryAccess *StoreMA : MemAccs) {
1237 if (StoreMA->isRead())
1238 continue;
1239
1240 Loads.clear();
1241 collectCandiateReductionLoads(StoreMA, Loads);
1242 for (MemoryAccess *LoadMA : Loads)
1243 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1244 }
1245
1246 // Then check each possible candidate pair.
1247 for (const auto &CandidatePair : Candidates) {
1248 bool Valid = true;
1249 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1250 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1251
1252 // Skip those with obviously unequal base addresses.
1253 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1254 isl_map_free(LoadAccs);
1255 isl_map_free(StoreAccs);
1256 continue;
1257 }
1258
1259 // And check if the remaining for overlap with other memory accesses.
1260 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1261 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1262 isl_set *AllAccs = isl_map_range(AllAccsRel);
1263
1264 for (MemoryAccess *MA : MemAccs) {
1265 if (MA == CandidatePair.first || MA == CandidatePair.second)
1266 continue;
1267
1268 isl_map *AccRel =
1269 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1270 isl_set *Accs = isl_map_range(AccRel);
1271
1272 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1273 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1274 Valid = Valid && isl_set_is_empty(OverlapAccs);
1275 isl_set_free(OverlapAccs);
1276 }
1277 }
1278
1279 isl_set_free(AllAccs);
1280 if (!Valid)
1281 continue;
1282
Johannes Doerfertf6183392014-07-01 20:52:51 +00001283 const LoadInst *Load =
1284 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1285 MemoryAccess::ReductionType RT =
1286 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1287
Johannes Doerferte58a0122014-06-27 20:31:28 +00001288 // If no overlapping access was found we mark the load and store as
1289 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001290 CandidatePair.first->markAsReductionLike(RT);
1291 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001292 }
Tobias Grosser75805372011-04-29 06:27:02 +00001293}
1294
Tobias Grosser74394f02013-01-14 22:40:23 +00001295std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001296
Tobias Grosser54839312015-04-21 11:37:25 +00001297std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001298 auto *S = getSchedule();
1299 auto Str = stringFromIslObj(S);
1300 isl_map_free(S);
1301 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001302}
1303
Tobias Grosser74394f02013-01-14 22:40:23 +00001304unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001305
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001306unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001307
Tobias Grosser75805372011-04-29 06:27:02 +00001308const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1309
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001310const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001311 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001312}
1313
Tobias Grosser74394f02013-01-14 22:40:23 +00001314isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001315
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001316__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001317
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001318__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001319 return isl_set_get_space(Domain);
1320}
1321
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001322__isl_give isl_id *ScopStmt::getDomainId() const {
1323 return isl_set_get_tuple_id(Domain);
1324}
Tobias Grossercd95b772012-08-30 11:49:38 +00001325
Tobias Grosser75805372011-04-29 06:27:02 +00001326ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001327 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001328 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001329}
1330
1331void ScopStmt::print(raw_ostream &OS) const {
1332 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001333 OS.indent(12) << "Domain :=\n";
1334
1335 if (Domain) {
1336 OS.indent(16) << getDomainStr() << ";\n";
1337 } else
1338 OS.indent(16) << "n/a\n";
1339
Tobias Grosser54839312015-04-21 11:37:25 +00001340 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001341
1342 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001343 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001344 } else
1345 OS.indent(16) << "n/a\n";
1346
Tobias Grosser083d3d32014-06-28 08:59:45 +00001347 for (MemoryAccess *Access : MemAccs)
1348 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001349}
1350
1351void ScopStmt::dump() const { print(dbgs()); }
1352
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001353void ScopStmt::hoistMemoryAccesses(MemoryAccessList &InvMAs,
1354 InvariantAccessesTy &TargetList) {
1355
1356 // Remove all memory accesses in @p InvMAs from this statement together
1357 // with all scalar accesses that were caused by them. The tricky iteration
1358 // order uses is needed because the MemAccs is a vector and the order in
1359 // which the accesses of each memory access list (MAL) are stored in this
1360 // vector is reversed.
1361 for (MemoryAccess *MA : InvMAs) {
1362 auto &MAL = *lookupAccessesFor(MA->getAccessInstruction());
1363 MAL.reverse();
1364
1365 auto MALIt = MAL.begin();
1366 auto MALEnd = MAL.end();
1367 auto MemAccsIt = MemAccs.begin();
1368 while (MALIt != MALEnd) {
1369 while (*MemAccsIt != *MALIt)
1370 MemAccsIt++;
1371
1372 MALIt++;
1373 MemAccs.erase(MemAccsIt);
1374 }
1375
1376 InstructionToAccess.erase(MA->getAccessInstruction());
1377 delete &MAL;
1378 }
1379
1380 // Get the context under which this statement, hence the memory accesses, are
1381 // executed.
1382 isl_set *DomainCtx = isl_set_params(getDomain());
1383 DomainCtx = isl_set_remove_redundancies(DomainCtx);
1384 DomainCtx = isl_set_detect_equalities(DomainCtx);
1385 DomainCtx = isl_set_coalesce(DomainCtx);
1386
1387 for (MemoryAccess *MA : InvMAs)
1388 TargetList.push_back(std::make_pair(MA, isl_set_copy(DomainCtx)));
1389
1390 isl_set_free(DomainCtx);
1391}
1392
Tobias Grosser75805372011-04-29 06:27:02 +00001393//===----------------------------------------------------------------------===//
1394/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001395
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001396void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001397 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1398 isl_set_free(Context);
1399 Context = NewContext;
1400}
1401
Tobias Grosserabfbe632013-02-05 12:09:06 +00001402void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001403 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001404 Parameter = extractConstantFactor(Parameter, *SE).second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001405 if (ParameterIds.find(Parameter) != ParameterIds.end())
1406 continue;
1407
1408 int dimension = Parameters.size();
1409
1410 Parameters.push_back(Parameter);
1411 ParameterIds[Parameter] = dimension;
1412 }
1413}
1414
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001415__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1416 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001417
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001418 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001419 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001420
Tobias Grosser8f99c162011-11-15 11:38:55 +00001421 std::string ParameterName;
1422
1423 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1424 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001425 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001426 }
1427
1428 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001429 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001430
Tobias Grosser20532b82014-04-11 17:56:49 +00001431 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1432 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001433}
Tobias Grosser75805372011-04-29 06:27:02 +00001434
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001435isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1436 isl_set *DomainContext = isl_union_set_params(getDomains());
1437 return isl_set_intersect_params(C, DomainContext);
1438}
1439
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001440void Scop::buildBoundaryContext() {
1441 BoundaryContext = Affinator.getWrappingContext();
1442 BoundaryContext = isl_set_complement(BoundaryContext);
1443 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
1444}
1445
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001446void Scop::addUserContext() {
1447 if (UserContextStr.empty())
1448 return;
1449
1450 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1451 isl_space *Space = getParamSpace();
1452 if (isl_space_dim(Space, isl_dim_param) !=
1453 isl_set_dim(UserContext, isl_dim_param)) {
1454 auto SpaceStr = isl_space_to_str(Space);
1455 errs() << "Error: the context provided in -polly-context has not the same "
1456 << "number of dimensions than the computed context. Due to this "
1457 << "mismatch, the -polly-context option is ignored. Please provide "
1458 << "the context in the parameter space: " << SpaceStr << ".\n";
1459 free(SpaceStr);
1460 isl_set_free(UserContext);
1461 isl_space_free(Space);
1462 return;
1463 }
1464
1465 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1466 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1467 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1468
1469 if (strcmp(NameContext, NameUserContext) != 0) {
1470 auto SpaceStr = isl_space_to_str(Space);
1471 errs() << "Error: the name of dimension " << i
1472 << " provided in -polly-context "
1473 << "is '" << NameUserContext << "', but the name in the computed "
1474 << "context is '" << NameContext
1475 << "'. Due to this name mismatch, "
1476 << "the -polly-context option is ignored. Please provide "
1477 << "the context in the parameter space: " << SpaceStr << ".\n";
1478 free(SpaceStr);
1479 isl_set_free(UserContext);
1480 isl_space_free(Space);
1481 return;
1482 }
1483
1484 UserContext =
1485 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1486 isl_space_get_dim_id(Space, isl_dim_param, i));
1487 }
1488
1489 Context = isl_set_intersect(Context, UserContext);
1490 isl_space_free(Space);
1491}
1492
Tobias Grosser6be480c2011-11-08 15:41:13 +00001493void Scop::buildContext() {
1494 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001495 Context = isl_set_universe(isl_space_copy(Space));
1496 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001497}
1498
Tobias Grosser18daaca2012-05-22 10:47:27 +00001499void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001500 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001501 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001502
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001503 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001504
Johannes Doerferte7044942015-02-24 11:58:30 +00001505 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001506 }
1507}
1508
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001509void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001510 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001511 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001512
Tobias Grosser083d3d32014-06-28 08:59:45 +00001513 for (const auto &ParamID : ParameterIds) {
1514 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001515 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001516 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001517 }
1518
1519 // Align the parameters of all data structures to the model.
1520 Context = isl_set_align_params(Context, Space);
1521
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001522 for (ScopStmt &Stmt : *this)
1523 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001524}
1525
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001526static __isl_give isl_set *
1527simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1528 const Scop &S) {
1529 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1530 AssumptionContext = isl_set_gist_params(AssumptionContext, DomainParameters);
1531 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1532 return AssumptionContext;
1533}
1534
1535void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001536 // The parameter constraints of the iteration domains give us a set of
1537 // constraints that need to hold for all cases where at least a single
1538 // statement iteration is executed in the whole scop. We now simplify the
1539 // assumed context under the assumption that such constraints hold and at
1540 // least a single statement iteration is executed. For cases where no
1541 // statement instances are executed, the assumptions we have taken about
1542 // the executed code do not matter and can be changed.
1543 //
1544 // WARNING: This only holds if the assumptions we have taken do not reduce
1545 // the set of statement instances that are executed. Otherwise we
1546 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001547 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001548 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001549 // performed. In such a case, modifying the run-time conditions and
1550 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001551 // to not be executed.
1552 //
1553 // Example:
1554 //
1555 // When delinearizing the following code:
1556 //
1557 // for (long i = 0; i < 100; i++)
1558 // for (long j = 0; j < m; j++)
1559 // A[i+p][j] = 1.0;
1560 //
1561 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001562 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001563 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001564 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1565 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001566}
1567
Johannes Doerfertb164c792014-09-18 11:17:17 +00001568/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001569static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001570 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1571 isl_pw_multi_aff *MinPMA, *MaxPMA;
1572 isl_pw_aff *LastDimAff;
1573 isl_aff *OneAff;
1574 unsigned Pos;
1575
Johannes Doerfert9143d672014-09-27 11:02:39 +00001576 // Restrict the number of parameters involved in the access as the lexmin/
1577 // lexmax computation will take too long if this number is high.
1578 //
1579 // Experiments with a simple test case using an i7 4800MQ:
1580 //
1581 // #Parameters involved | Time (in sec)
1582 // 6 | 0.01
1583 // 7 | 0.04
1584 // 8 | 0.12
1585 // 9 | 0.40
1586 // 10 | 1.54
1587 // 11 | 6.78
1588 // 12 | 30.38
1589 //
1590 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1591 unsigned InvolvedParams = 0;
1592 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1593 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1594 InvolvedParams++;
1595
1596 if (InvolvedParams > RunTimeChecksMaxParameters) {
1597 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001598 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001599 }
1600 }
1601
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001602 Set = isl_set_remove_divs(Set);
1603
Johannes Doerfertb164c792014-09-18 11:17:17 +00001604 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1605 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1606
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001607 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1608 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1609
Johannes Doerfertb164c792014-09-18 11:17:17 +00001610 // Adjust the last dimension of the maximal access by one as we want to
1611 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1612 // we test during code generation might now point after the end of the
1613 // allocated array but we will never dereference it anyway.
1614 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1615 "Assumed at least one output dimension");
1616 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1617 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1618 OneAff = isl_aff_zero_on_domain(
1619 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1620 OneAff = isl_aff_add_constant_si(OneAff, 1);
1621 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1622 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1623
1624 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1625
1626 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001627 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001628}
1629
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001630static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1631 isl_set *Domain = MA->getStatement()->getDomain();
1632 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1633 return isl_set_reset_tuple_id(Domain);
1634}
1635
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001636/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1637static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001638 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001639 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001640
1641 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1642 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001643 Locations = isl_union_set_coalesce(Locations);
1644 Locations = isl_union_set_detect_equalities(Locations);
1645 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001646 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001647 isl_union_set_free(Locations);
1648 return Valid;
1649}
1650
Johannes Doerfert96425c22015-08-30 21:13:53 +00001651/// @brief Helper to treat non-affine regions and basic blocks the same.
1652///
1653///{
1654
1655/// @brief Return the block that is the representing block for @p RN.
1656static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1657 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1658 : RN->getNodeAs<BasicBlock>();
1659}
1660
1661/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001662static inline BasicBlock *
1663getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001664 if (RN->isSubRegion()) {
1665 assert(idx == 0);
1666 return RN->getNodeAs<Region>()->getExit();
1667 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001668 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001669}
1670
1671/// @brief Return the smallest loop surrounding @p RN.
1672static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1673 if (!RN->isSubRegion())
1674 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1675
1676 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1677 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1678 while (L && NonAffineSubRegion->contains(L))
1679 L = L->getParentLoop();
1680 return L;
1681}
1682
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001683static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1684 if (!RN->isSubRegion())
1685 return 1;
1686
1687 unsigned NumBlocks = 0;
1688 Region *R = RN->getNodeAs<Region>();
1689 for (auto BB : R->blocks()) {
1690 (void)BB;
1691 NumBlocks++;
1692 }
1693 return NumBlocks;
1694}
1695
Johannes Doerfert96425c22015-08-30 21:13:53 +00001696///}
1697
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001698static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1699 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001700 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001701 isl_id *DimId =
1702 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
1703 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
1704}
1705
Johannes Doerfert96425c22015-08-30 21:13:53 +00001706isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1707 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1708 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00001709 return getDomainConditions(BB);
1710}
1711
1712isl_set *Scop::getDomainConditions(BasicBlock *BB) {
1713 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001714 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001715}
1716
1717void Scop::buildDomains(Region *R, LoopInfo &LI, ScopDetection &SD,
1718 DominatorTree &DT) {
1719
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001720 auto *EntryBB = R->getEntry();
1721 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
1722 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001723
1724 Loop *L = LI.getLoopFor(EntryBB);
1725 while (LD-- >= 0) {
1726 S = addDomainDimId(S, LD + 1, L);
1727 L = L->getParentLoop();
1728 }
1729
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001730 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001731
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00001732 if (SD.isNonAffineSubRegion(R, R))
1733 return;
1734
Johannes Doerfert96425c22015-08-30 21:13:53 +00001735 buildDomainsWithBranchConstraints(R, LI, SD, DT);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001736 propagateDomainConstraints(R, LI, SD, DT);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001737}
1738
1739void Scop::buildDomainsWithBranchConstraints(Region *R, LoopInfo &LI,
1740 ScopDetection &SD,
1741 DominatorTree &DT) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001742 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00001743
1744 // To create the domain for each block in R we iterate over all blocks and
1745 // subregions in R and propagate the conditions under which the current region
1746 // element is executed. To this end we iterate in reverse post order over R as
1747 // it ensures that we first visit all predecessors of a region node (either a
1748 // basic block or a subregion) before we visit the region node itself.
1749 // Initially, only the domain for the SCoP region entry block is set and from
1750 // there we propagate the current domain to all successors, however we add the
1751 // condition that the successor is actually executed next.
1752 // As we are only interested in non-loop carried constraints here we can
1753 // simply skip loop back edges.
1754
1755 ReversePostOrderTraversal<Region *> RTraversal(R);
1756 for (auto *RN : RTraversal) {
1757
1758 // Recurse for affine subregions but go on for basic blocks and non-affine
1759 // subregions.
1760 if (RN->isSubRegion()) {
1761 Region *SubRegion = RN->getNodeAs<Region>();
1762 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
1763 buildDomainsWithBranchConstraints(SubRegion, LI, SD, DT);
1764 continue;
1765 }
1766 }
1767
1768 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001769 TerminatorInst *TI = BB->getTerminator();
1770
1771 // Unreachable instructions do not have successors so we can skip them.
1772 if (isa<UnreachableInst>(TI)) {
1773 // Assume unreachables only in error blocks.
1774 assert(isErrorBlock(*BB));
1775 continue;
1776 }
1777
Johannes Doerfert96425c22015-08-30 21:13:53 +00001778 isl_set *Domain = DomainMap[BB];
1779 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
1780 assert(Domain && "Due to reverse post order traversal of the region all "
1781 "predecessor of the current region node should have been "
1782 "visited and a domain for this region node should have "
1783 "been set.");
1784
1785 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1786 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1787
1788 // Build the condition sets for the successor nodes of the current region
1789 // node. If it is a non-affine subregion we will always execute the single
1790 // exit node, hence the single entry node domain is the condition set. For
1791 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001792 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001793 if (RN->isSubRegion())
1794 ConditionSets.push_back(isl_set_copy(Domain));
1795 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001796 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001797
1798 // Now iterate over the successors and set their initial domain based on
1799 // their condition set. We skip back edges here and have to be careful when
1800 // we leave a loop not to keep constraints over a dimension that doesn't
1801 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001802 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00001803 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001804 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001805 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001806
1807 // Skip back edges.
1808 if (DT.dominates(SuccBB, BB)) {
1809 isl_set_free(CondSet);
1810 continue;
1811 }
1812
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001813 // Do not adjust the number of dimensions if we enter a boxed loop or are
1814 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001815 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001816 Region *SuccRegion = RI.getRegionFor(SuccBB);
1817 if (BBLoop != SuccBBLoop && !RN->isSubRegion() &&
1818 !(SD.isNonAffineSubRegion(SuccRegion, &getRegion()) &&
1819 SuccRegion->contains(SuccBBLoop))) {
1820
1821 // Check if the edge to SuccBB is a loop entry or exit edge. If so
1822 // adjust the dimensionality accordingly. Lastly, if we leave a loop
1823 // and enter a new one we need to drop the old constraints.
1824 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001825 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001826 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001827 CondSet = isl_set_project_out(CondSet, isl_dim_set,
1828 isl_set_n_dim(CondSet) - LoopDepthDiff,
1829 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001830 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001831 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001832 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001833 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001834 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001835 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001836 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
1837 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001838 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001839 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00001840 }
1841
1842 // Set the domain for the successor or merge it with an existing domain in
1843 // case there are multiple paths (without loop back edges) to the
1844 // successor block.
1845 isl_set *&SuccDomain = DomainMap[SuccBB];
1846 if (!SuccDomain)
1847 SuccDomain = CondSet;
1848 else
1849 SuccDomain = isl_set_union(SuccDomain, CondSet);
1850
1851 SuccDomain = isl_set_coalesce(SuccDomain);
1852 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : " << Domain
1853 << "\n");
1854 }
1855 }
1856}
1857
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001858/// @brief Return the domain for @p BB wrt @p DomainMap.
1859///
1860/// This helper function will lookup @p BB in @p DomainMap but also handle the
1861/// case where @p BB is contained in a non-affine subregion using the region
1862/// tree obtained by @p RI.
1863static __isl_give isl_set *
1864getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
1865 RegionInfo &RI) {
1866 auto DIt = DomainMap.find(BB);
1867 if (DIt != DomainMap.end())
1868 return isl_set_copy(DIt->getSecond());
1869
1870 Region *R = RI.getRegionFor(BB);
1871 while (R->getEntry() == BB)
1872 R = R->getParent();
1873 return getDomainForBlock(R->getEntry(), DomainMap, RI);
1874}
1875
Johannes Doerferte114dc02015-09-14 11:15:58 +00001876static bool containsErrorBlock(RegionNode *RN) {
1877 if (!RN->isSubRegion())
1878 return isErrorBlock(*RN->getNodeAs<BasicBlock>());
1879 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
1880 if (isErrorBlock(*BB))
1881 return true;
1882 return false;
1883}
1884
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001885void Scop::propagateDomainConstraints(Region *R, LoopInfo &LI,
1886 ScopDetection &SD, DominatorTree &DT) {
1887 // Iterate over the region R and propagate the domain constrains from the
1888 // predecessors to the current node. In contrast to the
1889 // buildDomainsWithBranchConstraints function, this one will pull the domain
1890 // information from the predecessors instead of pushing it to the successors.
1891 // Additionally, we assume the domains to be already present in the domain
1892 // map here. However, we iterate again in reverse post order so we know all
1893 // predecessors have been visited before a block or non-affine subregion is
1894 // visited.
1895
1896 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
1897 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
1898
1899 ReversePostOrderTraversal<Region *> RTraversal(R);
1900 for (auto *RN : RTraversal) {
1901
1902 // Recurse for affine subregions but go on for basic blocks and non-affine
1903 // subregions.
1904 if (RN->isSubRegion()) {
1905 Region *SubRegion = RN->getNodeAs<Region>();
1906 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
1907 propagateDomainConstraints(SubRegion, LI, SD, DT);
1908 continue;
1909 }
1910 }
1911
1912 BasicBlock *BB = getRegionNodeBasicBlock(RN);
1913 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1914 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1915
1916 isl_set *&Domain = DomainMap[BB];
1917 assert(Domain && "Due to reverse post order traversal of the region all "
1918 "predecessor of the current region node should have been "
1919 "visited and a domain for this region node should have "
1920 "been set.");
1921
1922 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
1923 for (auto *PredBB : predecessors(BB)) {
1924
1925 // Skip backedges
1926 if (DT.dominates(BB, PredBB))
1927 continue;
1928
1929 isl_set *PredBBDom = nullptr;
1930
1931 // Handle the SCoP entry block with its outside predecessors.
1932 if (!getRegion().contains(PredBB))
1933 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
1934
1935 if (!PredBBDom) {
1936 // Determine the loop depth of the predecessor and adjust its domain to
1937 // the domain of the current block. This can mean we have to:
1938 // o) Drop a dimension if this block is the exit of a loop, not the
1939 // header of a new loop and the predecessor was part of the loop.
1940 // o) Add an unconstrainted new dimension if this block is the header
1941 // of a loop and the predecessor is not part of it.
1942 // o) Drop the information about the innermost loop dimension when the
1943 // predecessor and the current block are surrounded by different
1944 // loops in the same depth.
1945 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
1946 Loop *PredBBLoop = LI.getLoopFor(PredBB);
1947 while (BoxedLoops.count(PredBBLoop))
1948 PredBBLoop = PredBBLoop->getParentLoop();
1949
1950 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001951 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001952 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001953 PredBBDom = isl_set_project_out(
1954 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
1955 LoopDepthDiff);
1956 else if (PredBBLoopDepth < BBLoopDepth) {
1957 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001958 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001959 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
1960 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001961 PredBBDom = isl_set_drop_constraints_involving_dims(
1962 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001963 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001964 }
1965
1966 PredDom = isl_set_union(PredDom, PredBBDom);
1967 }
1968
1969 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00001970 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001971
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00001972 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001973 addLoopBoundsToHeaderDomain(BBLoop, LI);
1974
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001975 // Add assumptions for error blocks.
Johannes Doerferte114dc02015-09-14 11:15:58 +00001976 if (containsErrorBlock(RN)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001977 IsOptimized = true;
1978 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
1979 addAssumption(isl_set_complement(DomPar));
1980 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001981 }
1982}
1983
1984/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
1985/// is incremented by one and all other dimensions are equal, e.g.,
1986/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
1987/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
1988static __isl_give isl_map *
1989createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
1990 auto *MapSpace = isl_space_map_from_set(SetSpace);
1991 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
1992 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
1993 if (u != Dim)
1994 NextIterationMap =
1995 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
1996 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
1997 C = isl_constraint_set_constant_si(C, 1);
1998 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
1999 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2000 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2001 return NextIterationMap;
2002}
2003
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002004void Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
2005 int LoopDepth = getRelativeLoopDepth(L);
2006 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002007
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002008 BasicBlock *HeaderBB = L->getHeader();
2009 assert(DomainMap.count(HeaderBB));
2010 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002011
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002012 isl_map *NextIterationMap =
2013 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002014
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002015 isl_set *UnionBackedgeCondition =
2016 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002017
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002018 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2019 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002020
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002021 for (BasicBlock *LatchBB : LatchBlocks) {
2022 assert(DomainMap.count(LatchBB));
2023 isl_set *LatchBBDom = DomainMap[LatchBB];
2024 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002025
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002026 TerminatorInst *TI = LatchBB->getTerminator();
2027 BranchInst *BI = dyn_cast<BranchInst>(TI);
2028 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002029 BackedgeCondition = isl_set_copy(LatchBBDom);
2030 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002031 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002032 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002033 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002034
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002035 // Free the non back edge condition set as we do not need it.
2036 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002037
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002038 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002039 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002040
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002041 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2042 assert(LatchLoopDepth >= LoopDepth);
2043 BackedgeCondition =
2044 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2045 LatchLoopDepth - LoopDepth);
2046 UnionBackedgeCondition =
2047 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002048 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002049
2050 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2051 for (int i = 0; i < LoopDepth; i++)
2052 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2053
2054 isl_set *UnionBackedgeConditionComplement =
2055 isl_set_complement(UnionBackedgeCondition);
2056 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2057 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2058 UnionBackedgeConditionComplement =
2059 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2060 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2061 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2062
2063 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2064 HeaderBBDom = Parts.second;
2065
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002066 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2067 // the bounded assumptions to the context as they are already implied by the
2068 // <nsw> tag.
2069 if (Affinator.hasNSWAddRecForLoop(L)) {
2070 isl_set_free(Parts.first);
2071 return;
2072 }
2073
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002074 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2075 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfert707a4062015-09-20 16:38:19 +00002076 addAssumption(BoundedCtx);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002077}
2078
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002079void Scop::buildAliasChecks(AliasAnalysis &AA) {
2080 if (!PollyUseRuntimeAliasChecks)
2081 return;
2082
2083 if (buildAliasGroups(AA))
2084 return;
2085
2086 // If a problem occurs while building the alias groups we need to delete
2087 // this SCoP and pretend it wasn't valid in the first place. To this end
2088 // we make the assumed context infeasible.
2089 addAssumption(isl_set_empty(getParamSpace()));
2090
2091 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2092 << " could not be created as the number of parameters involved "
2093 "is too high. The SCoP will be "
2094 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2095 "the maximal number of parameters but be advised that the "
2096 "compile time might increase exponentially.\n\n");
2097}
2098
Johannes Doerfert9143d672014-09-27 11:02:39 +00002099bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002100 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002101 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002102 // for all memory accesses inside the SCoP.
2103 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002104 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002105 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002106 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002107 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002108 // if their access domains intersect, otherwise they are in different
2109 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002110 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002111 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002112 // and maximal accesses to each array of a group in read only and non
2113 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002114 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2115
2116 AliasSetTracker AST(AA);
2117
2118 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002119 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002120 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002121
2122 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002123 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002124 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2125 isl_set_free(StmtDomain);
2126 if (StmtDomainEmpty)
2127 continue;
2128
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002129 for (MemoryAccess *MA : Stmt) {
Michael Kruse8d0b7342015-09-25 21:21:00 +00002130 if (MA->isImplicit())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002131 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002132 if (!MA->isRead())
2133 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002134 Instruction *Acc = MA->getAccessInstruction();
2135 PtrToAcc[getPointerOperand(*Acc)] = MA;
2136 AST.add(Acc);
2137 }
2138 }
2139
2140 SmallVector<AliasGroupTy, 4> AliasGroups;
2141 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002142 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002143 continue;
2144 AliasGroupTy AG;
2145 for (auto PR : AS)
2146 AG.push_back(PtrToAcc[PR.getValue()]);
2147 assert(AG.size() > 1 &&
2148 "Alias groups should contain at least two accesses");
2149 AliasGroups.push_back(std::move(AG));
2150 }
2151
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002152 // Split the alias groups based on their domain.
2153 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2154 AliasGroupTy NewAG;
2155 AliasGroupTy &AG = AliasGroups[u];
2156 AliasGroupTy::iterator AGI = AG.begin();
2157 isl_set *AGDomain = getAccessDomain(*AGI);
2158 while (AGI != AG.end()) {
2159 MemoryAccess *MA = *AGI;
2160 isl_set *MADomain = getAccessDomain(MA);
2161 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2162 NewAG.push_back(MA);
2163 AGI = AG.erase(AGI);
2164 isl_set_free(MADomain);
2165 } else {
2166 AGDomain = isl_set_union(AGDomain, MADomain);
2167 AGI++;
2168 }
2169 }
2170 if (NewAG.size() > 1)
2171 AliasGroups.push_back(std::move(NewAG));
2172 isl_set_free(AGDomain);
2173 }
2174
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002175 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002176 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2177 for (AliasGroupTy &AG : AliasGroups) {
2178 NonReadOnlyBaseValues.clear();
2179 ReadOnlyPairs.clear();
2180
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002181 if (AG.size() < 2) {
2182 AG.clear();
2183 continue;
2184 }
2185
Johannes Doerfert13771732014-10-01 12:40:46 +00002186 for (auto II = AG.begin(); II != AG.end();) {
2187 Value *BaseAddr = (*II)->getBaseAddr();
2188 if (HasWriteAccess.count(BaseAddr)) {
2189 NonReadOnlyBaseValues.insert(BaseAddr);
2190 II++;
2191 } else {
2192 ReadOnlyPairs[BaseAddr].insert(*II);
2193 II = AG.erase(II);
2194 }
2195 }
2196
2197 // If we don't have read only pointers check if there are at least two
2198 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002199 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002200 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002201 continue;
2202 }
2203
2204 // If we don't have non read only pointers clear the alias group.
2205 if (NonReadOnlyBaseValues.empty()) {
2206 AG.clear();
2207 continue;
2208 }
2209
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002210 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002211 MinMaxAliasGroups.emplace_back();
2212 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2213 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2214 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2215 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002216
2217 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002218
2219 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002220 for (MemoryAccess *MA : AG)
2221 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002222
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002223 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2224 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002225
2226 // Bail out if the number of values we need to compare is too large.
2227 // This is important as the number of comparisions grows quadratically with
2228 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002229 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2230 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002231 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002232
2233 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002234 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002235 Accesses = isl_union_map_empty(getParamSpace());
2236
2237 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2238 for (MemoryAccess *MA : ReadOnlyPair.second)
2239 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2240
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002241 Valid =
2242 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002243
2244 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002245 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002246 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002247
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002248 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002249}
2250
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002251static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
2252 Loop *L = LI.getLoopFor(R.getEntry());
2253 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2254}
2255
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002256static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2257 ScopDetection &SD) {
2258
2259 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2260
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002261 unsigned MinLD = INT_MAX, MaxLD = 0;
2262 for (BasicBlock *BB : R.blocks()) {
2263 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002264 if (!R.contains(L))
2265 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002266 if (BoxedLoops && BoxedLoops->count(L))
2267 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002268 unsigned LD = L->getLoopDepth();
2269 MinLD = std::min(MinLD, LD);
2270 MaxLD = std::max(MaxLD, LD);
2271 }
2272 }
2273
2274 // Handle the case that there is no loop in the SCoP first.
2275 if (MaxLD == 0)
2276 return 1;
2277
2278 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2279 assert(MaxLD >= MinLD &&
2280 "Maximal loop depth was smaller than mininaml loop depth?");
2281 return MaxLD - MinLD + 1;
2282}
2283
Michael Kruse9d080092015-09-11 21:41:48 +00002284Scop::Scop(Region &R, AccFuncMapType &AccFuncMap,
2285 ScalarEvolution &ScalarEvolution, DominatorTree &DT,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002286 isl_ctx *Context, unsigned MaxLoopDepth)
Michael Kruse9d080092015-09-11 21:41:48 +00002287 : DT(DT), SE(&ScalarEvolution), R(R), AccFuncMap(AccFuncMap),
2288 IsOptimized(false), HasSingleExitEdge(R.getExitingBlock()),
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002289 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Affinator(this),
2290 BoundaryContext(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002291
Michael Kruse9d080092015-09-11 21:41:48 +00002292void Scop::init(LoopInfo &LI, ScopDetection &SD, AliasAnalysis &AA) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002293 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00002294
Johannes Doerfert96425c22015-08-30 21:13:53 +00002295 buildDomains(&R, LI, SD, DT);
2296
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002297 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
Tobias Grosser75805372011-04-29 06:27:02 +00002298
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002299 Loop *L = getLoopSurroundingRegion(R, LI);
2300 LoopSchedules[L];
Michael Kruse9d080092015-09-11 21:41:48 +00002301 buildSchedule(&R, LI, SD, LoopSchedules);
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002302 updateAccessDimensionality();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002303 Schedule = LoopSchedules[L].first;
Tobias Grosser75805372011-04-29 06:27:02 +00002304
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002305 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002306 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002307 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002308 buildBoundaryContext();
2309 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002310 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002311
2312 hoistInvariantLoads();
2313 simplifySCoP();
Tobias Grosser75805372011-04-29 06:27:02 +00002314}
2315
2316Scop::~Scop() {
2317 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002318 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002319 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002320 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002321
Johannes Doerfert96425c22015-08-30 21:13:53 +00002322 for (auto It : DomainMap)
2323 isl_set_free(It.second);
2324
Johannes Doerfertb164c792014-09-18 11:17:17 +00002325 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002326 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002327 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002328 isl_pw_multi_aff_free(MMA.first);
2329 isl_pw_multi_aff_free(MMA.second);
2330 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002331 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002332 isl_pw_multi_aff_free(MMA.first);
2333 isl_pw_multi_aff_free(MMA.second);
2334 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002335 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002336
2337 for (const auto &IA : InvariantAccesses)
2338 isl_set_free(IA.second);
Tobias Grosser75805372011-04-29 06:27:02 +00002339}
2340
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002341void Scop::updateAccessDimensionality() {
2342 for (auto &Stmt : *this)
2343 for (auto &Access : Stmt)
2344 Access->updateDimensionality();
2345}
2346
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002347void Scop::simplifySCoP() {
2348
2349 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2350 ScopStmt &Stmt = *StmtIt;
2351
2352 if (!StmtIt->isEmpty()) {
2353 StmtIt++;
2354 continue;
2355 }
2356
2357 if (Stmt.isRegionStmt())
2358 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2359 StmtMap.erase(BB);
2360 else
2361 StmtMap.erase(Stmt.getBasicBlock());
2362
2363 StmtIt = Stmts.erase(StmtIt);
2364 }
2365}
2366
2367void Scop::hoistInvariantLoads() {
2368 isl_union_map *Writes = getWrites();
2369 for (ScopStmt &Stmt : *this) {
2370
2371 // TODO: Loads that are not loop carried, hence are in a statement with
2372 // zero iterators, are by construction invariant, though we
2373 // currently "hoist" them anyway.
2374
2375 isl_set *Domain = Stmt.getDomain();
2376 MemoryAccessList InvMAs;
2377
2378 for (MemoryAccess *MA : Stmt) {
2379 if (MA->isImplicit() || MA->isWrite() || !MA->isAffine())
2380 continue;
2381
2382 isl_map *AccessRelation = MA->getAccessRelation();
2383 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
2384 Stmt.getNumIterators())) {
2385 isl_map_free(AccessRelation);
2386 continue;
2387 }
2388
2389 AccessRelation =
2390 isl_map_intersect_domain(AccessRelation, isl_set_copy(Domain));
2391 isl_set *AccessRange = isl_map_range(AccessRelation);
2392
2393 isl_union_map *Written = isl_union_map_intersect_range(
2394 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
2395 bool IsWritten = !isl_union_map_is_empty(Written);
2396 isl_union_map_free(Written);
2397
2398 if (IsWritten)
2399 continue;
2400
2401 InvMAs.push_front(MA);
2402 }
2403
2404 // We inserted invariant accesses always in the front but need them to be
2405 // sorted in a "natural order". The statements are already sorted in reverse
2406 // post order and that suffices for the accesses too. The reason we require
2407 // an order in the first place is the dependences between invariant loads
2408 // that can be caused by indirect loads.
2409 InvMAs.reverse();
2410
2411 // Transfer the memory access from the statement to the SCoP.
2412 Stmt.hoistMemoryAccesses(InvMAs, InvariantAccesses);
2413
2414 isl_set_free(Domain);
2415 }
2416 isl_union_map_free(Writes);
2417
2418 if (!InvariantAccesses.empty())
2419 IsOptimized = true;
2420}
2421
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002422const ScopArrayInfo *
2423Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Michael Kruse28468772015-09-14 15:45:33 +00002424 ArrayRef<const SCEV *> Sizes, bool IsPHI) {
Tobias Grosser92245222015-07-28 14:53:44 +00002425 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002426 if (!SAI) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002427 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, IsPHI,
2428 this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002429 } else {
2430 if (Sizes.size() > SAI->getNumberOfDimensions())
2431 SAI->updateSizes(Sizes);
2432 }
Tobias Grosserab671442015-05-23 05:58:27 +00002433 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002434}
2435
Tobias Grosser92245222015-07-28 14:53:44 +00002436const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, bool IsPHI) {
2437 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002438 assert(SAI && "No ScopArrayInfo available for this base pointer");
2439 return SAI;
2440}
2441
Tobias Grosser74394f02013-01-14 22:40:23 +00002442std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002443std::string Scop::getAssumedContextStr() const {
2444 return stringFromIslObj(AssumedContext);
2445}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002446std::string Scop::getBoundaryContextStr() const {
2447 return stringFromIslObj(BoundaryContext);
2448}
Tobias Grosser75805372011-04-29 06:27:02 +00002449
2450std::string Scop::getNameStr() const {
2451 std::string ExitName, EntryName;
2452 raw_string_ostream ExitStr(ExitName);
2453 raw_string_ostream EntryStr(EntryName);
2454
Tobias Grosserf240b482014-01-09 10:42:15 +00002455 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002456 EntryStr.str();
2457
2458 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00002459 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002460 ExitStr.str();
2461 } else
2462 ExitName = "FunctionExit";
2463
2464 return EntryName + "---" + ExitName;
2465}
2466
Tobias Grosser74394f02013-01-14 22:40:23 +00002467__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00002468__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002469 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00002470}
2471
Tobias Grossere86109f2013-10-29 21:05:49 +00002472__isl_give isl_set *Scop::getAssumedContext() const {
2473 return isl_set_copy(AssumedContext);
2474}
2475
Johannes Doerfert43788c52015-08-20 05:58:56 +00002476__isl_give isl_set *Scop::getRuntimeCheckContext() const {
2477 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002478 RuntimeCheckContext =
2479 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
2480 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002481 return RuntimeCheckContext;
2482}
2483
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002484bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002485 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002486 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002487 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
2488 isl_set_free(RuntimeCheckContext);
2489 return IsFeasible;
2490}
2491
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002492void Scop::addAssumption(__isl_take isl_set *Set) {
2493 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00002494 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002495}
2496
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002497__isl_give isl_set *Scop::getBoundaryContext() const {
2498 return isl_set_copy(BoundaryContext);
2499}
2500
Tobias Grosser75805372011-04-29 06:27:02 +00002501void Scop::printContext(raw_ostream &OS) const {
2502 OS << "Context:\n";
2503
2504 if (!Context) {
2505 OS.indent(4) << "n/a\n\n";
2506 return;
2507 }
2508
2509 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00002510
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002511 OS.indent(4) << "Assumed Context:\n";
2512 if (!AssumedContext) {
2513 OS.indent(4) << "n/a\n\n";
2514 return;
2515 }
2516
2517 OS.indent(4) << getAssumedContextStr() << "\n";
2518
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002519 OS.indent(4) << "Boundary Context:\n";
2520 if (!BoundaryContext) {
2521 OS.indent(4) << "n/a\n\n";
2522 return;
2523 }
2524
2525 OS.indent(4) << getBoundaryContextStr() << "\n";
2526
Tobias Grosser083d3d32014-06-28 08:59:45 +00002527 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00002528 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00002529 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
2530 }
Tobias Grosser75805372011-04-29 06:27:02 +00002531}
2532
Johannes Doerfertb164c792014-09-18 11:17:17 +00002533void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002534 int noOfGroups = 0;
2535 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002536 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002537 noOfGroups += 1;
2538 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002539 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002540 }
2541
Tobias Grosserbb853c22015-07-25 12:31:03 +00002542 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00002543 if (MinMaxAliasGroups.empty()) {
2544 OS.indent(8) << "n/a\n";
2545 return;
2546 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002547
Tobias Grosserbb853c22015-07-25 12:31:03 +00002548 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002549
2550 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002551 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002552 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002553 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002554 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2555 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002556 }
2557 OS << " ]]\n";
2558 }
2559
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002560 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002561 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00002562 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002563 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002564 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2565 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002566 }
2567 OS << " ]]\n";
2568 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002569 }
2570}
2571
Tobias Grosser75805372011-04-29 06:27:02 +00002572void Scop::printStatements(raw_ostream &OS) const {
2573 OS << "Statements {\n";
2574
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002575 for (const ScopStmt &Stmt : *this)
2576 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00002577
2578 OS.indent(4) << "}\n";
2579}
2580
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002581void Scop::printArrayInfo(raw_ostream &OS) const {
2582 OS << "Arrays {\n";
2583
Tobias Grosserab671442015-05-23 05:58:27 +00002584 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002585 Array.second->print(OS);
2586
2587 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002588
2589 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
2590
2591 for (auto &Array : arrays())
2592 Array.second->print(OS, /* SizeAsPwAff */ true);
2593
2594 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002595}
2596
Tobias Grosser75805372011-04-29 06:27:02 +00002597void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00002598 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
2599 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00002600 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00002601 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002602 OS.indent(4) << "Invariant Accesses: {\n";
2603 for (const auto &IA : InvariantAccesses) {
2604 IA.first->print(OS);
2605 OS.indent(12) << "Execution Context: " << IA.second << "\n";
2606 }
2607 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00002608 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002609 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002610 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00002611 printStatements(OS.indent(4));
2612}
2613
2614void Scop::dump() const { print(dbgs()); }
2615
Tobias Grosser9a38ab82011-11-08 15:41:03 +00002616isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00002617
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002618__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
2619 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00002620}
2621
Tobias Grosser808cd692015-07-14 09:33:13 +00002622__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002623 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002624
Tobias Grosser808cd692015-07-14 09:33:13 +00002625 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002626 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002627
2628 return Domain;
2629}
2630
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002631__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002632 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002633
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002634 for (ScopStmt &Stmt : *this) {
2635 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002636 if (!MA->isMustWrite())
2637 continue;
2638
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002639 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002640 isl_map *AccessDomain = MA->getAccessRelation();
2641 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2642 Write = isl_union_map_add_map(Write, AccessDomain);
2643 }
2644 }
2645 return isl_union_map_coalesce(Write);
2646}
2647
2648__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002649 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002650
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002651 for (ScopStmt &Stmt : *this) {
2652 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002653 if (!MA->isMayWrite())
2654 continue;
2655
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002656 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002657 isl_map *AccessDomain = MA->getAccessRelation();
2658 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2659 Write = isl_union_map_add_map(Write, AccessDomain);
2660 }
2661 }
2662 return isl_union_map_coalesce(Write);
2663}
2664
Tobias Grosser37eb4222014-02-20 21:43:54 +00002665__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002666 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002667
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002668 for (ScopStmt &Stmt : *this) {
2669 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002670 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002671 continue;
2672
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002673 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002674 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002675 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2676 Write = isl_union_map_add_map(Write, AccessDomain);
2677 }
2678 }
2679 return isl_union_map_coalesce(Write);
2680}
2681
2682__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002683 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002684
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002685 for (ScopStmt &Stmt : *this) {
2686 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002687 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002688 continue;
2689
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002690 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002691 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002692
2693 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2694 Read = isl_union_map_add_map(Read, AccessDomain);
2695 }
2696 }
2697 return isl_union_map_coalesce(Read);
2698}
2699
Tobias Grosser808cd692015-07-14 09:33:13 +00002700__isl_give isl_union_map *Scop::getSchedule() const {
2701 auto Tree = getScheduleTree();
2702 auto S = isl_schedule_get_map(Tree);
2703 isl_schedule_free(Tree);
2704 return S;
2705}
Tobias Grosser37eb4222014-02-20 21:43:54 +00002706
Tobias Grosser808cd692015-07-14 09:33:13 +00002707__isl_give isl_schedule *Scop::getScheduleTree() const {
2708 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
2709 getDomains());
2710}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002711
Tobias Grosser808cd692015-07-14 09:33:13 +00002712void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
2713 auto *S = isl_schedule_from_domain(getDomains());
2714 S = isl_schedule_insert_partial_schedule(
2715 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
2716 isl_schedule_free(Schedule);
2717 Schedule = S;
2718}
2719
2720void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
2721 isl_schedule_free(Schedule);
2722 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00002723}
2724
2725bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
2726 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002727 for (ScopStmt &Stmt : *this) {
2728 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002729 isl_union_set *NewStmtDomain = isl_union_set_intersect(
2730 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
2731
2732 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
2733 isl_union_set_free(StmtDomain);
2734 isl_union_set_free(NewStmtDomain);
2735 continue;
2736 }
2737
2738 Changed = true;
2739
2740 isl_union_set_free(StmtDomain);
2741 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
2742
2743 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002744 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002745 isl_union_set_free(NewStmtDomain);
2746 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002747 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002748 }
2749 isl_union_set_free(Domain);
2750 return Changed;
2751}
2752
Tobias Grosser75805372011-04-29 06:27:02 +00002753ScalarEvolution *Scop::getSE() const { return SE; }
2754
Michael Kruse9d080092015-09-11 21:41:48 +00002755bool Scop::isTrivialBB(BasicBlock *BB) {
2756 if (getAccessFunctions(BB) && !isErrorBlock(*BB))
Tobias Grosser75805372011-04-29 06:27:02 +00002757 return false;
2758
2759 return true;
2760}
2761
Tobias Grosser808cd692015-07-14 09:33:13 +00002762struct MapToDimensionDataTy {
2763 int N;
2764 isl_union_pw_multi_aff *Res;
2765};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002766
Tobias Grosser808cd692015-07-14 09:33:13 +00002767// @brief Create a function that maps the elements of 'Set' to its N-th
2768// dimension.
2769//
2770// The result is added to 'User->Res'.
2771//
2772// @param Set The input set.
2773// @param N The dimension to map to.
2774//
2775// @returns Zero if no error occurred, non-zero otherwise.
2776static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
2777 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
2778 int Dim;
2779 isl_space *Space;
2780 isl_pw_multi_aff *PMA;
2781
2782 Dim = isl_set_dim(Set, isl_dim_set);
2783 Space = isl_set_get_space(Set);
2784 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
2785 Dim - Data->N);
2786 if (Data->N > 1)
2787 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
2788 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
2789
2790 isl_set_free(Set);
2791
2792 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002793}
2794
Tobias Grosser808cd692015-07-14 09:33:13 +00002795// @brief Create a function that maps the elements of Domain to their Nth
2796// dimension.
2797//
2798// @param Domain The set of elements to map.
2799// @param N The dimension to map to.
2800static __isl_give isl_multi_union_pw_aff *
2801mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002802 if (N <= 0 || isl_union_set_is_empty(Domain)) {
2803 isl_union_set_free(Domain);
2804 return nullptr;
2805 }
2806
Tobias Grosser808cd692015-07-14 09:33:13 +00002807 struct MapToDimensionDataTy Data;
2808 isl_space *Space;
2809
2810 Space = isl_union_set_get_space(Domain);
2811 Data.N = N;
2812 Data.Res = isl_union_pw_multi_aff_empty(Space);
2813 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
2814 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
2815
2816 isl_union_set_free(Domain);
2817 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
2818}
2819
Michael Kruse9d080092015-09-11 21:41:48 +00002820ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00002821 ScopStmt *Stmt;
2822 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00002823 Stmts.emplace_back(*this, *BB);
Tobias Grosser808cd692015-07-14 09:33:13 +00002824 Stmt = &Stmts.back();
2825 StmtMap[BB] = Stmt;
2826 } else {
2827 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00002828 Stmts.emplace_back(*this, *R);
Tobias Grosser808cd692015-07-14 09:33:13 +00002829 Stmt = &Stmts.back();
2830 for (BasicBlock *BB : R->blocks())
2831 StmtMap[BB] = Stmt;
2832 }
2833 return Stmt;
2834}
2835
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002836void Scop::buildSchedule(
Michael Kruse9d080092015-09-11 21:41:48 +00002837 Region *R, LoopInfo &LI, ScopDetection &SD,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002838 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00002839
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002840 if (SD.isNonAffineSubRegion(R, &getRegion())) {
2841 auto *Stmt = addScopStmt(nullptr, R);
2842 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
2843 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Johannes Doerfertc6987c12015-09-26 13:41:43 +00002844 Loop *L = getLoopSurroundingRegion(*R, LI);
2845 auto &LSchedulePair = LoopSchedules[L];
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002846 LSchedulePair.first = StmtSchedule;
2847 return;
2848 }
2849
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002850 ReversePostOrderTraversal<Region *> RTraversal(R);
2851 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00002852
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002853 if (RN->isSubRegion()) {
2854 Region *SubRegion = RN->getNodeAs<Region>();
2855 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Michael Kruse9d080092015-09-11 21:41:48 +00002856 buildSchedule(SubRegion, LI, SD, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002857 continue;
2858 }
Tobias Grosser75805372011-04-29 06:27:02 +00002859 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002860
2861 Loop *L = getRegionNodeLoop(RN, LI);
2862 int LD = getRelativeLoopDepth(L);
2863 auto &LSchedulePair = LoopSchedules[L];
2864 LSchedulePair.second += getNumBlocksInRegionNode(RN);
2865
2866 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Michael Kruse9d080092015-09-11 21:41:48 +00002867 if (RN->isSubRegion() || !isTrivialBB(BB)) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002868
2869 ScopStmt *Stmt;
2870 if (RN->isSubRegion())
Michael Kruse9d080092015-09-11 21:41:48 +00002871 Stmt = addScopStmt(nullptr, RN->getNodeAs<Region>());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002872 else
Michael Kruse9d080092015-09-11 21:41:48 +00002873 Stmt = addScopStmt(BB, nullptr);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002874
2875 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
2876 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
2877 LSchedulePair.first =
2878 combineInSequence(LSchedulePair.first, StmtSchedule);
2879 }
2880
2881 unsigned NumVisited = LSchedulePair.second;
2882 while (L && NumVisited == L->getNumBlocks()) {
2883 auto *LDomain = isl_schedule_get_domain(LSchedulePair.first);
2884 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
2885 LSchedulePair.first =
2886 isl_schedule_insert_partial_schedule(LSchedulePair.first, MUPA);
2887
2888 auto *PL = L->getParentLoop();
2889 assert(LoopSchedules.count(PL));
2890 auto &PSchedulePair = LoopSchedules[PL];
2891 PSchedulePair.first =
2892 combineInSequence(PSchedulePair.first, LSchedulePair.first);
2893 PSchedulePair.second += NumVisited;
2894
2895 L = PL;
2896 NumVisited = PSchedulePair.second;
2897 }
Tobias Grosser808cd692015-07-14 09:33:13 +00002898 }
Tobias Grosser75805372011-04-29 06:27:02 +00002899}
2900
Johannes Doerfert7c494212014-10-31 23:13:39 +00002901ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00002902 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00002903 if (StmtMapIt == StmtMap.end())
2904 return nullptr;
2905 return StmtMapIt->second;
2906}
2907
Johannes Doerfert96425c22015-08-30 21:13:53 +00002908int Scop::getRelativeLoopDepth(const Loop *L) const {
2909 Loop *OuterLoop =
2910 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
2911 if (!OuterLoop)
2912 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00002913 return L->getLoopDepth() - OuterLoop->getLoopDepth();
2914}
2915
Michael Krused868b5d2015-09-10 15:25:24 +00002916void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00002917 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002918
2919 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
2920 // true, are not modeled as ordinary PHI nodes as they are not part of the
2921 // region. However, we model the operands in the predecessor blocks that are
2922 // part of the region as regular scalar accesses.
2923
2924 // If we can synthesize a PHI we can skip it, however only if it is in
2925 // the region. If it is not it can only be in the exit block of the region.
2926 // In this case we model the operands but not the PHI itself.
2927 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
2928 return;
2929
2930 // PHI nodes are modeled as if they had been demoted prior to the SCoP
2931 // detection. Hence, the PHI is a load of a new memory location in which the
2932 // incoming value was written at the end of the incoming basic block.
2933 bool OnlyNonAffineSubRegionOperands = true;
2934 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
2935 Value *Op = PHI->getIncomingValue(u);
2936 BasicBlock *OpBB = PHI->getIncomingBlock(u);
2937
2938 // Do not build scalar dependences inside a non-affine subregion.
2939 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
2940 continue;
2941
2942 OnlyNonAffineSubRegionOperands = false;
2943
2944 if (!R.contains(OpBB))
2945 continue;
2946
2947 Instruction *OpI = dyn_cast<Instruction>(Op);
2948 if (OpI) {
2949 BasicBlock *OpIBB = OpI->getParent();
2950 // As we pretend there is a use (or more precise a write) of OpI in OpBB
2951 // we have to insert a scalar dependence from the definition of OpI to
2952 // OpBB if the definition is not in OpBB.
2953 if (OpIBB != OpBB) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002954 addScalarReadAccess(OpI, PHI, OpBB);
2955 addScalarWriteAccess(OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00002956 }
Tobias Grosserda95a4a2015-09-24 20:59:59 +00002957 } else if (ModelReadOnlyScalars && !isa<Constant>(Op)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002958 addScalarReadAccess(Op, PHI, OpBB);
Michael Kruse7bf39442015-09-10 12:46:52 +00002959 }
2960
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002961 addPHIWriteAccess(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00002962 }
2963
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002964 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
2965 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00002966 }
2967}
2968
Michael Krused868b5d2015-09-10 15:25:24 +00002969bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
2970 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002971 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
2972 if (isIgnoredIntrinsic(Inst))
2973 return false;
2974
2975 bool AnyCrossStmtUse = false;
2976 BasicBlock *ParentBB = Inst->getParent();
2977
2978 for (User *U : Inst->users()) {
2979 Instruction *UI = dyn_cast<Instruction>(U);
2980
2981 // Ignore the strange user
2982 if (UI == 0)
2983 continue;
2984
2985 BasicBlock *UseParent = UI->getParent();
2986
2987 // Ignore the users in the same BB (statement)
2988 if (UseParent == ParentBB)
2989 continue;
2990
2991 // Do not build scalar dependences inside a non-affine subregion.
2992 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
2993 continue;
2994
2995 // Check whether or not the use is in the SCoP.
2996 if (!R->contains(UseParent)) {
2997 AnyCrossStmtUse = true;
2998 continue;
2999 }
3000
3001 // If the instruction can be synthesized and the user is in the region
3002 // we do not need to add scalar dependences.
3003 if (canSynthesizeInst)
3004 continue;
3005
3006 // No need to translate these scalar dependences into polyhedral form,
3007 // because synthesizable scalars can be generated by the code generator.
3008 if (canSynthesize(UI, LI, SE, R))
3009 continue;
3010
3011 // Skip PHI nodes in the region as they handle their operands on their own.
3012 if (isa<PHINode>(UI))
3013 continue;
3014
3015 // Now U is used in another statement.
3016 AnyCrossStmtUse = true;
3017
3018 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00003019 // Use the def instruction as base address of the MemoryAccess, so that it
3020 // will become the name of the scalar access in the polyhedral form.
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003021 addScalarReadAccess(Inst, UI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003022 }
3023
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003024 if (ModelReadOnlyScalars && !isa<PHINode>(Inst)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003025 for (Value *Op : Inst->operands()) {
3026 if (canSynthesize(Op, LI, SE, R))
3027 continue;
3028
3029 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
3030 if (R->contains(OpInst))
3031 continue;
3032
3033 if (isa<Constant>(Op))
3034 continue;
3035
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003036 addScalarReadAccess(Op, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003037 }
3038 }
3039
3040 return AnyCrossStmtUse;
3041}
3042
3043extern MapInsnToMemAcc InsnToMemAcc;
3044
Michael Krusee2bccbb2015-09-18 19:59:43 +00003045void ScopInfo::buildMemoryAccess(
3046 Instruction *Inst, Loop *L, Region *R,
3047 const ScopDetection::BoxedLoopsSetTy *BoxedLoops) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003048 unsigned Size;
3049 Type *SizeType;
3050 Value *Val;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003051 enum MemoryAccess::AccessType Type;
Michael Kruse7bf39442015-09-10 12:46:52 +00003052
3053 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
3054 SizeType = Load->getType();
3055 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003056 Type = MemoryAccess::READ;
Michael Kruse7bf39442015-09-10 12:46:52 +00003057 Val = Load;
3058 } else {
3059 StoreInst *Store = cast<StoreInst>(Inst);
3060 SizeType = Store->getValueOperand()->getType();
3061 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003062 Type = MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003063 Val = Store->getValueOperand();
3064 }
3065
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003066 auto Address = getPointerOperand(*Inst);
3067
3068 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003069 const SCEVUnknown *BasePointer =
3070 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3071
3072 assert(BasePointer && "Could not find base pointer");
3073 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
3074
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003075 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3076 auto NewAddress = Address;
3077 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3078 auto Src = BitCast->getOperand(0);
3079 auto SrcTy = Src->getType();
3080 auto DstTy = BitCast->getType();
3081 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3082 NewAddress = Src;
3083 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003084
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003085 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3086 std::vector<const SCEV *> Subscripts;
3087 std::vector<int> Sizes;
3088 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3089 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003090
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003091 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003092
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003093 bool AllAffineSubcripts = true;
3094 for (auto Subscript : Subscripts)
3095 if (!isAffineExpr(R, Subscript, *SE)) {
3096 AllAffineSubcripts = false;
3097 break;
3098 }
3099
3100 if (AllAffineSubcripts && Sizes.size() > 0) {
3101 for (auto V : Sizes)
3102 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3103 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003104 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003105 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003106
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003107 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3108 Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00003109 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003110 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003111 }
3112 }
3113
Michael Kruse7bf39442015-09-10 12:46:52 +00003114 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003115 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003116 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3117 AccItr->second.DelinearizedSubscripts,
3118 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003119 return;
3120 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003121
3122 // Check if the access depends on a loop contained in a non-affine subregion.
3123 bool isVariantInNonAffineLoop = false;
3124 if (BoxedLoops) {
3125 SetVector<const Loop *> Loops;
3126 findLoops(AccessFunction, Loops);
3127 for (const Loop *L : Loops)
3128 if (BoxedLoops->count(L))
3129 isVariantInNonAffineLoop = true;
3130 }
3131
3132 bool IsAffine = !isVariantInNonAffineLoop &&
3133 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue());
3134
Michael Krusecaac2b62015-09-26 15:51:44 +00003135 // FIXME: Size of the number of bytes of an array element, not the number of
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003136 // elements as probably intended here.
Tobias Grossera43b6e92015-09-27 17:54:50 +00003137 const SCEV *SizeSCEV =
3138 SE->getConstant(TD->getIntPtrType(Inst->getContext()), Size);
Michael Kruse7bf39442015-09-10 12:46:52 +00003139
Michael Krusee2bccbb2015-09-18 19:59:43 +00003140 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3141 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003142
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003143 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, IsAffine,
3144 ArrayRef<const SCEV *>(AccessFunction),
3145 ArrayRef<const SCEV *>(SizeSCEV), Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003146}
3147
Michael Krused868b5d2015-09-10 15:25:24 +00003148void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003149
3150 if (SD->isNonAffineSubRegion(&SR, &R)) {
3151 for (BasicBlock *BB : SR.blocks())
3152 buildAccessFunctions(R, *BB, &SR);
3153 return;
3154 }
3155
3156 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3157 if (I->isSubRegion())
3158 buildAccessFunctions(R, *I->getNodeAs<Region>());
3159 else
3160 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
3161}
3162
Michael Krused868b5d2015-09-10 15:25:24 +00003163void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
3164 Region *NonAffineSubRegion,
3165 bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003166 Loop *L = LI->getLoopFor(&BB);
3167
3168 // The set of loops contained in non-affine subregions that are part of R.
3169 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3170
3171 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
3172 Instruction *Inst = I;
3173
3174 PHINode *PHI = dyn_cast<PHINode>(Inst);
3175 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003176 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003177
3178 // For the exit block we stop modeling after the last PHI node.
3179 if (!PHI && IsExitBlock)
3180 break;
3181
3182 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
Michael Krusee2bccbb2015-09-18 19:59:43 +00003183 buildMemoryAccess(Inst, L, &R, BoxedLoops);
Michael Kruse7bf39442015-09-10 12:46:52 +00003184
3185 if (isIgnoredIntrinsic(Inst))
3186 continue;
3187
3188 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00003189 if (!isa<StoreInst>(Inst))
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003190 addScalarWriteAccess(Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003191 }
3192 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003193}
Michael Kruse7bf39442015-09-10 12:46:52 +00003194
Michael Kruse2d0ece92015-09-24 11:41:21 +00003195void ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3196 MemoryAccess::AccessType Type,
3197 Value *BaseAddress, unsigned ElemBytes,
3198 bool Affine, Value *AccessValue,
3199 ArrayRef<const SCEV *> Subscripts,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003200 ArrayRef<const SCEV *> Sizes,
3201 MemoryAccess::AccessOrigin Origin) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00003202 AccFuncSetType &AccList = AccFuncMap[BB];
3203 size_t Identifier = AccList.size();
Michael Kruse7bf39442015-09-10 12:46:52 +00003204
Michael Krusee2bccbb2015-09-18 19:59:43 +00003205 Value *BaseAddr = BaseAddress;
3206 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3207
3208 std::string IdName = "__polly_array_ref_" + std::to_string(Identifier);
3209 isl_id *Id = isl_id_alloc(ctx, IdName.c_str(), nullptr);
3210
Michael Kruse2d0ece92015-09-24 11:41:21 +00003211 AccList.emplace_back(Inst, Id, Type, BaseAddress, ElemBytes, Affine,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003212 Subscripts, Sizes, AccessValue, Origin, BaseName);
Michael Kruse7bf39442015-09-10 12:46:52 +00003213}
3214
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003215void ScopInfo::addExplicitAccess(
3216 Instruction *MemAccInst, MemoryAccess::AccessType Type, Value *BaseAddress,
3217 unsigned ElemBytes, bool IsAffine, ArrayRef<const SCEV *> Subscripts,
3218 ArrayRef<const SCEV *> Sizes, Value *AccessValue) {
3219 assert(isa<LoadInst>(MemAccInst) || isa<StoreInst>(MemAccInst));
3220 assert(isa<LoadInst>(MemAccInst) == (Type == MemoryAccess::READ));
3221 addMemoryAccess(MemAccInst->getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003222 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
3223 MemoryAccess::EXPLICIT);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003224}
3225void ScopInfo::addScalarWriteAccess(Instruction *Value) {
3226 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
3227 true, Value, ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003228 ArrayRef<const SCEV *>(), MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003229}
3230void ScopInfo::addScalarReadAccess(Value *Value, Instruction *User) {
3231 assert(!isa<PHINode>(User));
3232 addMemoryAccess(User->getParent(), User, MemoryAccess::READ, Value, 1, true,
3233 Value, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003234 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003235}
3236void ScopInfo::addScalarReadAccess(Value *Value, PHINode *User,
3237 BasicBlock *UserBB) {
3238 addMemoryAccess(UserBB, User, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003239 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3240 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003241}
3242void ScopInfo::addPHIWriteAccess(PHINode *PHI, BasicBlock *IncomingBlock,
3243 Value *IncomingValue, bool IsExitBlock) {
3244 addMemoryAccess(IncomingBlock, IncomingBlock->getTerminator(),
3245 MemoryAccess::MUST_WRITE, PHI, 1, true, IncomingValue,
3246 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003247 IsExitBlock ? MemoryAccess::SCALAR : MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003248}
3249void ScopInfo::addPHIReadAccess(PHINode *PHI) {
3250 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003251 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3252 MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003253}
3254
Michael Kruse76e924d2015-09-30 09:16:07 +00003255void ScopInfo::buildScop(Region &R, DominatorTree &DT) {
Michael Kruse9d080092015-09-11 21:41:48 +00003256 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Michael Kruse76e924d2015-09-30 09:16:07 +00003257 scop = new Scop(R, AccFuncMap, *SE, DT, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00003258
3259 buildAccessFunctions(R, R);
3260
3261 // In case the region does not have an exiting block we will later (during
3262 // code generation) split the exit block. This will move potential PHI nodes
3263 // from the current exit block into the new region exiting block. Hence, PHI
3264 // nodes that are at this point not part of the region will be.
3265 // To handle these PHI nodes later we will now model their operands as scalar
3266 // accesses. Note that we do not model anything in the exit block if we have
3267 // an exiting block in the region, as there will not be any splitting later.
3268 if (!R.getExitingBlock())
3269 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
3270
Michael Kruse76e924d2015-09-30 09:16:07 +00003271 scop->init(*LI, *SD, *AA);
Michael Kruse7bf39442015-09-10 12:46:52 +00003272}
3273
Michael Krused868b5d2015-09-10 15:25:24 +00003274void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00003275 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00003276 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00003277 return;
3278 }
3279
Michael Kruse9d080092015-09-11 21:41:48 +00003280 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00003281}
3282
Michael Krused868b5d2015-09-10 15:25:24 +00003283void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00003284 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00003285 if (scop) {
3286 delete scop;
3287 scop = 0;
3288 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003289}
3290
3291//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00003292ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00003293 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00003294 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00003295}
3296
3297ScopInfo::~ScopInfo() {
3298 clear();
3299 isl_ctx_free(ctx);
3300}
3301
Tobias Grosser75805372011-04-29 06:27:02 +00003302void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Michael Krused868b5d2015-09-10 15:25:24 +00003303 AU.addRequiredID(IndependentBlocksID);
Chandler Carruthf5579872015-01-17 14:16:56 +00003304 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00003305 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00003306 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00003307 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
3308 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003309 AU.addRequired<AAResultsWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00003310 AU.setPreservesAll();
3311}
3312
3313bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00003314 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00003315
Michael Krused868b5d2015-09-10 15:25:24 +00003316 if (!SD->isMaxRegionInScop(*R))
3317 return false;
3318
3319 Function *F = R->getEntry()->getParent();
3320 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3321 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3322 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3323 TD = &F->getParent()->getDataLayout();
3324 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Krused868b5d2015-09-10 15:25:24 +00003325
Michael Kruse76e924d2015-09-30 09:16:07 +00003326 buildScop(*R, DT);
Tobias Grosser75805372011-04-29 06:27:02 +00003327
Tobias Grosserd6a50b32015-05-30 06:26:21 +00003328 DEBUG(scop->print(dbgs()));
3329
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003330 if (!scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003331 delete scop;
3332 scop = nullptr;
3333 return false;
3334 }
3335
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003336 // Statistics.
3337 ++ScopFound;
3338 if (scop->getMaxLoopDepth() > 0)
3339 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00003340 return false;
3341}
3342
3343char ScopInfo::ID = 0;
3344
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003345Pass *polly::createScopInfoPass() { return new ScopInfo(); }
3346
Tobias Grosser73600b82011-10-08 00:30:40 +00003347INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
3348 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003349 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003350INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00003351INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00003352INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00003353INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003354INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003355INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00003356INITIALIZE_PASS_END(ScopInfo, "polly-scops",
3357 "Polly - Create polyhedral description of Scops", false,
3358 false)