blob: 4920b1181873c692e04648e6f907437db5aefc8e [file] [log] [blame]
Johannes Doerfert58a7c752015-09-28 09:48:53 +00001//===--------- ScopInfo.cpp - Create Scops from LLVM IR ------------------===//
Tobias Grosser75805372011-04-29 06:27:02 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Create a polyhedral description for a static control flow region.
11//
12// The pass creates a polyhedral description of the Scops detected by the Scop
13// detection derived from their LLVM-IR code.
14//
Tobias Grossera5605d32014-10-29 19:58:28 +000015// This representation is shared among several tools in the polyhedral
Tobias Grosser75805372011-04-29 06:27:02 +000016// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
Tobias Grosser75805372011-04-29 06:27:02 +000020#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000021#include "polly/Options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000022#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000023#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000024#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000025#include "polly/Support/ScopHelper.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000026#include "llvm/ADT/MapVector.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000027#include "llvm/ADT/PostOrderIterator.h"
28#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000029#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000030#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000031#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000032#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000033#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000034#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000035#include "llvm/Analysis/RegionIterator.h"
36#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser75805372011-04-29 06:27:02 +000037#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000038#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000039#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000040#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000041#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000042#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000043#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000044#include "isl/schedule.h"
45#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000046#include "isl/set.h"
47#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000048#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000049#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000050#include <sstream>
51#include <string>
52#include <vector>
53
54using namespace llvm;
55using namespace polly;
56
Chandler Carruth95fef942014-04-22 03:30:19 +000057#define DEBUG_TYPE "polly-scops"
58
Tobias Grosser74394f02013-01-14 22:40:23 +000059STATISTIC(ScopFound, "Number of valid Scops");
60STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000061
Michael Kruse7bf39442015-09-10 12:46:52 +000062static cl::opt<bool> ModelReadOnlyScalars(
63 "polly-analyze-read-only-scalars",
64 cl::desc("Model read-only scalar values in the scop description"),
65 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
66
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000067// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000068// operations can overflow easily. Additive reductions and bit operations
69// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000070static cl::opt<bool> DisableMultiplicativeReductions(
71 "polly-disable-multiplicative-reductions",
72 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
73 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000074
Johannes Doerfert9143d672014-09-27 11:02:39 +000075static cl::opt<unsigned> RunTimeChecksMaxParameters(
76 "polly-rtc-max-parameters",
77 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
78 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
79
Tobias Grosser71500722015-03-28 15:11:14 +000080static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
81 "polly-rtc-max-arrays-per-group",
82 cl::desc("The maximal number of arrays to compare in each alias group."),
83 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000084static cl::opt<std::string> UserContextStr(
85 "polly-context", cl::value_desc("isl parameter set"),
86 cl::desc("Provide additional constraints on the context parameters"),
87 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000088
Tobias Grosserd83b8a82015-08-20 19:08:11 +000089static cl::opt<bool> DetectReductions("polly-detect-reductions",
90 cl::desc("Detect and exploit reductions"),
91 cl::Hidden, cl::ZeroOrMore,
92 cl::init(true), cl::cat(PollyCategory));
93
Michael Kruse7bf39442015-09-10 12:46:52 +000094//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +000095
Michael Kruse046dde42015-08-10 13:01:57 +000096// Create a sequence of two schedules. Either argument may be null and is
97// interpreted as the empty schedule. Can also return null if both schedules are
98// empty.
99static __isl_give isl_schedule *
100combineInSequence(__isl_take isl_schedule *Prev,
101 __isl_take isl_schedule *Succ) {
102 if (!Prev)
103 return Succ;
104 if (!Succ)
105 return Prev;
106
107 return isl_schedule_sequence(Prev, Succ);
108}
109
Johannes Doerferte7044942015-02-24 11:58:30 +0000110static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
111 const ConstantRange &Range,
112 int dim,
113 enum isl_dim_type type) {
114 isl_val *V;
115 isl_ctx *ctx = isl_set_get_ctx(S);
116
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000117 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
118 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000119 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000120 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
121
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000122 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000123 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000124 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000125 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000126 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
127
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000128 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000129 return isl_set_union(SLB, SUB);
130 else
131 return isl_set_intersect(SLB, SUB);
132}
133
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000134static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
135 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
136 if (!BasePtrLI)
137 return nullptr;
138
139 if (!S->getRegion().contains(BasePtrLI))
140 return nullptr;
141
142 ScalarEvolution &SE = *S->getSE();
143
144 auto *OriginBaseSCEV =
145 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
146 if (!OriginBaseSCEV)
147 return nullptr;
148
149 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
150 if (!OriginBaseSCEVUnknown)
151 return nullptr;
152
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000153 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
154 ScopArrayInfo::KIND_ARRAY);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000155}
156
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000157ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000158 ArrayRef<const SCEV *> Sizes, enum ARRAYKIND Kind,
159 Scop *S)
160 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000161 std::string BasePtrName =
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000162 getIslCompatibleName("MemRef_", BasePtr, Kind == KIND_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000163 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000164
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000165 updateSizes(Sizes);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000166 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
167 if (BasePtrOriginSAI)
168 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000169}
170
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000171__isl_give isl_space *ScopArrayInfo::getSpace() const {
172 auto Space =
173 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
174 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
175 return Space;
176}
177
Tobias Grosser8286b832015-11-02 11:29:32 +0000178bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000179 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
180 int ExtraDimsNew = NewSizes.size() - SharedDims;
181 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Tobias Grosser8286b832015-11-02 11:29:32 +0000182 for (int i = 0; i < SharedDims; i++)
183 if (NewSizes[i + ExtraDimsNew] != DimensionSizes[i + ExtraDimsOld])
184 return false;
185
186 if (DimensionSizes.size() >= NewSizes.size())
187 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000188
189 DimensionSizes.clear();
190 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
191 NewSizes.end());
192 for (isl_pw_aff *Size : DimensionSizesPw)
193 isl_pw_aff_free(Size);
194 DimensionSizesPw.clear();
195 for (const SCEV *Expr : DimensionSizes) {
196 isl_pw_aff *Size = S.getPwAff(Expr);
197 DimensionSizesPw.push_back(Size);
198 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000199 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000200}
201
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000202ScopArrayInfo::~ScopArrayInfo() {
203 isl_id_free(Id);
204 for (isl_pw_aff *Size : DimensionSizesPw)
205 isl_pw_aff_free(Size);
206}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000207
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000208std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
209
210int ScopArrayInfo::getElemSizeInBytes() const {
211 return ElementType->getPrimitiveSizeInBits() / 8;
212}
213
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000214isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
215
216void ScopArrayInfo::dump() const { print(errs()); }
217
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000218void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000219 OS.indent(8) << *getElementType() << " " << getName();
220 if (getNumberOfDimensions() > 0)
221 OS << "[*]";
Tobias Grosser26253842015-11-10 14:24:21 +0000222 for (unsigned u = 1; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000223 OS << "[";
224
Tobias Grosser26253842015-11-10 14:24:21 +0000225 if (SizeAsPwAff) {
226 auto Size = getDimensionSizePw(u);
227 OS << " " << Size << " ";
228 isl_pw_aff_free(Size);
229 } else {
230 OS << *getDimensionSize(u);
231 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000232
233 OS << "]";
234 }
235
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000236 OS << ";";
237
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000238 if (BasePtrOriginSAI)
239 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
240
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000241 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000242}
243
244const ScopArrayInfo *
245ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
246 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
247 assert(Id && "Output dimension didn't have an ID");
248 return getFromId(Id);
249}
250
251const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
252 void *User = isl_id_get_user(Id);
253 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
254 isl_id_free(Id);
255 return SAI;
256}
257
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000258void MemoryAccess::updateDimensionality() {
259 auto ArraySpace = getScopArrayInfo()->getSpace();
260 auto AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
261
262 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
263 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
264 auto DimsMissing = DimsArray - DimsAccess;
265
266 auto Map = isl_map_from_domain_and_range(isl_set_universe(AccessSpace),
267 isl_set_universe(ArraySpace));
268
269 for (unsigned i = 0; i < DimsMissing; i++)
270 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
271
272 for (unsigned i = DimsMissing; i < DimsArray; i++)
273 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
274
275 AccessRelation = isl_map_apply_range(AccessRelation, Map);
276}
277
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000278const std::string
279MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
280 switch (RT) {
281 case MemoryAccess::RT_NONE:
282 llvm_unreachable("Requested a reduction operator string for a memory "
283 "access which isn't a reduction");
284 case MemoryAccess::RT_ADD:
285 return "+";
286 case MemoryAccess::RT_MUL:
287 return "*";
288 case MemoryAccess::RT_BOR:
289 return "|";
290 case MemoryAccess::RT_BXOR:
291 return "^";
292 case MemoryAccess::RT_BAND:
293 return "&";
294 }
295 llvm_unreachable("Unknown reduction type");
296 return "";
297}
298
Johannes Doerfertf6183392014-07-01 20:52:51 +0000299/// @brief Return the reduction type for a given binary operator
300static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
301 const Instruction *Load) {
302 if (!BinOp)
303 return MemoryAccess::RT_NONE;
304 switch (BinOp->getOpcode()) {
305 case Instruction::FAdd:
306 if (!BinOp->hasUnsafeAlgebra())
307 return MemoryAccess::RT_NONE;
308 // Fall through
309 case Instruction::Add:
310 return MemoryAccess::RT_ADD;
311 case Instruction::Or:
312 return MemoryAccess::RT_BOR;
313 case Instruction::Xor:
314 return MemoryAccess::RT_BXOR;
315 case Instruction::And:
316 return MemoryAccess::RT_BAND;
317 case Instruction::FMul:
318 if (!BinOp->hasUnsafeAlgebra())
319 return MemoryAccess::RT_NONE;
320 // Fall through
321 case Instruction::Mul:
322 if (DisableMultiplicativeReductions)
323 return MemoryAccess::RT_NONE;
324 return MemoryAccess::RT_MUL;
325 default:
326 return MemoryAccess::RT_NONE;
327 }
328}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000329
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000330/// @brief Derive the individual index expressions from a GEP instruction
331///
332/// This function optimistically assumes the GEP references into a fixed size
333/// array. If this is actually true, this function returns a list of array
334/// subscript expressions as SCEV as well as a list of integers describing
335/// the size of the individual array dimensions. Both lists have either equal
336/// length of the size list is one element shorter in case there is no known
337/// size available for the outermost array dimension.
338///
339/// @param GEP The GetElementPtr instruction to analyze.
340///
341/// @return A tuple with the subscript expressions and the dimension sizes.
342static std::tuple<std::vector<const SCEV *>, std::vector<int>>
343getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
344 std::vector<const SCEV *> Subscripts;
345 std::vector<int> Sizes;
346
347 Type *Ty = GEP->getPointerOperandType();
348
349 bool DroppedFirstDim = false;
350
Michael Kruse26ed65e2015-09-24 17:32:49 +0000351 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000352
353 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
354
355 if (i == 1) {
356 if (auto PtrTy = dyn_cast<PointerType>(Ty)) {
357 Ty = PtrTy->getElementType();
358 } else if (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
359 Ty = ArrayTy->getElementType();
360 } else {
361 Subscripts.clear();
362 Sizes.clear();
363 break;
364 }
365 if (auto Const = dyn_cast<SCEVConstant>(Expr))
366 if (Const->getValue()->isZero()) {
367 DroppedFirstDim = true;
368 continue;
369 }
370 Subscripts.push_back(Expr);
371 continue;
372 }
373
374 auto ArrayTy = dyn_cast<ArrayType>(Ty);
375 if (!ArrayTy) {
376 Subscripts.clear();
377 Sizes.clear();
378 break;
379 }
380
381 Subscripts.push_back(Expr);
382 if (!(DroppedFirstDim && i == 2))
383 Sizes.push_back(ArrayTy->getNumElements());
384
385 Ty = ArrayTy->getElementType();
386 }
387
388 return std::make_tuple(Subscripts, Sizes);
389}
390
Tobias Grosser75805372011-04-29 06:27:02 +0000391MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000392 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000393 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000394 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000395}
396
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000397const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
398 isl_id *ArrayId = getArrayId();
399 void *User = isl_id_get_user(ArrayId);
400 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
401 isl_id_free(ArrayId);
402 return SAI;
403}
404
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000405__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000406 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
407}
408
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000409__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
410 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000411 isl_map *Schedule, *ScheduledAccRel;
412 isl_union_set *UDomain;
413
414 UDomain = isl_union_set_from_set(getStatement()->getDomain());
415 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
416 Schedule = isl_map_from_union_map(USchedule);
417 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
418 return isl_pw_multi_aff_from_map(ScheduledAccRel);
419}
420
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000421__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000422 return isl_map_copy(AccessRelation);
423}
424
Johannes Doerferta99130f2014-10-13 12:58:03 +0000425std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000426 return stringFromIslObj(AccessRelation);
427}
428
Johannes Doerferta99130f2014-10-13 12:58:03 +0000429__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000430 return isl_map_get_space(AccessRelation);
431}
432
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000433__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000434 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000435}
436
Tobias Grosser6f730082015-09-05 07:46:47 +0000437std::string MemoryAccess::getNewAccessRelationStr() const {
438 return stringFromIslObj(NewAccessRelation);
439}
440
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000441__isl_give isl_basic_map *
442MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000443 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000444 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000445
Tobias Grosser084d8f72012-05-29 09:29:44 +0000446 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000447 isl_basic_set_universe(Statement->getDomainSpace()),
448 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000449}
450
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000451// Formalize no out-of-bound access assumption
452//
453// When delinearizing array accesses we optimistically assume that the
454// delinearized accesses do not access out of bound locations (the subscript
455// expression of each array evaluates for each statement instance that is
456// executed to a value that is larger than zero and strictly smaller than the
457// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000458// dimension for which we do not need to assume any upper bound. At this point
459// we formalize this assumption to ensure that at code generation time the
460// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000461//
462// To find the set of constraints necessary to avoid out of bound accesses, we
463// first build the set of data locations that are not within array bounds. We
464// then apply the reverse access relation to obtain the set of iterations that
465// may contain invalid accesses and reduce this set of iterations to the ones
466// that are actually executed by intersecting them with the domain of the
467// statement. If we now project out all loop dimensions, we obtain a set of
468// parameters that may cause statement instances to be executed that may
469// possibly yield out of bound memory accesses. The complement of these
470// constraints is the set of constraints that needs to be assumed to ensure such
471// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000472void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000473 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000474 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Michael Krusee2bccbb2015-09-18 19:59:43 +0000475 for (int i = 1, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000476 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
477 isl_pw_aff *Var =
478 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
479 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
480
481 isl_set *DimOutside;
482
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000483 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Michael Krusee2bccbb2015-09-18 19:59:43 +0000484 isl_pw_aff *SizeE = Statement->getPwAff(Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000485
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000486 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
487 Statement->getNumIterators());
488 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
489 isl_space_dim(Space, isl_dim_set));
490 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
491 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000492
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000493 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000494
495 Outside = isl_set_union(Outside, DimOutside);
496 }
497
498 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
499 Outside = isl_set_intersect(Outside, Statement->getDomain());
500 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000501
502 // Remove divs to avoid the construction of overly complicated assumptions.
503 // Doing so increases the set of parameter combinations that are assumed to
504 // not appear. This is always save, but may make the resulting run-time check
505 // bail out more often than strictly necessary.
506 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000507 Outside = isl_set_complement(Outside);
508 Statement->getParent()->addAssumption(Outside);
509 isl_space_free(Space);
510}
511
Johannes Doerferte7044942015-02-24 11:58:30 +0000512void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
513 ScalarEvolution *SE = Statement->getParent()->getSE();
514
515 Value *Ptr = getPointerOperand(*getAccessInstruction());
516 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
517 return;
518
519 auto *PtrSCEV = SE->getSCEV(Ptr);
520 if (isa<SCEVCouldNotCompute>(PtrSCEV))
521 return;
522
523 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
524 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
525 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
526
527 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
528 if (Range.isFullSet())
529 return;
530
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000531 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000532 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000533 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
534 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
535
536 auto Min = LB.sdiv(APInt(BW, ElementSize));
537 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000538
539 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
540 AccessRange =
541 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
542 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
543}
544
Michael Krusee2bccbb2015-09-18 19:59:43 +0000545__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000546 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000547 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000548
549 for (int i = Size - 2; i >= 0; --i) {
550 isl_space *Space;
551 isl_map *MapOne, *MapTwo;
Michael Krusee2bccbb2015-09-18 19:59:43 +0000552 isl_pw_aff *DimSize = Statement->getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000553
554 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
555 isl_pw_aff_free(DimSize);
556 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
557
558 Space = isl_map_get_space(AccessRelation);
559 Space = isl_space_map_from_set(isl_space_range(Space));
560 Space = isl_space_align_params(Space, SpaceSize);
561
562 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
563 isl_id_free(ParamId);
564
565 MapOne = isl_map_universe(isl_space_copy(Space));
566 for (int j = 0; j < Size; ++j)
567 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
568 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
569
570 MapTwo = isl_map_universe(isl_space_copy(Space));
571 for (int j = 0; j < Size; ++j)
572 if (j < i || j > i + 1)
573 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
574
575 isl_local_space *LS = isl_local_space_from_space(Space);
576 isl_constraint *C;
577 C = isl_equality_alloc(isl_local_space_copy(LS));
578 C = isl_constraint_set_constant_si(C, -1);
579 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
580 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
581 MapTwo = isl_map_add_constraint(MapTwo, C);
582 C = isl_equality_alloc(LS);
583 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
584 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
585 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
586 MapTwo = isl_map_add_constraint(MapTwo, C);
587 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
588
589 MapOne = isl_map_union(MapOne, MapTwo);
590 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
591 }
592 return AccessRelation;
593}
594
Michael Krusee2bccbb2015-09-18 19:59:43 +0000595void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
596 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000597
Michael Krusee2bccbb2015-09-18 19:59:43 +0000598 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000599 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000600
Michael Krusee2bccbb2015-09-18 19:59:43 +0000601 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000602 // We overapproximate non-affine accesses with a possible access to the
603 // whole array. For read accesses it does not make a difference, if an
604 // access must or may happen. However, for write accesses it is important to
605 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000606 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000607 AccessRelation =
608 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000609
Michael Krusee2bccbb2015-09-18 19:59:43 +0000610 computeBoundsOnAccessRelation(getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000611 return;
612 }
613
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000614 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000615 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000616
Michael Krusee2bccbb2015-09-18 19:59:43 +0000617 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
618 isl_pw_aff *Affine = Statement->getPwAff(Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000619
Sebastian Pop422e33f2014-06-03 18:16:31 +0000620 if (Size == 1) {
621 // For the non delinearized arrays, divide the access function of the last
622 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000623 //
624 // A stride one array access in C expressed as A[i] is expressed in
625 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
626 // two subsequent values of 'i' index two values that are stored next to
627 // each other in memory. By this division we make this characteristic
628 // obvious again.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000629 isl_val *v = isl_val_int_from_si(Ctx, getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000630 Affine = isl_pw_aff_scale_down_val(Affine, v);
631 }
632
633 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
634
Tobias Grosser79baa212014-04-10 08:38:02 +0000635 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000636 }
637
Michael Krusee2bccbb2015-09-18 19:59:43 +0000638 if (Sizes.size() > 1 && !isa<SCEVConstant>(Sizes[0]))
639 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000640
Tobias Grosser79baa212014-04-10 08:38:02 +0000641 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000642 AccessRelation = isl_map_set_tuple_id(
643 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000644 AccessRelation =
645 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
646
Michael Krusee2bccbb2015-09-18 19:59:43 +0000647 assumeNoOutOfBound();
Tobias Grosseraa660a92015-03-30 00:07:50 +0000648 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000649 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000650}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000651
Michael Krusecac948e2015-10-02 13:53:07 +0000652MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000653 AccessType Type, Value *BaseAddress,
654 unsigned ElemBytes, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000655 ArrayRef<const SCEV *> Subscripts,
656 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Michael Kruse8d0b7342015-09-25 21:21:00 +0000657 AccessOrigin Origin, StringRef BaseName)
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000658 : Origin(Origin), AccType(Type), RedType(RT_NONE), Statement(Stmt),
Michael Krusecac948e2015-10-02 13:53:07 +0000659 BaseAddr(BaseAddress), BaseName(BaseName), ElemBytes(ElemBytes),
660 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
661 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000662 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000663 NewAccessRelation(nullptr) {
664
665 std::string IdName = "__polly_array_ref";
666 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
667}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000668
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000669void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000670 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000671 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000672}
673
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000674const std::string MemoryAccess::getReductionOperatorStr() const {
675 return MemoryAccess::getReductionOperatorStr(getReductionType());
676}
677
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000678__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
679
Johannes Doerfertf6183392014-07-01 20:52:51 +0000680raw_ostream &polly::operator<<(raw_ostream &OS,
681 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000682 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000683 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000684 else
685 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000686 return OS;
687}
688
Tobias Grosser75805372011-04-29 06:27:02 +0000689void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000690 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000691 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000692 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000693 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000694 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000695 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000696 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000697 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000698 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000699 break;
700 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000701 OS << "[Reduction Type: " << getReductionType() << "] ";
Michael Kruse8d0b7342015-09-25 21:21:00 +0000702 OS << "[Scalar: " << isImplicit() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000703 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000704 if (hasNewAccessRelation())
705 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000706}
707
Tobias Grosser74394f02013-01-14 22:40:23 +0000708void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000709
710// Create a map in the size of the provided set domain, that maps from the
711// one element of the provided set domain to another element of the provided
712// set domain.
713// The mapping is limited to all points that are equal in all but the last
714// dimension and for which the last dimension of the input is strict smaller
715// than the last dimension of the output.
716//
717// getEqualAndLarger(set[i0, i1, ..., iX]):
718//
719// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
720// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
721//
Tobias Grosserf5338802011-10-06 00:03:35 +0000722static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000723 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000724 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000725 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000726
727 // Set all but the last dimension to be equal for the input and output
728 //
729 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
730 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000731 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000732 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000733
734 // Set the last dimension of the input to be strict smaller than the
735 // last dimension of the output.
736 //
737 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000738 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
739 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000740 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000741}
742
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000743__isl_give isl_set *
744MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000745 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000746 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000747 isl_space *Space = isl_space_range(isl_map_get_space(S));
748 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000749
Sebastian Popa00a0292012-12-18 07:46:06 +0000750 S = isl_map_reverse(S);
751 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000752
Sebastian Popa00a0292012-12-18 07:46:06 +0000753 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
754 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
755 NextScatt = isl_map_apply_domain(NextScatt, S);
756 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000757
Sebastian Popa00a0292012-12-18 07:46:06 +0000758 isl_set *Deltas = isl_map_deltas(NextScatt);
759 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000760}
761
Sebastian Popa00a0292012-12-18 07:46:06 +0000762bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000763 int StrideWidth) const {
764 isl_set *Stride, *StrideX;
765 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000766
Sebastian Popa00a0292012-12-18 07:46:06 +0000767 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000768 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000769 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
770 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
771 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
772 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000773 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000774
Tobias Grosser28dd4862012-01-24 16:42:16 +0000775 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000776 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000777
Tobias Grosser28dd4862012-01-24 16:42:16 +0000778 return IsStrideX;
779}
780
Sebastian Popa00a0292012-12-18 07:46:06 +0000781bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
782 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000783}
784
Sebastian Popa00a0292012-12-18 07:46:06 +0000785bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
786 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000787}
788
Tobias Grosser166c4222015-09-05 07:46:40 +0000789void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
790 isl_map_free(NewAccessRelation);
791 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000792}
Tobias Grosser75805372011-04-29 06:27:02 +0000793
794//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000795
Tobias Grosser808cd692015-07-14 09:33:13 +0000796isl_map *ScopStmt::getSchedule() const {
797 isl_set *Domain = getDomain();
798 if (isl_set_is_empty(Domain)) {
799 isl_set_free(Domain);
800 return isl_map_from_aff(
801 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
802 }
803 auto *Schedule = getParent()->getSchedule();
804 Schedule = isl_union_map_intersect_domain(
805 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
806 if (isl_union_map_is_empty(Schedule)) {
807 isl_set_free(Domain);
808 isl_union_map_free(Schedule);
809 return isl_map_from_aff(
810 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
811 }
812 auto *M = isl_map_from_union_map(Schedule);
813 M = isl_map_coalesce(M);
814 M = isl_map_gist_domain(M, Domain);
815 M = isl_map_coalesce(M);
816 return M;
817}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000818
Johannes Doerfert574182d2015-08-12 10:19:50 +0000819__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000820 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
821 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000822}
823
Tobias Grosser37eb4222014-02-20 21:43:54 +0000824void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
825 assert(isl_set_is_subset(NewDomain, Domain) &&
826 "New domain is not a subset of old domain!");
827 isl_set_free(Domain);
828 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000829}
830
Michael Krusecac948e2015-10-02 13:53:07 +0000831void ScopStmt::buildAccessRelations() {
832 for (MemoryAccess *Access : MemAccs) {
833 Type *ElementType = Access->getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000834
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000835 ScopArrayInfo::ARRAYKIND Ty;
836 if (Access->isPHI())
837 Ty = ScopArrayInfo::KIND_PHI;
838 else if (Access->isImplicit())
839 Ty = ScopArrayInfo::KIND_SCALAR;
840 else
841 Ty = ScopArrayInfo::KIND_ARRAY;
842
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000843 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000844 Access->getBaseAddr(), ElementType, Access->Sizes, Ty);
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000845
Michael Krusecac948e2015-10-02 13:53:07 +0000846 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +0000847 }
848}
849
Michael Krusecac948e2015-10-02 13:53:07 +0000850void ScopStmt::addAccess(MemoryAccess *Access) {
851 Instruction *AccessInst = Access->getAccessInstruction();
852
853 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
854 if (!MAL)
855 MAL = new MemoryAccessList();
856 MAL->emplace_front(Access);
857 MemAccs.push_back(MAL->front());
858}
859
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000860void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000861 for (MemoryAccess *MA : *this)
862 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000863
864 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000865}
866
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000867/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
868static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
869 void *User) {
870 isl_set **BoundedParts = static_cast<isl_set **>(User);
871 if (isl_basic_set_is_bounded(BSet))
872 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
873 else
874 isl_basic_set_free(BSet);
875 return isl_stat_ok;
876}
877
878/// @brief Return the bounded parts of @p S.
879static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
880 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
881 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
882 isl_set_free(S);
883 return BoundedParts;
884}
885
886/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
887///
888/// @returns A separation of @p S into first an unbounded then a bounded subset,
889/// both with regards to the dimension @p Dim.
890static std::pair<__isl_give isl_set *, __isl_give isl_set *>
891partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
892
893 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000894 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000895
896 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000897 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000898
899 // Remove dimensions that are greater than Dim as they are not interesting.
900 assert(NumDimsS >= Dim + 1);
901 OnlyDimS =
902 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
903
904 // Create artificial parametric upper bounds for dimensions smaller than Dim
905 // as we are not interested in them.
906 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
907 for (unsigned u = 0; u < Dim; u++) {
908 isl_constraint *C = isl_inequality_alloc(
909 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
910 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
911 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
912 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
913 }
914
915 // Collect all bounded parts of OnlyDimS.
916 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
917
918 // Create the dimensions greater than Dim again.
919 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
920 NumDimsS - Dim - 1);
921
922 // Remove the artificial upper bound parameters again.
923 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
924
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000925 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000926 return std::make_pair(UnboundedParts, BoundedParts);
927}
928
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000929/// @brief Set the dimension Ids from @p From in @p To.
930static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
931 __isl_take isl_set *To) {
932 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
933 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
934 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
935 }
936 return To;
937}
938
939/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000940static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000941 __isl_take isl_pw_aff *L,
942 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +0000943 switch (Pred) {
944 case ICmpInst::ICMP_EQ:
945 return isl_pw_aff_eq_set(L, R);
946 case ICmpInst::ICMP_NE:
947 return isl_pw_aff_ne_set(L, R);
948 case ICmpInst::ICMP_SLT:
949 return isl_pw_aff_lt_set(L, R);
950 case ICmpInst::ICMP_SLE:
951 return isl_pw_aff_le_set(L, R);
952 case ICmpInst::ICMP_SGT:
953 return isl_pw_aff_gt_set(L, R);
954 case ICmpInst::ICMP_SGE:
955 return isl_pw_aff_ge_set(L, R);
956 case ICmpInst::ICMP_ULT:
957 return isl_pw_aff_lt_set(L, R);
958 case ICmpInst::ICMP_UGT:
959 return isl_pw_aff_gt_set(L, R);
960 case ICmpInst::ICMP_ULE:
961 return isl_pw_aff_le_set(L, R);
962 case ICmpInst::ICMP_UGE:
963 return isl_pw_aff_ge_set(L, R);
964 default:
965 llvm_unreachable("Non integer predicate not supported");
966 }
967}
968
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000969/// @brief Create the conditions under which @p L @p Pred @p R is true.
970///
971/// Helper function that will make sure the dimensions of the result have the
972/// same isl_id's as the @p Domain.
973static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
974 __isl_take isl_pw_aff *L,
975 __isl_take isl_pw_aff *R,
976 __isl_keep isl_set *Domain) {
977 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
978 return setDimensionIds(Domain, ConsequenceCondSet);
979}
980
981/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000982///
983/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000984/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
985/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000986static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000987buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +0000988 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
989
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000990 Value *Condition = getConditionFromTerminator(SI);
991 assert(Condition && "No condition for switch");
992
993 ScalarEvolution &SE = *S.getSE();
994 BasicBlock *BB = SI->getParent();
995 isl_pw_aff *LHS, *RHS;
996 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
997
998 unsigned NumSuccessors = SI->getNumSuccessors();
999 ConditionSets.resize(NumSuccessors);
1000 for (auto &Case : SI->cases()) {
1001 unsigned Idx = Case.getSuccessorIndex();
1002 ConstantInt *CaseValue = Case.getCaseValue();
1003
1004 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
1005 isl_set *CaseConditionSet =
1006 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1007 ConditionSets[Idx] = isl_set_coalesce(
1008 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1009 }
1010
1011 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1012 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1013 for (unsigned u = 2; u < NumSuccessors; u++)
1014 ConditionSetUnion =
1015 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1016 ConditionSets[0] = setDimensionIds(
1017 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1018
1019 S.markAsOptimized();
1020 isl_pw_aff_free(LHS);
1021}
1022
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001023/// @brief Build the conditions sets for the branch condition @p Condition in
1024/// the @p Domain.
1025///
1026/// This will fill @p ConditionSets with the conditions under which control
1027/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1028/// have as many elements as @p TI has successors.
1029static void
1030buildConditionSets(Scop &S, Value *Condition, TerminatorInst *TI, Loop *L,
1031 __isl_keep isl_set *Domain,
1032 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1033
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 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1041 auto Opcode = BinOp->getOpcode();
1042 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1043
1044 buildConditionSets(S, BinOp->getOperand(0), TI, L, Domain, ConditionSets);
1045 buildConditionSets(S, BinOp->getOperand(1), TI, L, Domain, ConditionSets);
1046
1047 isl_set_free(ConditionSets.pop_back_val());
1048 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1049 isl_set_free(ConditionSets.pop_back_val());
1050 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1051
1052 if (Opcode == Instruction::And)
1053 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1054 else
1055 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1056 } else {
1057 auto *ICond = dyn_cast<ICmpInst>(Condition);
1058 assert(ICond &&
1059 "Condition of exiting branch was neither constant nor ICmp!");
1060
1061 ScalarEvolution &SE = *S.getSE();
1062 BasicBlock *BB = TI->getParent();
1063 isl_pw_aff *LHS, *RHS;
1064 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1065 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
1066 ConsequenceCondSet =
1067 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1068 }
1069
1070 assert(ConsequenceCondSet);
1071 isl_set *AlternativeCondSet =
1072 isl_set_complement(isl_set_copy(ConsequenceCondSet));
1073
1074 ConditionSets.push_back(isl_set_coalesce(
1075 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
1076 ConditionSets.push_back(isl_set_coalesce(
1077 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
1078}
1079
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001080/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1081///
1082/// This will fill @p ConditionSets with the conditions under which control
1083/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1084/// have as many elements as @p TI has successors.
1085static void
1086buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1087 __isl_keep isl_set *Domain,
1088 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1089
1090 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1091 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1092
1093 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1094
1095 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001096 ConditionSets.push_back(isl_set_copy(Domain));
1097 return;
1098 }
1099
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001100 Value *Condition = getConditionFromTerminator(TI);
1101 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001102
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001103 return buildConditionSets(S, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001104}
1105
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001106void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +00001107 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +00001108
Tobias Grosser084d8f72012-05-29 09:29:44 +00001109 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1110
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001111 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001112 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001113}
1114
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001115void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001116 isl_ctx *Ctx = Parent.getIslCtx();
1117 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1118 Type *Ty = GEP->getPointerOperandType();
1119 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001120 ScopDetection &SD = Parent.getSD();
1121
1122 // The set of loads that are required to be invariant.
1123 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001124
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001125 std::vector<const SCEV *> Subscripts;
1126 std::vector<int> Sizes;
1127
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001128 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001129
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001130 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001131 Ty = PtrTy->getElementType();
1132 }
1133
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001134 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001135
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001136 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001137
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001138 for (size_t i = 0; i < Sizes.size(); i++) {
1139 auto Expr = Subscripts[i + IndexOffset];
1140 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001141
Johannes Doerfert09e36972015-10-07 20:17:36 +00001142 InvariantLoadsSetTy AccessILS;
1143 if (!isAffineExpr(&Parent.getRegion(), Expr, SE, nullptr, &AccessILS))
1144 continue;
1145
1146 bool NonAffine = false;
1147 for (LoadInst *LInst : AccessILS)
1148 if (!ScopRIL.count(LInst))
1149 NonAffine = true;
1150
1151 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001152 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001153
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001154 isl_pw_aff *AccessOffset = getPwAff(Expr);
1155 AccessOffset =
1156 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001157
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001158 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1159 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001160
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001161 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1162 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1163 OutOfBound = isl_set_params(OutOfBound);
1164 isl_set *InBound = isl_set_complement(OutOfBound);
1165 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001166
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001167 // A => B == !A or B
1168 isl_set *InBoundIfExecuted =
1169 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001170
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001171 Parent.addAssumption(InBoundIfExecuted);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001172 }
1173
1174 isl_local_space_free(LSpace);
1175}
1176
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001177void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1178 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001179 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1180 deriveAssumptionsFromGEP(GEP);
1181}
1182
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001183void ScopStmt::collectSurroundingLoops() {
1184 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1185 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1186 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1187 isl_id_free(DimId);
1188 }
1189}
1190
Michael Kruse9d080092015-09-11 21:41:48 +00001191ScopStmt::ScopStmt(Scop &parent, Region &R)
Michael Krusecac948e2015-10-02 13:53:07 +00001192 : Parent(parent), Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001193
Tobias Grosser16c44032015-07-09 07:31:45 +00001194 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001195}
1196
Michael Kruse9d080092015-09-11 21:41:48 +00001197ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Michael Krusecac948e2015-10-02 13:53:07 +00001198 : Parent(parent), Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001199
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001200 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001201}
1202
1203void ScopStmt::init() {
1204 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001205
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001206 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001207 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001208 buildAccessRelations();
1209
1210 if (BB) {
1211 deriveAssumptions(BB);
1212 } else {
1213 for (BasicBlock *Block : R->blocks()) {
1214 deriveAssumptions(Block);
1215 }
1216 }
1217
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001218 if (DetectReductions)
1219 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001220}
1221
Johannes Doerferte58a0122014-06-27 20:31:28 +00001222/// @brief Collect loads which might form a reduction chain with @p StoreMA
1223///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001224/// Check if the stored value for @p StoreMA is a binary operator with one or
1225/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001226/// used only once (by @p StoreMA) and its load operands are also used only
1227/// once, we have found a possible reduction chain. It starts at an operand
1228/// load and includes the binary operator and @p StoreMA.
1229///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001230/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001231/// escape this block or into any other store except @p StoreMA.
1232void ScopStmt::collectCandiateReductionLoads(
1233 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1234 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1235 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001236 return;
1237
1238 // Skip if there is not one binary operator between the load and the store
1239 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001240 if (!BinOp)
1241 return;
1242
1243 // Skip if the binary operators has multiple uses
1244 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001245 return;
1246
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001247 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001248 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1249 return;
1250
Johannes Doerfert9890a052014-07-01 00:32:29 +00001251 // Skip if the binary operator is outside the current SCoP
1252 if (BinOp->getParent() != Store->getParent())
1253 return;
1254
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001255 // Skip if it is a multiplicative reduction and we disabled them
1256 if (DisableMultiplicativeReductions &&
1257 (BinOp->getOpcode() == Instruction::Mul ||
1258 BinOp->getOpcode() == Instruction::FMul))
1259 return;
1260
Johannes Doerferte58a0122014-06-27 20:31:28 +00001261 // Check the binary operator operands for a candidate load
1262 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1263 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1264 if (!PossibleLoad0 && !PossibleLoad1)
1265 return;
1266
1267 // A load is only a candidate if it cannot escape (thus has only this use)
1268 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001269 if (PossibleLoad0->getParent() == Store->getParent())
1270 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001271 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001272 if (PossibleLoad1->getParent() == Store->getParent())
1273 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001274}
1275
1276/// @brief Check for reductions in this ScopStmt
1277///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001278/// Iterate over all store memory accesses and check for valid binary reduction
1279/// like chains. For all candidates we check if they have the same base address
1280/// and there are no other accesses which overlap with them. The base address
1281/// check rules out impossible reductions candidates early. The overlap check,
1282/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001283/// guarantees that none of the intermediate results will escape during
1284/// execution of the loop nest. We basically check here that no other memory
1285/// access can access the same memory as the potential reduction.
1286void ScopStmt::checkForReductions() {
1287 SmallVector<MemoryAccess *, 2> Loads;
1288 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1289
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001290 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001291 // stores and collecting possible reduction loads.
1292 for (MemoryAccess *StoreMA : MemAccs) {
1293 if (StoreMA->isRead())
1294 continue;
1295
1296 Loads.clear();
1297 collectCandiateReductionLoads(StoreMA, Loads);
1298 for (MemoryAccess *LoadMA : Loads)
1299 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1300 }
1301
1302 // Then check each possible candidate pair.
1303 for (const auto &CandidatePair : Candidates) {
1304 bool Valid = true;
1305 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1306 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1307
1308 // Skip those with obviously unequal base addresses.
1309 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1310 isl_map_free(LoadAccs);
1311 isl_map_free(StoreAccs);
1312 continue;
1313 }
1314
1315 // And check if the remaining for overlap with other memory accesses.
1316 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1317 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1318 isl_set *AllAccs = isl_map_range(AllAccsRel);
1319
1320 for (MemoryAccess *MA : MemAccs) {
1321 if (MA == CandidatePair.first || MA == CandidatePair.second)
1322 continue;
1323
1324 isl_map *AccRel =
1325 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1326 isl_set *Accs = isl_map_range(AccRel);
1327
1328 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1329 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1330 Valid = Valid && isl_set_is_empty(OverlapAccs);
1331 isl_set_free(OverlapAccs);
1332 }
1333 }
1334
1335 isl_set_free(AllAccs);
1336 if (!Valid)
1337 continue;
1338
Johannes Doerfertf6183392014-07-01 20:52:51 +00001339 const LoadInst *Load =
1340 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1341 MemoryAccess::ReductionType RT =
1342 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1343
Johannes Doerferte58a0122014-06-27 20:31:28 +00001344 // If no overlapping access was found we mark the load and store as
1345 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001346 CandidatePair.first->markAsReductionLike(RT);
1347 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001348 }
Tobias Grosser75805372011-04-29 06:27:02 +00001349}
1350
Tobias Grosser74394f02013-01-14 22:40:23 +00001351std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001352
Tobias Grosser54839312015-04-21 11:37:25 +00001353std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001354 auto *S = getSchedule();
1355 auto Str = stringFromIslObj(S);
1356 isl_map_free(S);
1357 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001358}
1359
Tobias Grosser74394f02013-01-14 22:40:23 +00001360unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001361
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001362unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001363
Tobias Grosser75805372011-04-29 06:27:02 +00001364const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1365
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001366const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001367 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001368}
1369
Tobias Grosser74394f02013-01-14 22:40:23 +00001370isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001371
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001372__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001373
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001374__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001375 return isl_set_get_space(Domain);
1376}
1377
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001378__isl_give isl_id *ScopStmt::getDomainId() const {
1379 return isl_set_get_tuple_id(Domain);
1380}
Tobias Grossercd95b772012-08-30 11:49:38 +00001381
Tobias Grosser75805372011-04-29 06:27:02 +00001382ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001383 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001384 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001385}
1386
1387void ScopStmt::print(raw_ostream &OS) const {
1388 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001389 OS.indent(12) << "Domain :=\n";
1390
1391 if (Domain) {
1392 OS.indent(16) << getDomainStr() << ";\n";
1393 } else
1394 OS.indent(16) << "n/a\n";
1395
Tobias Grosser54839312015-04-21 11:37:25 +00001396 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001397
1398 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001399 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001400 } else
1401 OS.indent(16) << "n/a\n";
1402
Tobias Grosser083d3d32014-06-28 08:59:45 +00001403 for (MemoryAccess *Access : MemAccs)
1404 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001405}
1406
1407void ScopStmt::dump() const { print(dbgs()); }
1408
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001409void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001410
1411 // Remove all memory accesses in @p InvMAs from this statement together
1412 // with all scalar accesses that were caused by them. The tricky iteration
1413 // order uses is needed because the MemAccs is a vector and the order in
1414 // which the accesses of each memory access list (MAL) are stored in this
1415 // vector is reversed.
1416 for (MemoryAccess *MA : InvMAs) {
1417 auto &MAL = *lookupAccessesFor(MA->getAccessInstruction());
1418 MAL.reverse();
1419
1420 auto MALIt = MAL.begin();
1421 auto MALEnd = MAL.end();
1422 auto MemAccsIt = MemAccs.begin();
1423 while (MALIt != MALEnd) {
1424 while (*MemAccsIt != *MALIt)
1425 MemAccsIt++;
1426
1427 MALIt++;
1428 MemAccs.erase(MemAccsIt);
1429 }
1430
1431 InstructionToAccess.erase(MA->getAccessInstruction());
1432 delete &MAL;
1433 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001434}
1435
Tobias Grosser75805372011-04-29 06:27:02 +00001436//===----------------------------------------------------------------------===//
1437/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001438
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001439void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001440 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1441 isl_set_free(Context);
1442 Context = NewContext;
1443}
1444
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001445/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1446struct SCEVSensitiveParameterRewriter
1447 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1448 ValueToValueMap &VMap;
1449 ScalarEvolution &SE;
1450
1451public:
1452 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1453 : VMap(VMap), SE(SE) {}
1454
1455 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1456 ValueToValueMap &VMap) {
1457 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1458 return SSPR.visit(E);
1459 }
1460
1461 const SCEV *visit(const SCEV *E) {
1462 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1463 }
1464
1465 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1466
1467 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1468 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1469 }
1470
1471 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1472 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1473 }
1474
1475 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1476 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1477 }
1478
1479 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1480 SmallVector<const SCEV *, 4> Operands;
1481 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1482 Operands.push_back(visit(E->getOperand(i)));
1483 return SE.getAddExpr(Operands);
1484 }
1485
1486 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1487 SmallVector<const SCEV *, 4> Operands;
1488 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1489 Operands.push_back(visit(E->getOperand(i)));
1490 return SE.getMulExpr(Operands);
1491 }
1492
1493 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1494 SmallVector<const SCEV *, 4> Operands;
1495 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1496 Operands.push_back(visit(E->getOperand(i)));
1497 return SE.getSMaxExpr(Operands);
1498 }
1499
1500 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1501 SmallVector<const SCEV *, 4> Operands;
1502 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1503 Operands.push_back(visit(E->getOperand(i)));
1504 return SE.getUMaxExpr(Operands);
1505 }
1506
1507 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1508 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1509 }
1510
1511 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1512 auto *Start = visit(E->getStart());
1513 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1514 visit(E->getStepRecurrence(SE)),
1515 E->getLoop(), SCEV::FlagAnyWrap);
1516 return SE.getAddExpr(Start, AddRec);
1517 }
1518
1519 const SCEV *visitUnknown(const SCEVUnknown *E) {
1520 if (auto *NewValue = VMap.lookup(E->getValue()))
1521 return SE.getUnknown(NewValue);
1522 return E;
1523 }
1524};
1525
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001526const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001527 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001528}
1529
Tobias Grosserabfbe632013-02-05 12:09:06 +00001530void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001531 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001532 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001533
1534 // Normalize the SCEV to get the representing element for an invariant load.
1535 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1536
Tobias Grosser60b54f12011-11-08 15:41:28 +00001537 if (ParameterIds.find(Parameter) != ParameterIds.end())
1538 continue;
1539
1540 int dimension = Parameters.size();
1541
1542 Parameters.push_back(Parameter);
1543 ParameterIds[Parameter] = dimension;
1544 }
1545}
1546
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001547__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001548 // Normalize the SCEV to get the representing element for an invariant load.
1549 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1550
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001551 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001552
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001553 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001554 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001555
Tobias Grosser8f99c162011-11-15 11:38:55 +00001556 std::string ParameterName;
1557
1558 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1559 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001560 ParameterName = Val->getName();
Johannes Doerferte071f6d2015-11-03 16:49:59 +00001561 if (!Val->hasName())
1562 if (LoadInst *LI = dyn_cast<LoadInst>(Val))
1563 ParameterName =
1564 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001565 }
1566
1567 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001568 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001569
Tobias Grosser20532b82014-04-11 17:56:49 +00001570 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1571 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001572}
Tobias Grosser75805372011-04-29 06:27:02 +00001573
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001574isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1575 isl_set *DomainContext = isl_union_set_params(getDomains());
1576 return isl_set_intersect_params(C, DomainContext);
1577}
1578
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001579void Scop::buildBoundaryContext() {
1580 BoundaryContext = Affinator.getWrappingContext();
1581 BoundaryContext = isl_set_complement(BoundaryContext);
1582 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
1583}
1584
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001585void Scop::addUserContext() {
1586 if (UserContextStr.empty())
1587 return;
1588
1589 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1590 isl_space *Space = getParamSpace();
1591 if (isl_space_dim(Space, isl_dim_param) !=
1592 isl_set_dim(UserContext, isl_dim_param)) {
1593 auto SpaceStr = isl_space_to_str(Space);
1594 errs() << "Error: the context provided in -polly-context has not the same "
1595 << "number of dimensions than the computed context. Due to this "
1596 << "mismatch, the -polly-context option is ignored. Please provide "
1597 << "the context in the parameter space: " << SpaceStr << ".\n";
1598 free(SpaceStr);
1599 isl_set_free(UserContext);
1600 isl_space_free(Space);
1601 return;
1602 }
1603
1604 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1605 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1606 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1607
1608 if (strcmp(NameContext, NameUserContext) != 0) {
1609 auto SpaceStr = isl_space_to_str(Space);
1610 errs() << "Error: the name of dimension " << i
1611 << " provided in -polly-context "
1612 << "is '" << NameUserContext << "', but the name in the computed "
1613 << "context is '" << NameContext
1614 << "'. Due to this name mismatch, "
1615 << "the -polly-context option is ignored. Please provide "
1616 << "the context in the parameter space: " << SpaceStr << ".\n";
1617 free(SpaceStr);
1618 isl_set_free(UserContext);
1619 isl_space_free(Space);
1620 return;
1621 }
1622
1623 UserContext =
1624 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1625 isl_space_get_dim_id(Space, isl_dim_param, i));
1626 }
1627
1628 Context = isl_set_intersect(Context, UserContext);
1629 isl_space_free(Space);
1630}
1631
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001632void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001633 DenseMap<const SCEV *, LoadInst *> EquivClasses;
1634
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001635 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001636 for (LoadInst *LInst : RIL) {
1637 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1638
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001639 LoadInst *&ClassRep = EquivClasses[PointerSCEV];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001640 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001641 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001642 continue;
1643 }
1644
1645 ClassRep = LInst;
1646 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(),
1647 nullptr);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001648 }
1649}
1650
Tobias Grosser6be480c2011-11-08 15:41:13 +00001651void Scop::buildContext() {
1652 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001653 Context = isl_set_universe(isl_space_copy(Space));
1654 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001655}
1656
Tobias Grosser18daaca2012-05-22 10:47:27 +00001657void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001658 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001659 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001660
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001661 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001662
Johannes Doerferte7044942015-02-24 11:58:30 +00001663 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001664 }
1665}
1666
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001667void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001668 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001669 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001670
Tobias Grosser083d3d32014-06-28 08:59:45 +00001671 for (const auto &ParamID : ParameterIds) {
1672 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001673 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001674 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001675 }
1676
1677 // Align the parameters of all data structures to the model.
1678 Context = isl_set_align_params(Context, Space);
1679
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001680 for (ScopStmt &Stmt : *this)
1681 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001682}
1683
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001684static __isl_give isl_set *
1685simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1686 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001687 // If we modelt all blocks in the SCoP that have side effects we can simplify
1688 // the context with the constraints that are needed for anything to be
1689 // executed at all. However, if we have error blocks in the SCoP we already
1690 // assumed some parameter combinations cannot occure and removed them from the
1691 // domains, thus we cannot use the remaining domain to simplify the
1692 // assumptions.
1693 if (!S.hasErrorBlock()) {
1694 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1695 AssumptionContext =
1696 isl_set_gist_params(AssumptionContext, DomainParameters);
1697 }
1698
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001699 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1700 return AssumptionContext;
1701}
1702
1703void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001704 // The parameter constraints of the iteration domains give us a set of
1705 // constraints that need to hold for all cases where at least a single
1706 // statement iteration is executed in the whole scop. We now simplify the
1707 // assumed context under the assumption that such constraints hold and at
1708 // least a single statement iteration is executed. For cases where no
1709 // statement instances are executed, the assumptions we have taken about
1710 // the executed code do not matter and can be changed.
1711 //
1712 // WARNING: This only holds if the assumptions we have taken do not reduce
1713 // the set of statement instances that are executed. Otherwise we
1714 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001715 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001716 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001717 // performed. In such a case, modifying the run-time conditions and
1718 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001719 // to not be executed.
1720 //
1721 // Example:
1722 //
1723 // When delinearizing the following code:
1724 //
1725 // for (long i = 0; i < 100; i++)
1726 // for (long j = 0; j < m; j++)
1727 // A[i+p][j] = 1.0;
1728 //
1729 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001730 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001731 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001732 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1733 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001734}
1735
Johannes Doerfertb164c792014-09-18 11:17:17 +00001736/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001737static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001738 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1739 isl_pw_multi_aff *MinPMA, *MaxPMA;
1740 isl_pw_aff *LastDimAff;
1741 isl_aff *OneAff;
1742 unsigned Pos;
1743
Johannes Doerfert9143d672014-09-27 11:02:39 +00001744 // Restrict the number of parameters involved in the access as the lexmin/
1745 // lexmax computation will take too long if this number is high.
1746 //
1747 // Experiments with a simple test case using an i7 4800MQ:
1748 //
1749 // #Parameters involved | Time (in sec)
1750 // 6 | 0.01
1751 // 7 | 0.04
1752 // 8 | 0.12
1753 // 9 | 0.40
1754 // 10 | 1.54
1755 // 11 | 6.78
1756 // 12 | 30.38
1757 //
1758 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1759 unsigned InvolvedParams = 0;
1760 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1761 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1762 InvolvedParams++;
1763
1764 if (InvolvedParams > RunTimeChecksMaxParameters) {
1765 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001766 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001767 }
1768 }
1769
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001770 Set = isl_set_remove_divs(Set);
1771
Johannes Doerfertb164c792014-09-18 11:17:17 +00001772 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1773 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1774
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001775 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1776 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1777
Johannes Doerfertb164c792014-09-18 11:17:17 +00001778 // Adjust the last dimension of the maximal access by one as we want to
1779 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1780 // we test during code generation might now point after the end of the
1781 // allocated array but we will never dereference it anyway.
1782 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1783 "Assumed at least one output dimension");
1784 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1785 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1786 OneAff = isl_aff_zero_on_domain(
1787 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1788 OneAff = isl_aff_add_constant_si(OneAff, 1);
1789 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1790 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1791
1792 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1793
1794 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001795 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001796}
1797
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001798static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1799 isl_set *Domain = MA->getStatement()->getDomain();
1800 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1801 return isl_set_reset_tuple_id(Domain);
1802}
1803
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001804/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1805static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001806 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001807 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001808
1809 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1810 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001811 Locations = isl_union_set_coalesce(Locations);
1812 Locations = isl_union_set_detect_equalities(Locations);
1813 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001814 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001815 isl_union_set_free(Locations);
1816 return Valid;
1817}
1818
Johannes Doerfert96425c22015-08-30 21:13:53 +00001819/// @brief Helper to treat non-affine regions and basic blocks the same.
1820///
1821///{
1822
1823/// @brief Return the block that is the representing block for @p RN.
1824static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1825 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1826 : RN->getNodeAs<BasicBlock>();
1827}
1828
1829/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001830static inline BasicBlock *
1831getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001832 if (RN->isSubRegion()) {
1833 assert(idx == 0);
1834 return RN->getNodeAs<Region>()->getExit();
1835 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001836 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001837}
1838
1839/// @brief Return the smallest loop surrounding @p RN.
1840static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1841 if (!RN->isSubRegion())
1842 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1843
1844 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1845 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1846 while (L && NonAffineSubRegion->contains(L))
1847 L = L->getParentLoop();
1848 return L;
1849}
1850
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001851static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1852 if (!RN->isSubRegion())
1853 return 1;
1854
1855 unsigned NumBlocks = 0;
1856 Region *R = RN->getNodeAs<Region>();
1857 for (auto BB : R->blocks()) {
1858 (void)BB;
1859 NumBlocks++;
1860 }
1861 return NumBlocks;
1862}
1863
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001864static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
1865 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00001866 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001867 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00001868 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001869 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00001870 return true;
1871 return false;
1872}
1873
Johannes Doerfert96425c22015-08-30 21:13:53 +00001874///}
1875
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001876static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1877 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001878 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001879 isl_id *DimId =
1880 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
1881 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
1882}
1883
Johannes Doerfert96425c22015-08-30 21:13:53 +00001884isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1885 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1886 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00001887 return getDomainConditions(BB);
1888}
1889
1890isl_set *Scop::getDomainConditions(BasicBlock *BB) {
1891 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001892 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001893}
1894
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001895void Scop::buildDomains(Region *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001896
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001897 auto *EntryBB = R->getEntry();
1898 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
1899 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001900
1901 Loop *L = LI.getLoopFor(EntryBB);
1902 while (LD-- >= 0) {
1903 S = addDomainDimId(S, LD + 1, L);
1904 L = L->getParentLoop();
1905 }
1906
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001907 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001908
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00001909 if (SD.isNonAffineSubRegion(R, R))
1910 return;
1911
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001912 buildDomainsWithBranchConstraints(R);
1913 propagateDomainConstraints(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001914}
1915
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001916void Scop::buildDomainsWithBranchConstraints(Region *R) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001917 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00001918
1919 // To create the domain for each block in R we iterate over all blocks and
1920 // subregions in R and propagate the conditions under which the current region
1921 // element is executed. To this end we iterate in reverse post order over R as
1922 // it ensures that we first visit all predecessors of a region node (either a
1923 // basic block or a subregion) before we visit the region node itself.
1924 // Initially, only the domain for the SCoP region entry block is set and from
1925 // there we propagate the current domain to all successors, however we add the
1926 // condition that the successor is actually executed next.
1927 // As we are only interested in non-loop carried constraints here we can
1928 // simply skip loop back edges.
1929
1930 ReversePostOrderTraversal<Region *> RTraversal(R);
1931 for (auto *RN : RTraversal) {
1932
1933 // Recurse for affine subregions but go on for basic blocks and non-affine
1934 // subregions.
1935 if (RN->isSubRegion()) {
1936 Region *SubRegion = RN->getNodeAs<Region>();
1937 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001938 buildDomainsWithBranchConstraints(SubRegion);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001939 continue;
1940 }
1941 }
1942
Johannes Doerfertf5673802015-10-01 23:48:18 +00001943 // Error blocks are assumed not to be executed. Therefor they are not
1944 // checked properly in the ScopDetection. Any attempt to generate control
1945 // conditions from them might result in a crash. However, this is only true
1946 // for the first step of the domain generation (this function) where we
1947 // push the control conditions of a block to the successors. In the second
1948 // step (propagateDomainConstraints) we only receive domain constraints from
1949 // the predecessors and can therefor look at the domain of a error block.
1950 // That allows us to generate the assumptions needed for them not to be
1951 // executed at runtime.
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001952 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
1953 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00001954 continue;
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001955 }
Johannes Doerfertf5673802015-10-01 23:48:18 +00001956
Johannes Doerfert96425c22015-08-30 21:13:53 +00001957 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001958 TerminatorInst *TI = BB->getTerminator();
1959
Johannes Doerfertf5673802015-10-01 23:48:18 +00001960 isl_set *Domain = DomainMap.lookup(BB);
1961 if (!Domain) {
1962 DEBUG(dbgs() << "\tSkip: " << BB->getName()
1963 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001964 continue;
1965 }
1966
Johannes Doerfert96425c22015-08-30 21:13:53 +00001967 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001968
1969 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1970 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1971
1972 // Build the condition sets for the successor nodes of the current region
1973 // node. If it is a non-affine subregion we will always execute the single
1974 // exit node, hence the single entry node domain is the condition set. For
1975 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001976 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001977 if (RN->isSubRegion())
1978 ConditionSets.push_back(isl_set_copy(Domain));
1979 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001980 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001981
1982 // Now iterate over the successors and set their initial domain based on
1983 // their condition set. We skip back edges here and have to be careful when
1984 // we leave a loop not to keep constraints over a dimension that doesn't
1985 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001986 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00001987 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001988 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001989 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001990
1991 // Skip back edges.
1992 if (DT.dominates(SuccBB, BB)) {
1993 isl_set_free(CondSet);
1994 continue;
1995 }
1996
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001997 // Do not adjust the number of dimensions if we enter a boxed loop or are
1998 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001999 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002000 Region *SuccRegion = RI.getRegionFor(SuccBB);
Johannes Doerfert634909c2015-10-04 14:57:41 +00002001 if (SD.isNonAffineSubRegion(SuccRegion, &getRegion()))
2002 while (SuccBBLoop && SuccRegion->contains(SuccBBLoop))
2003 SuccBBLoop = SuccBBLoop->getParentLoop();
2004
2005 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002006
2007 // Check if the edge to SuccBB is a loop entry or exit edge. If so
2008 // adjust the dimensionality accordingly. Lastly, if we leave a loop
2009 // and enter a new one we need to drop the old constraints.
2010 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002011 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002012 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002013 CondSet = isl_set_project_out(CondSet, isl_dim_set,
2014 isl_set_n_dim(CondSet) - LoopDepthDiff,
2015 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002016 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002017 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002018 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002019 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002020 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002021 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002022 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
2023 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002024 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002025 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002026 }
2027
2028 // Set the domain for the successor or merge it with an existing domain in
2029 // case there are multiple paths (without loop back edges) to the
2030 // successor block.
2031 isl_set *&SuccDomain = DomainMap[SuccBB];
2032 if (!SuccDomain)
2033 SuccDomain = CondSet;
2034 else
2035 SuccDomain = isl_set_union(SuccDomain, CondSet);
2036
2037 SuccDomain = isl_set_coalesce(SuccDomain);
Johannes Doerfert634909c2015-10-04 14:57:41 +00002038 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
2039 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002040 }
2041 }
2042}
2043
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002044/// @brief Return the domain for @p BB wrt @p DomainMap.
2045///
2046/// This helper function will lookup @p BB in @p DomainMap but also handle the
2047/// case where @p BB is contained in a non-affine subregion using the region
2048/// tree obtained by @p RI.
2049static __isl_give isl_set *
2050getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
2051 RegionInfo &RI) {
2052 auto DIt = DomainMap.find(BB);
2053 if (DIt != DomainMap.end())
2054 return isl_set_copy(DIt->getSecond());
2055
2056 Region *R = RI.getRegionFor(BB);
2057 while (R->getEntry() == BB)
2058 R = R->getParent();
2059 return getDomainForBlock(R->getEntry(), DomainMap, RI);
2060}
2061
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002062void Scop::propagateDomainConstraints(Region *R) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002063 // Iterate over the region R and propagate the domain constrains from the
2064 // predecessors to the current node. In contrast to the
2065 // buildDomainsWithBranchConstraints function, this one will pull the domain
2066 // information from the predecessors instead of pushing it to the successors.
2067 // Additionally, we assume the domains to be already present in the domain
2068 // map here. However, we iterate again in reverse post order so we know all
2069 // predecessors have been visited before a block or non-affine subregion is
2070 // visited.
2071
2072 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2073 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2074
2075 ReversePostOrderTraversal<Region *> RTraversal(R);
2076 for (auto *RN : RTraversal) {
2077
2078 // Recurse for affine subregions but go on for basic blocks and non-affine
2079 // subregions.
2080 if (RN->isSubRegion()) {
2081 Region *SubRegion = RN->getNodeAs<Region>();
2082 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002083 propagateDomainConstraints(SubRegion);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002084 continue;
2085 }
2086 }
2087
Johannes Doerfertf5673802015-10-01 23:48:18 +00002088 // Get the domain for the current block and check if it was initialized or
2089 // not. The only way it was not is if this block is only reachable via error
2090 // blocks, thus will not be executed under the assumptions we make. Such
2091 // blocks have to be skipped as their predecessors might not have domains
2092 // either. It would not benefit us to compute the domain anyway, only the
2093 // domains of the error blocks that are reachable from non-error blocks
2094 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002095 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002096 isl_set *&Domain = DomainMap[BB];
2097 if (!Domain) {
2098 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2099 << ", it is only reachable from error blocks.\n");
2100 DomainMap.erase(BB);
2101 continue;
2102 }
2103 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
2104
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002105 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2106 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2107
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002108 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2109 for (auto *PredBB : predecessors(BB)) {
2110
2111 // Skip backedges
2112 if (DT.dominates(BB, PredBB))
2113 continue;
2114
2115 isl_set *PredBBDom = nullptr;
2116
2117 // Handle the SCoP entry block with its outside predecessors.
2118 if (!getRegion().contains(PredBB))
2119 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
2120
2121 if (!PredBBDom) {
2122 // Determine the loop depth of the predecessor and adjust its domain to
2123 // the domain of the current block. This can mean we have to:
2124 // o) Drop a dimension if this block is the exit of a loop, not the
2125 // header of a new loop and the predecessor was part of the loop.
2126 // o) Add an unconstrainted new dimension if this block is the header
2127 // of a loop and the predecessor is not part of it.
2128 // o) Drop the information about the innermost loop dimension when the
2129 // predecessor and the current block are surrounded by different
2130 // loops in the same depth.
2131 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2132 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2133 while (BoxedLoops.count(PredBBLoop))
2134 PredBBLoop = PredBBLoop->getParentLoop();
2135
2136 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002137 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002138 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002139 PredBBDom = isl_set_project_out(
2140 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2141 LoopDepthDiff);
2142 else if (PredBBLoopDepth < BBLoopDepth) {
2143 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002144 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002145 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2146 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002147 PredBBDom = isl_set_drop_constraints_involving_dims(
2148 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002149 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002150 }
2151
2152 PredDom = isl_set_union(PredDom, PredBBDom);
2153 }
2154
2155 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002156 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002157
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002158 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002159 addLoopBoundsToHeaderDomain(BBLoop);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002160
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002161 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002162 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002163 IsOptimized = true;
2164 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2165 addAssumption(isl_set_complement(DomPar));
2166 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002167 }
2168}
2169
2170/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2171/// is incremented by one and all other dimensions are equal, e.g.,
2172/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2173/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2174static __isl_give isl_map *
2175createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2176 auto *MapSpace = isl_space_map_from_set(SetSpace);
2177 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2178 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2179 if (u != Dim)
2180 NextIterationMap =
2181 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2182 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2183 C = isl_constraint_set_constant_si(C, 1);
2184 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2185 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2186 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2187 return NextIterationMap;
2188}
2189
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002190void Scop::addLoopBoundsToHeaderDomain(Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002191 int LoopDepth = getRelativeLoopDepth(L);
2192 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002193
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002194 BasicBlock *HeaderBB = L->getHeader();
2195 assert(DomainMap.count(HeaderBB));
2196 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002197
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002198 isl_map *NextIterationMap =
2199 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002200
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002201 isl_set *UnionBackedgeCondition =
2202 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002203
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002204 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2205 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002206
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002207 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002208
2209 // If the latch is only reachable via error statements we skip it.
2210 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2211 if (!LatchBBDom)
2212 continue;
2213
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002214 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002215
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002216 TerminatorInst *TI = LatchBB->getTerminator();
2217 BranchInst *BI = dyn_cast<BranchInst>(TI);
2218 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002219 BackedgeCondition = isl_set_copy(LatchBBDom);
2220 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002221 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002222 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002223 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002224
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002225 // Free the non back edge condition set as we do not need it.
2226 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002227
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002228 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002229 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002230
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002231 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2232 assert(LatchLoopDepth >= LoopDepth);
2233 BackedgeCondition =
2234 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2235 LatchLoopDepth - LoopDepth);
2236 UnionBackedgeCondition =
2237 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002238 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002239
2240 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2241 for (int i = 0; i < LoopDepth; i++)
2242 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2243
2244 isl_set *UnionBackedgeConditionComplement =
2245 isl_set_complement(UnionBackedgeCondition);
2246 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2247 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2248 UnionBackedgeConditionComplement =
2249 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2250 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2251 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2252
2253 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2254 HeaderBBDom = Parts.second;
2255
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002256 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2257 // the bounded assumptions to the context as they are already implied by the
2258 // <nsw> tag.
2259 if (Affinator.hasNSWAddRecForLoop(L)) {
2260 isl_set_free(Parts.first);
2261 return;
2262 }
2263
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002264 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2265 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfert707a4062015-09-20 16:38:19 +00002266 addAssumption(BoundedCtx);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002267}
2268
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002269void Scop::buildAliasChecks(AliasAnalysis &AA) {
2270 if (!PollyUseRuntimeAliasChecks)
2271 return;
2272
2273 if (buildAliasGroups(AA))
2274 return;
2275
2276 // If a problem occurs while building the alias groups we need to delete
2277 // this SCoP and pretend it wasn't valid in the first place. To this end
2278 // we make the assumed context infeasible.
2279 addAssumption(isl_set_empty(getParamSpace()));
2280
2281 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2282 << " could not be created as the number of parameters involved "
2283 "is too high. The SCoP will be "
2284 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2285 "the maximal number of parameters but be advised that the "
2286 "compile time might increase exponentially.\n\n");
2287}
2288
Johannes Doerfert9143d672014-09-27 11:02:39 +00002289bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002290 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002291 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002292 // for all memory accesses inside the SCoP.
2293 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002294 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002295 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002296 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002297 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002298 // if their access domains intersect, otherwise they are in different
2299 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002300 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002301 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002302 // and maximal accesses to each array of a group in read only and non
2303 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002304 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2305
2306 AliasSetTracker AST(AA);
2307
2308 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002309 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002310 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002311
2312 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002313 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002314 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2315 isl_set_free(StmtDomain);
2316 if (StmtDomainEmpty)
2317 continue;
2318
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002319 for (MemoryAccess *MA : Stmt) {
Michael Kruse8d0b7342015-09-25 21:21:00 +00002320 if (MA->isImplicit())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002321 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002322 if (!MA->isRead())
2323 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002324 Instruction *Acc = MA->getAccessInstruction();
2325 PtrToAcc[getPointerOperand(*Acc)] = MA;
2326 AST.add(Acc);
2327 }
2328 }
2329
2330 SmallVector<AliasGroupTy, 4> AliasGroups;
2331 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002332 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002333 continue;
2334 AliasGroupTy AG;
2335 for (auto PR : AS)
2336 AG.push_back(PtrToAcc[PR.getValue()]);
2337 assert(AG.size() > 1 &&
2338 "Alias groups should contain at least two accesses");
2339 AliasGroups.push_back(std::move(AG));
2340 }
2341
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002342 // Split the alias groups based on their domain.
2343 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2344 AliasGroupTy NewAG;
2345 AliasGroupTy &AG = AliasGroups[u];
2346 AliasGroupTy::iterator AGI = AG.begin();
2347 isl_set *AGDomain = getAccessDomain(*AGI);
2348 while (AGI != AG.end()) {
2349 MemoryAccess *MA = *AGI;
2350 isl_set *MADomain = getAccessDomain(MA);
2351 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2352 NewAG.push_back(MA);
2353 AGI = AG.erase(AGI);
2354 isl_set_free(MADomain);
2355 } else {
2356 AGDomain = isl_set_union(AGDomain, MADomain);
2357 AGI++;
2358 }
2359 }
2360 if (NewAG.size() > 1)
2361 AliasGroups.push_back(std::move(NewAG));
2362 isl_set_free(AGDomain);
2363 }
2364
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002365 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002366 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2367 for (AliasGroupTy &AG : AliasGroups) {
2368 NonReadOnlyBaseValues.clear();
2369 ReadOnlyPairs.clear();
2370
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002371 if (AG.size() < 2) {
2372 AG.clear();
2373 continue;
2374 }
2375
Johannes Doerfert13771732014-10-01 12:40:46 +00002376 for (auto II = AG.begin(); II != AG.end();) {
2377 Value *BaseAddr = (*II)->getBaseAddr();
2378 if (HasWriteAccess.count(BaseAddr)) {
2379 NonReadOnlyBaseValues.insert(BaseAddr);
2380 II++;
2381 } else {
2382 ReadOnlyPairs[BaseAddr].insert(*II);
2383 II = AG.erase(II);
2384 }
2385 }
2386
2387 // If we don't have read only pointers check if there are at least two
2388 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002389 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002390 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002391 continue;
2392 }
2393
2394 // If we don't have non read only pointers clear the alias group.
2395 if (NonReadOnlyBaseValues.empty()) {
2396 AG.clear();
2397 continue;
2398 }
2399
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002400 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002401 MinMaxAliasGroups.emplace_back();
2402 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2403 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2404 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2405 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002406
2407 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002408
2409 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002410 for (MemoryAccess *MA : AG)
2411 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002412
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002413 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2414 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002415
2416 // Bail out if the number of values we need to compare is too large.
2417 // This is important as the number of comparisions grows quadratically with
2418 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002419 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2420 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002421 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002422
2423 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002424 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002425 Accesses = isl_union_map_empty(getParamSpace());
2426
2427 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2428 for (MemoryAccess *MA : ReadOnlyPair.second)
2429 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2430
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002431 Valid =
2432 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002433
2434 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002435 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002436 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002437
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002438 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002439}
2440
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002441static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
2442 Loop *L = LI.getLoopFor(R.getEntry());
2443 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2444}
2445
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002446static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2447 ScopDetection &SD) {
2448
2449 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2450
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002451 unsigned MinLD = INT_MAX, MaxLD = 0;
2452 for (BasicBlock *BB : R.blocks()) {
2453 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002454 if (!R.contains(L))
2455 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002456 if (BoxedLoops && BoxedLoops->count(L))
2457 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002458 unsigned LD = L->getLoopDepth();
2459 MinLD = std::min(MinLD, LD);
2460 MaxLD = std::max(MaxLD, LD);
2461 }
2462 }
2463
2464 // Handle the case that there is no loop in the SCoP first.
2465 if (MaxLD == 0)
2466 return 1;
2467
2468 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2469 assert(MaxLD >= MinLD &&
2470 "Maximal loop depth was smaller than mininaml loop depth?");
2471 return MaxLD - MinLD + 1;
2472}
2473
Johannes Doerfert478a7de2015-10-02 13:09:31 +00002474Scop::Scop(Region &R, AccFuncMapType &AccFuncMap, ScopDetection &SD,
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002475 ScalarEvolution &ScalarEvolution, DominatorTree &DT, LoopInfo &LI,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002476 isl_ctx *Context, unsigned MaxLoopDepth)
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002477 : LI(LI), DT(DT), SE(&ScalarEvolution), SD(SD), R(R),
2478 AccFuncMap(AccFuncMap), IsOptimized(false),
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002479 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
2480 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Context(nullptr),
2481 Affinator(this), AssumedContext(nullptr), BoundaryContext(nullptr),
2482 Schedule(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002483
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002484void Scop::init(AliasAnalysis &AA) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002485 buildContext();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002486 buildInvariantEquivalenceClasses();
2487
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002488 buildDomains(&R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002489
Michael Krusecac948e2015-10-02 13:53:07 +00002490 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002491 // Exit early in case there are no executable statements left in this scop.
Michael Krusecac948e2015-10-02 13:53:07 +00002492 simplifySCoP(true);
Michael Kruseafe06702015-10-02 16:33:27 +00002493 if (Stmts.empty())
2494 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002495
Michael Krusecac948e2015-10-02 13:53:07 +00002496 // The ScopStmts now have enough information to initialize themselves.
2497 for (ScopStmt &Stmt : Stmts)
2498 Stmt.init();
2499
2500 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002501 Loop *L = getLoopSurroundingRegion(R, LI);
2502 LoopSchedules[L];
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002503 buildSchedule(&R, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002504 Schedule = LoopSchedules[L].first;
Tobias Grosser75805372011-04-29 06:27:02 +00002505
Tobias Grosser8286b832015-11-02 11:29:32 +00002506 if (isl_set_is_empty(AssumedContext))
2507 return;
2508
2509 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002510 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002511 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002512 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002513 buildBoundaryContext();
2514 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002515 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002516
2517 hoistInvariantLoads();
Michael Krusecac948e2015-10-02 13:53:07 +00002518 simplifySCoP(false);
Tobias Grosser75805372011-04-29 06:27:02 +00002519}
2520
2521Scop::~Scop() {
2522 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002523 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002524 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002525 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002526
Johannes Doerfert96425c22015-08-30 21:13:53 +00002527 for (auto It : DomainMap)
2528 isl_set_free(It.second);
2529
Johannes Doerfertb164c792014-09-18 11:17:17 +00002530 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002531 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002532 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002533 isl_pw_multi_aff_free(MMA.first);
2534 isl_pw_multi_aff_free(MMA.second);
2535 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002536 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002537 isl_pw_multi_aff_free(MMA.first);
2538 isl_pw_multi_aff_free(MMA.second);
2539 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002540 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002541
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002542 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002543 isl_set_free(std::get<2>(IAClass));
Tobias Grosser75805372011-04-29 06:27:02 +00002544}
2545
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002546void Scop::updateAccessDimensionality() {
2547 for (auto &Stmt : *this)
2548 for (auto &Access : Stmt)
2549 Access->updateDimensionality();
2550}
2551
Michael Krusecac948e2015-10-02 13:53:07 +00002552void Scop::simplifySCoP(bool RemoveIgnoredStmts) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002553 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2554 ScopStmt &Stmt = *StmtIt;
Michael Krusecac948e2015-10-02 13:53:07 +00002555 RegionNode *RN = Stmt.isRegionStmt()
2556 ? Stmt.getRegion()->getNode()
2557 : getRegion().getBBNode(Stmt.getBasicBlock());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002558
Johannes Doerferteca9e892015-11-03 16:54:49 +00002559 bool RemoveStmt = StmtIt->isEmpty();
2560 if (!RemoveStmt)
2561 RemoveStmt = isl_set_is_empty(DomainMap[getRegionNodeBasicBlock(RN)]);
2562 if (!RemoveStmt)
2563 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002564
Johannes Doerferteca9e892015-11-03 16:54:49 +00002565 // Remove read only statements only after invariant loop hoisting.
2566 if (!RemoveStmt && !RemoveIgnoredStmts) {
2567 bool OnlyRead = true;
2568 for (MemoryAccess *MA : Stmt) {
2569 if (MA->isRead())
2570 continue;
2571
2572 OnlyRead = false;
2573 break;
2574 }
2575
2576 RemoveStmt = OnlyRead;
2577 }
2578
2579 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00002580 // Remove the statement because it is unnecessary.
2581 if (Stmt.isRegionStmt())
2582 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2583 StmtMap.erase(BB);
2584 else
2585 StmtMap.erase(Stmt.getBasicBlock());
2586
2587 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002588 continue;
2589 }
2590
Michael Krusecac948e2015-10-02 13:53:07 +00002591 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002592 }
2593}
2594
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002595const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2596 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2597 if (!LInst)
2598 return nullptr;
2599
2600 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2601 LInst = cast<LoadInst>(Rep);
2602
2603 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2604 for (auto &IAClass : InvariantEquivClasses)
2605 if (PointerSCEV == std::get<0>(IAClass))
2606 return &IAClass;
2607
2608 return nullptr;
2609}
2610
2611void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2612
2613 // Get the context under which the statement is executed.
2614 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2615 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2616 DomainCtx = isl_set_detect_equalities(DomainCtx);
2617 DomainCtx = isl_set_coalesce(DomainCtx);
2618
2619 // Project out all parameters that relate to loads in the statement. Otherwise
2620 // we could have cyclic dependences on the constraints under which the
2621 // hoisted loads are executed and we could not determine an order in which to
2622 // pre-load them. This happens because not only lower bounds are part of the
2623 // domain but also upper bounds.
2624 for (MemoryAccess *MA : InvMAs) {
2625 Instruction *AccInst = MA->getAccessInstruction();
2626 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00002627 SetVector<Value *> Values;
2628 for (const SCEV *Parameter : Parameters) {
2629 Values.clear();
2630 findValues(Parameter, Values);
2631 if (!Values.count(AccInst))
2632 continue;
2633
2634 if (isl_id *ParamId = getIdForParam(Parameter)) {
2635 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2636 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2637 isl_id_free(ParamId);
2638 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002639 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002640 }
2641 }
2642
2643 for (MemoryAccess *MA : InvMAs) {
2644 // Check for another invariant access that accesses the same location as
2645 // MA and if found consolidate them. Otherwise create a new equivalence
2646 // class at the end of InvariantEquivClasses.
2647 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
2648 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2649
2650 bool Consolidated = false;
2651 for (auto &IAClass : InvariantEquivClasses) {
2652 if (PointerSCEV != std::get<0>(IAClass))
2653 continue;
2654
2655 Consolidated = true;
2656
2657 // Add MA to the list of accesses that are in this class.
2658 auto &MAs = std::get<1>(IAClass);
2659 MAs.push_front(MA);
2660
2661 // Unify the execution context of the class and this statement.
2662 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002663 if (IAClassDomainCtx)
2664 IAClassDomainCtx = isl_set_coalesce(
2665 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
2666 else
2667 IAClassDomainCtx = isl_set_copy(DomainCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002668 break;
2669 }
2670
2671 if (Consolidated)
2672 continue;
2673
2674 // If we did not consolidate MA, thus did not find an equivalence class
2675 // for it, we create a new one.
2676 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
2677 isl_set_copy(DomainCtx));
2678 }
2679
2680 isl_set_free(DomainCtx);
2681}
2682
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002683void Scop::hoistInvariantLoads() {
2684 isl_union_map *Writes = getWrites();
2685 for (ScopStmt &Stmt : *this) {
2686
2687 // TODO: Loads that are not loop carried, hence are in a statement with
2688 // zero iterators, are by construction invariant, though we
Johannes Doerfert09e36972015-10-07 20:17:36 +00002689 // currently "hoist" them anyway. This is necessary because we allow
2690 // them to be treated as parameters (e.g., in conditions) and our code
2691 // generation would otherwise use the old value.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002692
Johannes Doerfert8930f482015-10-02 14:51:00 +00002693 BasicBlock *BB = Stmt.isBlockStmt() ? Stmt.getBasicBlock()
2694 : Stmt.getRegion()->getEntry();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002695 isl_set *Domain = Stmt.getDomain();
2696 MemoryAccessList InvMAs;
2697
2698 for (MemoryAccess *MA : Stmt) {
2699 if (MA->isImplicit() || MA->isWrite() || !MA->isAffine())
2700 continue;
2701
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002702 // Skip accesses that have an invariant base pointer which is defined but
2703 // not loaded inside the SCoP. This can happened e.g., if a readnone call
2704 // returns a pointer that is used as a base address. However, as we want
2705 // to hoist indirect pointers, we allow the base pointer to be defined in
Johannes Doerfert654c3282015-10-21 22:14:57 +00002706 // the region if it is also a memory access. Each ScopArrayInfo object
2707 // that has a base pointer origin has a base pointer that is loaded and
2708 // that it is invariant, thus it will be hoisted too. However, if there is
Tobias Grosser27e19a02015-10-25 12:05:14 +00002709 // no base pointer origin we check that the base pointer is defined
Johannes Doerfert654c3282015-10-21 22:14:57 +00002710 // outside the region.
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002711 const ScopArrayInfo *SAI = MA->getScopArrayInfo();
Johannes Doerfert654c3282015-10-21 22:14:57 +00002712 while (auto *BasePtrOriginSAI = SAI->getBasePtrOriginSAI())
2713 SAI = BasePtrOriginSAI;
2714
2715 if (auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr()))
2716 if (R.contains(BasePtrInst))
2717 continue;
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002718
Johannes Doerfert8930f482015-10-02 14:51:00 +00002719 // Skip accesses in non-affine subregions as they might not be executed
2720 // under the same condition as the entry of the non-affine subregion.
2721 if (BB != MA->getAccessInstruction()->getParent())
2722 continue;
2723
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002724 isl_map *AccessRelation = MA->getAccessRelation();
Johannes Doerfertb864c2c2015-10-18 19:50:18 +00002725
2726 // Skip accesses that have an empty access relation. These can be caused
2727 // by multiple offsets with a type cast in-between that cause the overall
2728 // byte offset to be not divisible by the new types sizes.
2729 if (isl_map_is_empty(AccessRelation)) {
2730 isl_map_free(AccessRelation);
2731 continue;
2732 }
2733
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002734 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
2735 Stmt.getNumIterators())) {
2736 isl_map_free(AccessRelation);
2737 continue;
2738 }
2739
2740 AccessRelation =
2741 isl_map_intersect_domain(AccessRelation, isl_set_copy(Domain));
2742 isl_set *AccessRange = isl_map_range(AccessRelation);
2743
2744 isl_union_map *Written = isl_union_map_intersect_range(
2745 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
2746 bool IsWritten = !isl_union_map_is_empty(Written);
2747 isl_union_map_free(Written);
2748
2749 if (IsWritten)
2750 continue;
2751
2752 InvMAs.push_front(MA);
2753 }
2754
2755 // We inserted invariant accesses always in the front but need them to be
2756 // sorted in a "natural order". The statements are already sorted in reverse
2757 // post order and that suffices for the accesses too. The reason we require
2758 // an order in the first place is the dependences between invariant loads
2759 // that can be caused by indirect loads.
2760 InvMAs.reverse();
2761
2762 // Transfer the memory access from the statement to the SCoP.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002763 Stmt.removeMemoryAccesses(InvMAs);
2764 addInvariantLoads(Stmt, InvMAs);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002765
2766 isl_set_free(Domain);
2767 }
2768 isl_union_map_free(Writes);
2769
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002770 auto &ScopRIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert09e36972015-10-07 20:17:36 +00002771 // Check required invariant loads that were tagged during SCoP detection.
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002772 for (LoadInst *LI : ScopRIL) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00002773 assert(LI && getRegion().contains(LI));
2774 ScopStmt *Stmt = getStmtForBasicBlock(LI->getParent());
2775 if (Stmt && Stmt->lookupAccessesFor(LI) != nullptr) {
2776 DEBUG(dbgs() << "\n\nWARNING: Load (" << *LI
2777 << ") is required to be invariant but was not marked as "
2778 "such. SCoP for "
2779 << getRegion() << " will be dropped\n\n");
2780 addAssumption(isl_set_empty(getParamSpace()));
2781 return;
2782 }
2783 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002784}
2785
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002786const ScopArrayInfo *
2787Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002788 ArrayRef<const SCEV *> Sizes,
2789 ScopArrayInfo::ARRAYKIND Kind) {
2790 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002791 if (!SAI) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002792 SAI.reset(
2793 new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, Kind, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002794 } else {
Tobias Grosser8286b832015-11-02 11:29:32 +00002795 // In case of mismatching array sizes, we bail out by setting the run-time
2796 // context to false.
2797 if (!SAI->updateSizes(Sizes))
2798 addAssumption(isl_set_empty(getParamSpace()));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002799 }
Tobias Grosserab671442015-05-23 05:58:27 +00002800 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002801}
2802
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002803const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
2804 ScopArrayInfo::ARRAYKIND Kind) {
2805 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002806 assert(SAI && "No ScopArrayInfo available for this base pointer");
2807 return SAI;
2808}
2809
Tobias Grosser74394f02013-01-14 22:40:23 +00002810std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002811std::string Scop::getAssumedContextStr() const {
2812 return stringFromIslObj(AssumedContext);
2813}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002814std::string Scop::getBoundaryContextStr() const {
2815 return stringFromIslObj(BoundaryContext);
2816}
Tobias Grosser75805372011-04-29 06:27:02 +00002817
2818std::string Scop::getNameStr() const {
2819 std::string ExitName, EntryName;
2820 raw_string_ostream ExitStr(ExitName);
2821 raw_string_ostream EntryStr(EntryName);
2822
Tobias Grosserf240b482014-01-09 10:42:15 +00002823 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002824 EntryStr.str();
2825
2826 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00002827 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002828 ExitStr.str();
2829 } else
2830 ExitName = "FunctionExit";
2831
2832 return EntryName + "---" + ExitName;
2833}
2834
Tobias Grosser74394f02013-01-14 22:40:23 +00002835__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00002836__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002837 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00002838}
2839
Tobias Grossere86109f2013-10-29 21:05:49 +00002840__isl_give isl_set *Scop::getAssumedContext() const {
2841 return isl_set_copy(AssumedContext);
2842}
2843
Johannes Doerfert43788c52015-08-20 05:58:56 +00002844__isl_give isl_set *Scop::getRuntimeCheckContext() const {
2845 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002846 RuntimeCheckContext =
2847 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
2848 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002849 return RuntimeCheckContext;
2850}
2851
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002852bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002853 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002854 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002855 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
2856 isl_set_free(RuntimeCheckContext);
2857 return IsFeasible;
2858}
2859
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002860void Scop::addAssumption(__isl_take isl_set *Set) {
2861 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00002862 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002863}
2864
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002865__isl_give isl_set *Scop::getBoundaryContext() const {
2866 return isl_set_copy(BoundaryContext);
2867}
2868
Tobias Grosser75805372011-04-29 06:27:02 +00002869void Scop::printContext(raw_ostream &OS) const {
2870 OS << "Context:\n";
2871
2872 if (!Context) {
2873 OS.indent(4) << "n/a\n\n";
2874 return;
2875 }
2876
2877 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00002878
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002879 OS.indent(4) << "Assumed Context:\n";
2880 if (!AssumedContext) {
2881 OS.indent(4) << "n/a\n\n";
2882 return;
2883 }
2884
2885 OS.indent(4) << getAssumedContextStr() << "\n";
2886
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002887 OS.indent(4) << "Boundary Context:\n";
2888 if (!BoundaryContext) {
2889 OS.indent(4) << "n/a\n\n";
2890 return;
2891 }
2892
2893 OS.indent(4) << getBoundaryContextStr() << "\n";
2894
Tobias Grosser083d3d32014-06-28 08:59:45 +00002895 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00002896 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00002897 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
2898 }
Tobias Grosser75805372011-04-29 06:27:02 +00002899}
2900
Johannes Doerfertb164c792014-09-18 11:17:17 +00002901void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002902 int noOfGroups = 0;
2903 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002904 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002905 noOfGroups += 1;
2906 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002907 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002908 }
2909
Tobias Grosserbb853c22015-07-25 12:31:03 +00002910 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00002911 if (MinMaxAliasGroups.empty()) {
2912 OS.indent(8) << "n/a\n";
2913 return;
2914 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002915
Tobias Grosserbb853c22015-07-25 12:31:03 +00002916 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002917
2918 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002919 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002920 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002921 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002922 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2923 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002924 }
2925 OS << " ]]\n";
2926 }
2927
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002928 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002929 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00002930 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002931 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002932 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2933 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002934 }
2935 OS << " ]]\n";
2936 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002937 }
2938}
2939
Tobias Grosser75805372011-04-29 06:27:02 +00002940void Scop::printStatements(raw_ostream &OS) const {
2941 OS << "Statements {\n";
2942
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002943 for (const ScopStmt &Stmt : *this)
2944 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00002945
2946 OS.indent(4) << "}\n";
2947}
2948
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002949void Scop::printArrayInfo(raw_ostream &OS) const {
2950 OS << "Arrays {\n";
2951
Tobias Grosserab671442015-05-23 05:58:27 +00002952 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002953 Array.second->print(OS);
2954
2955 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002956
2957 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
2958
2959 for (auto &Array : arrays())
2960 Array.second->print(OS, /* SizeAsPwAff */ true);
2961
2962 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002963}
2964
Tobias Grosser75805372011-04-29 06:27:02 +00002965void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00002966 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
2967 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00002968 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00002969 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002970 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002971 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002972 const auto &MAs = std::get<1>(IAClass);
2973 if (MAs.empty()) {
2974 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002975 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002976 MAs.front()->print(OS);
2977 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002978 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002979 }
2980 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00002981 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002982 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002983 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00002984 printStatements(OS.indent(4));
2985}
2986
2987void Scop::dump() const { print(dbgs()); }
2988
Tobias Grosser9a38ab82011-11-08 15:41:03 +00002989isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00002990
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002991__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
2992 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00002993}
2994
Tobias Grosser808cd692015-07-14 09:33:13 +00002995__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002996 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002997
Tobias Grosser808cd692015-07-14 09:33:13 +00002998 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002999 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003000
3001 return Domain;
3002}
3003
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003004__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003005 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003006
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003007 for (ScopStmt &Stmt : *this) {
3008 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003009 if (!MA->isMustWrite())
3010 continue;
3011
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003012 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003013 isl_map *AccessDomain = MA->getAccessRelation();
3014 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3015 Write = isl_union_map_add_map(Write, AccessDomain);
3016 }
3017 }
3018 return isl_union_map_coalesce(Write);
3019}
3020
3021__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003022 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003023
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003024 for (ScopStmt &Stmt : *this) {
3025 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003026 if (!MA->isMayWrite())
3027 continue;
3028
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003029 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003030 isl_map *AccessDomain = MA->getAccessRelation();
3031 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3032 Write = isl_union_map_add_map(Write, AccessDomain);
3033 }
3034 }
3035 return isl_union_map_coalesce(Write);
3036}
3037
Tobias Grosser37eb4222014-02-20 21:43:54 +00003038__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003039 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003040
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003041 for (ScopStmt &Stmt : *this) {
3042 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00003043 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00003044 continue;
3045
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003046 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00003047 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00003048 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3049 Write = isl_union_map_add_map(Write, AccessDomain);
3050 }
3051 }
3052 return isl_union_map_coalesce(Write);
3053}
3054
3055__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003056 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003057
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003058 for (ScopStmt &Stmt : *this) {
3059 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00003060 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00003061 continue;
3062
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003063 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00003064 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00003065
3066 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3067 Read = isl_union_map_add_map(Read, AccessDomain);
3068 }
3069 }
3070 return isl_union_map_coalesce(Read);
3071}
3072
Tobias Grosser808cd692015-07-14 09:33:13 +00003073__isl_give isl_union_map *Scop::getSchedule() const {
3074 auto Tree = getScheduleTree();
3075 auto S = isl_schedule_get_map(Tree);
3076 isl_schedule_free(Tree);
3077 return S;
3078}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003079
Tobias Grosser808cd692015-07-14 09:33:13 +00003080__isl_give isl_schedule *Scop::getScheduleTree() const {
3081 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3082 getDomains());
3083}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003084
Tobias Grosser808cd692015-07-14 09:33:13 +00003085void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3086 auto *S = isl_schedule_from_domain(getDomains());
3087 S = isl_schedule_insert_partial_schedule(
3088 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3089 isl_schedule_free(Schedule);
3090 Schedule = S;
3091}
3092
3093void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3094 isl_schedule_free(Schedule);
3095 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003096}
3097
3098bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3099 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003100 for (ScopStmt &Stmt : *this) {
3101 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003102 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3103 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3104
3105 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3106 isl_union_set_free(StmtDomain);
3107 isl_union_set_free(NewStmtDomain);
3108 continue;
3109 }
3110
3111 Changed = true;
3112
3113 isl_union_set_free(StmtDomain);
3114 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3115
3116 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003117 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003118 isl_union_set_free(NewStmtDomain);
3119 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003120 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003121 }
3122 isl_union_set_free(Domain);
3123 return Changed;
3124}
3125
Tobias Grosser75805372011-04-29 06:27:02 +00003126ScalarEvolution *Scop::getSE() const { return SE; }
3127
Johannes Doerfertf5673802015-10-01 23:48:18 +00003128bool Scop::isIgnored(RegionNode *RN) {
3129 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser75805372011-04-29 06:27:02 +00003130
Johannes Doerfertf5673802015-10-01 23:48:18 +00003131 // Check if there are accesses contained.
3132 bool ContainsAccesses = false;
3133 if (!RN->isSubRegion())
3134 ContainsAccesses = getAccessFunctions(BB);
3135 else
3136 for (BasicBlock *RBB : RN->getNodeAs<Region>()->blocks())
3137 ContainsAccesses |= (getAccessFunctions(RBB) != nullptr);
3138 if (!ContainsAccesses)
3139 return true;
3140
3141 // Check for reachability via non-error blocks.
3142 if (!DomainMap.count(BB))
3143 return true;
3144
3145 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003146 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003147 return true;
3148
3149 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003150}
3151
Tobias Grosser808cd692015-07-14 09:33:13 +00003152struct MapToDimensionDataTy {
3153 int N;
3154 isl_union_pw_multi_aff *Res;
3155};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003156
Tobias Grosser808cd692015-07-14 09:33:13 +00003157// @brief Create a function that maps the elements of 'Set' to its N-th
3158// dimension.
3159//
3160// The result is added to 'User->Res'.
3161//
3162// @param Set The input set.
3163// @param N The dimension to map to.
3164//
3165// @returns Zero if no error occurred, non-zero otherwise.
3166static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3167 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3168 int Dim;
3169 isl_space *Space;
3170 isl_pw_multi_aff *PMA;
3171
3172 Dim = isl_set_dim(Set, isl_dim_set);
3173 Space = isl_set_get_space(Set);
3174 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3175 Dim - Data->N);
3176 if (Data->N > 1)
3177 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3178 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3179
3180 isl_set_free(Set);
3181
3182 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003183}
3184
Tobias Grosser808cd692015-07-14 09:33:13 +00003185// @brief Create a function that maps the elements of Domain to their Nth
3186// dimension.
3187//
3188// @param Domain The set of elements to map.
3189// @param N The dimension to map to.
3190static __isl_give isl_multi_union_pw_aff *
3191mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003192 if (N <= 0 || isl_union_set_is_empty(Domain)) {
3193 isl_union_set_free(Domain);
3194 return nullptr;
3195 }
3196
Tobias Grosser808cd692015-07-14 09:33:13 +00003197 struct MapToDimensionDataTy Data;
3198 isl_space *Space;
3199
3200 Space = isl_union_set_get_space(Domain);
3201 Data.N = N;
3202 Data.Res = isl_union_pw_multi_aff_empty(Space);
3203 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
3204 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
3205
3206 isl_union_set_free(Domain);
3207 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3208}
3209
Michael Kruse9d080092015-09-11 21:41:48 +00003210ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003211 ScopStmt *Stmt;
3212 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003213 Stmts.emplace_back(*this, *BB);
Tobias Grosser808cd692015-07-14 09:33:13 +00003214 Stmt = &Stmts.back();
3215 StmtMap[BB] = Stmt;
3216 } else {
3217 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003218 Stmts.emplace_back(*this, *R);
Tobias Grosser808cd692015-07-14 09:33:13 +00003219 Stmt = &Stmts.back();
3220 for (BasicBlock *BB : R->blocks())
3221 StmtMap[BB] = Stmt;
3222 }
3223 return Stmt;
3224}
3225
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003226void Scop::buildSchedule(
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003227 Region *R,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003228 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00003229
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003230 if (SD.isNonAffineSubRegion(R, &getRegion())) {
Johannes Doerfertc6987c12015-09-26 13:41:43 +00003231 Loop *L = getLoopSurroundingRegion(*R, LI);
3232 auto &LSchedulePair = LoopSchedules[L];
Michael Krusecac948e2015-10-02 13:53:07 +00003233 ScopStmt *Stmt = getStmtForBasicBlock(R->getEntry());
Michael Kruseafe06702015-10-02 16:33:27 +00003234 isl_set *Domain = Stmt->getDomain();
Michael Krusecac948e2015-10-02 13:53:07 +00003235 auto *UDomain = isl_union_set_from_set(Domain);
3236 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003237 LSchedulePair.first = StmtSchedule;
3238 return;
3239 }
3240
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003241 ReversePostOrderTraversal<Region *> RTraversal(R);
3242 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00003243
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003244 if (RN->isSubRegion()) {
3245 Region *SubRegion = RN->getNodeAs<Region>();
3246 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003247 buildSchedule(SubRegion, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003248 continue;
3249 }
Tobias Grosser75805372011-04-29 06:27:02 +00003250 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003251
3252 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert30c22652015-10-18 21:17:11 +00003253 if (!getRegion().contains(L))
3254 L = getLoopSurroundingRegion(getRegion(), LI);
3255
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003256 int LD = getRelativeLoopDepth(L);
3257 auto &LSchedulePair = LoopSchedules[L];
3258 LSchedulePair.second += getNumBlocksInRegionNode(RN);
3259
Michael Krusecac948e2015-10-02 13:53:07 +00003260 BasicBlock *BB = getRegionNodeBasicBlock(RN);
3261 ScopStmt *Stmt = getStmtForBasicBlock(BB);
3262 if (Stmt) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003263 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3264 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
3265 LSchedulePair.first =
3266 combineInSequence(LSchedulePair.first, StmtSchedule);
3267 }
3268
3269 unsigned NumVisited = LSchedulePair.second;
3270 while (L && NumVisited == L->getNumBlocks()) {
3271 auto *LDomain = isl_schedule_get_domain(LSchedulePair.first);
3272 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
3273 LSchedulePair.first =
3274 isl_schedule_insert_partial_schedule(LSchedulePair.first, MUPA);
3275
3276 auto *PL = L->getParentLoop();
Johannes Doerfertdca28372015-11-03 00:28:07 +00003277
3278 // Either we have a proper loop and we also build a schedule for the
3279 // parent loop or we have a infinite loop that does not have a proper
3280 // parent loop. In the former case this conditional will be skipped, in
3281 // the latter case however we will break here as we do not build a domain
3282 // nor a schedule for a infinite loop.
3283 assert(LoopSchedules.count(PL) || LSchedulePair.first == nullptr);
3284 if (!LoopSchedules.count(PL))
3285 break;
3286
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003287 auto &PSchedulePair = LoopSchedules[PL];
3288 PSchedulePair.first =
3289 combineInSequence(PSchedulePair.first, LSchedulePair.first);
3290 PSchedulePair.second += NumVisited;
3291
3292 L = PL;
3293 NumVisited = PSchedulePair.second;
3294 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003295 }
Tobias Grosser75805372011-04-29 06:27:02 +00003296}
3297
Johannes Doerfert7c494212014-10-31 23:13:39 +00003298ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003299 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003300 if (StmtMapIt == StmtMap.end())
3301 return nullptr;
3302 return StmtMapIt->second;
3303}
3304
Johannes Doerfert96425c22015-08-30 21:13:53 +00003305int Scop::getRelativeLoopDepth(const Loop *L) const {
3306 Loop *OuterLoop =
3307 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3308 if (!OuterLoop)
3309 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003310 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3311}
3312
Michael Krused868b5d2015-09-10 15:25:24 +00003313void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003314 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003315
3316 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3317 // true, are not modeled as ordinary PHI nodes as they are not part of the
3318 // region. However, we model the operands in the predecessor blocks that are
3319 // part of the region as regular scalar accesses.
3320
3321 // If we can synthesize a PHI we can skip it, however only if it is in
3322 // the region. If it is not it can only be in the exit block of the region.
3323 // In this case we model the operands but not the PHI itself.
3324 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3325 return;
3326
3327 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3328 // detection. Hence, the PHI is a load of a new memory location in which the
3329 // incoming value was written at the end of the incoming basic block.
3330 bool OnlyNonAffineSubRegionOperands = true;
3331 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3332 Value *Op = PHI->getIncomingValue(u);
3333 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3334
3335 // Do not build scalar dependences inside a non-affine subregion.
3336 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3337 continue;
3338
3339 OnlyNonAffineSubRegionOperands = false;
3340
3341 if (!R.contains(OpBB))
3342 continue;
3343
3344 Instruction *OpI = dyn_cast<Instruction>(Op);
3345 if (OpI) {
3346 BasicBlock *OpIBB = OpI->getParent();
3347 // As we pretend there is a use (or more precise a write) of OpI in OpBB
3348 // we have to insert a scalar dependence from the definition of OpI to
3349 // OpBB if the definition is not in OpBB.
Michael Kruse668af712015-10-15 14:45:48 +00003350 if (scop->getStmtForBasicBlock(OpIBB) !=
3351 scop->getStmtForBasicBlock(OpBB)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003352 addScalarReadAccess(OpI, PHI, OpBB);
3353 addScalarWriteAccess(OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003354 }
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003355 } else if (ModelReadOnlyScalars && !isa<Constant>(Op)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003356 addScalarReadAccess(Op, PHI, OpBB);
Michael Kruse7bf39442015-09-10 12:46:52 +00003357 }
3358
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003359 addPHIWriteAccess(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003360 }
3361
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003362 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3363 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003364 }
3365}
3366
Michael Krused868b5d2015-09-10 15:25:24 +00003367bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
3368 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003369 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
3370 if (isIgnoredIntrinsic(Inst))
3371 return false;
3372
3373 bool AnyCrossStmtUse = false;
3374 BasicBlock *ParentBB = Inst->getParent();
3375
3376 for (User *U : Inst->users()) {
3377 Instruction *UI = dyn_cast<Instruction>(U);
3378
3379 // Ignore the strange user
3380 if (UI == 0)
3381 continue;
3382
3383 BasicBlock *UseParent = UI->getParent();
3384
Tobias Grosserbaffa092015-10-24 20:55:27 +00003385 // Ignore basic block local uses. A value that is defined in a scop, but
3386 // used in a PHI node in the same basic block does not count as basic block
3387 // local, as for such cases a control flow edge is passed between definition
3388 // and use.
3389 if (UseParent == ParentBB && !isa<PHINode>(UI))
Michael Kruse7bf39442015-09-10 12:46:52 +00003390 continue;
3391
Michael Krusef714d472015-11-05 13:18:43 +00003392 // Uses by PHI nodes in the entry node count as external uses in case the
3393 // use is through an incoming block that is itself not contained in the
3394 // region.
3395 if (R->getEntry() == UseParent) {
3396 if (auto *PHI = dyn_cast<PHINode>(UI)) {
3397 bool ExternalUse = false;
3398 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
3399 if (PHI->getIncomingValue(i) == Inst &&
3400 !R->contains(PHI->getIncomingBlock(i))) {
3401 ExternalUse = true;
3402 break;
3403 }
3404 }
3405
3406 if (ExternalUse) {
3407 AnyCrossStmtUse = true;
3408 continue;
3409 }
3410 }
3411 }
3412
Michael Kruse7bf39442015-09-10 12:46:52 +00003413 // Do not build scalar dependences inside a non-affine subregion.
3414 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
3415 continue;
3416
Michael Kruse01cb3792015-10-17 21:07:08 +00003417 // Check for PHI nodes in the region exit and skip them, if they will be
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003418 // modeled as PHI nodes.
Michael Kruse01cb3792015-10-17 21:07:08 +00003419 //
3420 // PHI nodes in the region exit that have more than two incoming edges need
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003421 // to be modeled as PHI-Nodes to correctly model the fact that depending on
3422 // the control flow a different value will be assigned to the PHI node. In
3423 // case this is the case, there is no need to create an additional normal
3424 // scalar dependence. Hence, bail out before we register an "out-of-region"
3425 // use for this definition.
Michael Kruse01cb3792015-10-17 21:07:08 +00003426 if (isa<PHINode>(UI) && UI->getParent() == R->getExit() &&
3427 !R->getExitingBlock())
3428 continue;
3429
Michael Kruse7bf39442015-09-10 12:46:52 +00003430 // Check whether or not the use is in the SCoP.
Tobias Grosserc73d8b02015-10-23 22:36:22 +00003431 if (!R->contains(UseParent)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003432 AnyCrossStmtUse = true;
3433 continue;
3434 }
3435
3436 // If the instruction can be synthesized and the user is in the region
3437 // we do not need to add scalar dependences.
3438 if (canSynthesizeInst)
3439 continue;
3440
3441 // No need to translate these scalar dependences into polyhedral form,
3442 // because synthesizable scalars can be generated by the code generator.
3443 if (canSynthesize(UI, LI, SE, R))
3444 continue;
3445
3446 // Skip PHI nodes in the region as they handle their operands on their own.
3447 if (isa<PHINode>(UI))
3448 continue;
3449
3450 // Now U is used in another statement.
3451 AnyCrossStmtUse = true;
3452
3453 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00003454 // Use the def instruction as base address of the MemoryAccess, so that it
3455 // will become the name of the scalar access in the polyhedral form.
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003456 addScalarReadAccess(Inst, UI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003457 }
3458
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003459 if (ModelReadOnlyScalars && !isa<PHINode>(Inst)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003460 for (Value *Op : Inst->operands()) {
3461 if (canSynthesize(Op, LI, SE, R))
3462 continue;
3463
3464 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
3465 if (R->contains(OpInst))
3466 continue;
3467
3468 if (isa<Constant>(Op))
3469 continue;
3470
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003471 addScalarReadAccess(Op, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003472 }
3473 }
3474
3475 return AnyCrossStmtUse;
3476}
3477
3478extern MapInsnToMemAcc InsnToMemAcc;
3479
Michael Krusee2bccbb2015-09-18 19:59:43 +00003480void ScopInfo::buildMemoryAccess(
3481 Instruction *Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003482 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3483 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003484 unsigned Size;
3485 Type *SizeType;
3486 Value *Val;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003487 enum MemoryAccess::AccessType Type;
Michael Kruse7bf39442015-09-10 12:46:52 +00003488
3489 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
3490 SizeType = Load->getType();
3491 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003492 Type = MemoryAccess::READ;
Michael Kruse7bf39442015-09-10 12:46:52 +00003493 Val = Load;
3494 } else {
3495 StoreInst *Store = cast<StoreInst>(Inst);
3496 SizeType = Store->getValueOperand()->getType();
3497 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003498 Type = MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003499 Val = Store->getValueOperand();
3500 }
3501
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003502 auto Address = getPointerOperand(*Inst);
3503
3504 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003505 const SCEVUnknown *BasePointer =
3506 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3507
3508 assert(BasePointer && "Could not find base pointer");
3509 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
3510
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003511 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3512 auto NewAddress = Address;
3513 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3514 auto Src = BitCast->getOperand(0);
3515 auto SrcTy = Src->getType();
3516 auto DstTy = BitCast->getType();
3517 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3518 NewAddress = Src;
3519 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003520
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003521 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3522 std::vector<const SCEV *> Subscripts;
3523 std::vector<int> Sizes;
3524 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3525 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003526
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003527 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003528
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003529 bool AllAffineSubcripts = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003530 for (auto Subscript : Subscripts) {
3531 InvariantLoadsSetTy AccessILS;
3532 AllAffineSubcripts =
3533 isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS);
3534
3535 for (LoadInst *LInst : AccessILS)
3536 if (!ScopRIL.count(LInst))
3537 AllAffineSubcripts = false;
3538
3539 if (!AllAffineSubcripts)
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003540 break;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003541 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003542
3543 if (AllAffineSubcripts && Sizes.size() > 0) {
3544 for (auto V : Sizes)
3545 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3546 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003547 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003548 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003549
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003550 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3551 Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00003552 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003553 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003554 }
3555 }
3556
Michael Kruse7bf39442015-09-10 12:46:52 +00003557 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003558 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003559 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3560 AccItr->second.DelinearizedSubscripts,
3561 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003562 return;
3563 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003564
3565 // Check if the access depends on a loop contained in a non-affine subregion.
3566 bool isVariantInNonAffineLoop = false;
3567 if (BoxedLoops) {
3568 SetVector<const Loop *> Loops;
3569 findLoops(AccessFunction, Loops);
3570 for (const Loop *L : Loops)
3571 if (BoxedLoops->count(L))
3572 isVariantInNonAffineLoop = true;
3573 }
3574
Johannes Doerfert09e36972015-10-07 20:17:36 +00003575 InvariantLoadsSetTy AccessILS;
3576 bool IsAffine =
3577 !isVariantInNonAffineLoop &&
3578 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3579
3580 for (LoadInst *LInst : AccessILS)
3581 if (!ScopRIL.count(LInst))
3582 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003583
Michael Krusecaac2b62015-09-26 15:51:44 +00003584 // FIXME: Size of the number of bytes of an array element, not the number of
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003585 // elements as probably intended here.
Tobias Grossera43b6e92015-09-27 17:54:50 +00003586 const SCEV *SizeSCEV =
3587 SE->getConstant(TD->getIntPtrType(Inst->getContext()), Size);
Michael Kruse7bf39442015-09-10 12:46:52 +00003588
Michael Krusee2bccbb2015-09-18 19:59:43 +00003589 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3590 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003591
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003592 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, IsAffine,
3593 ArrayRef<const SCEV *>(AccessFunction),
3594 ArrayRef<const SCEV *>(SizeSCEV), Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003595}
3596
Michael Krused868b5d2015-09-10 15:25:24 +00003597void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003598
3599 if (SD->isNonAffineSubRegion(&SR, &R)) {
3600 for (BasicBlock *BB : SR.blocks())
3601 buildAccessFunctions(R, *BB, &SR);
3602 return;
3603 }
3604
3605 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3606 if (I->isSubRegion())
3607 buildAccessFunctions(R, *I->getNodeAs<Region>());
3608 else
3609 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
3610}
3611
Michael Krusecac948e2015-10-02 13:53:07 +00003612void ScopInfo::buildStmts(Region &SR) {
3613 Region *R = getRegion();
3614
3615 if (SD->isNonAffineSubRegion(&SR, R)) {
3616 scop->addScopStmt(nullptr, &SR);
3617 return;
3618 }
3619
3620 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3621 if (I->isSubRegion())
3622 buildStmts(*I->getNodeAs<Region>());
3623 else
3624 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
3625}
3626
Michael Krused868b5d2015-09-10 15:25:24 +00003627void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
3628 Region *NonAffineSubRegion,
3629 bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003630 Loop *L = LI->getLoopFor(&BB);
3631
3632 // The set of loops contained in non-affine subregions that are part of R.
3633 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3634
Johannes Doerfert09e36972015-10-07 20:17:36 +00003635 // The set of loads that are required to be invariant.
3636 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
3637
Michael Kruse7bf39442015-09-10 12:46:52 +00003638 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00003639 Instruction *Inst = &*I;
Michael Kruse7bf39442015-09-10 12:46:52 +00003640
3641 PHINode *PHI = dyn_cast<PHINode>(Inst);
3642 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003643 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003644
3645 // For the exit block we stop modeling after the last PHI node.
3646 if (!PHI && IsExitBlock)
3647 break;
3648
Johannes Doerfert09e36972015-10-07 20:17:36 +00003649 // TODO: At this point we only know that elements of ScopRIL have to be
3650 // invariant and will be hoisted for the SCoP to be processed. Though,
3651 // there might be other invariant accesses that will be hoisted and
3652 // that would allow to make a non-affine access affine.
Michael Kruse7bf39442015-09-10 12:46:52 +00003653 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
Johannes Doerfert09e36972015-10-07 20:17:36 +00003654 buildMemoryAccess(Inst, L, &R, BoxedLoops, ScopRIL);
Michael Kruse7bf39442015-09-10 12:46:52 +00003655
3656 if (isIgnoredIntrinsic(Inst))
3657 continue;
3658
Johannes Doerfert09e36972015-10-07 20:17:36 +00003659 // Do not build scalar dependences for required invariant loads as we will
3660 // hoist them later on anyway or drop the SCoP if we cannot.
3661 if (ScopRIL.count(dyn_cast<LoadInst>(Inst)))
3662 continue;
3663
Michael Kruse7bf39442015-09-10 12:46:52 +00003664 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00003665 if (!isa<StoreInst>(Inst))
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003666 addScalarWriteAccess(Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003667 }
3668 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003669}
Michael Kruse7bf39442015-09-10 12:46:52 +00003670
Michael Kruse2d0ece92015-09-24 11:41:21 +00003671void ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3672 MemoryAccess::AccessType Type,
3673 Value *BaseAddress, unsigned ElemBytes,
3674 bool Affine, Value *AccessValue,
3675 ArrayRef<const SCEV *> Subscripts,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003676 ArrayRef<const SCEV *> Sizes,
3677 MemoryAccess::AccessOrigin Origin) {
Michael Krusecac948e2015-10-02 13:53:07 +00003678 ScopStmt *Stmt = scop->getStmtForBasicBlock(BB);
3679
3680 // Do not create a memory access for anything not in the SCoP. It would be
3681 // ignored anyway.
3682 if (!Stmt)
3683 return;
3684
Michael Krusee2bccbb2015-09-18 19:59:43 +00003685 AccFuncSetType &AccList = AccFuncMap[BB];
Michael Krusee2bccbb2015-09-18 19:59:43 +00003686 Value *BaseAddr = BaseAddress;
3687 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3688
Michael Krusecac948e2015-10-02 13:53:07 +00003689 bool isApproximated =
3690 Stmt->isRegionStmt() && (Stmt->getRegion()->getEntry() != BB);
3691 if (isApproximated && Type == MemoryAccess::MUST_WRITE)
3692 Type = MemoryAccess::MAY_WRITE;
3693
Tobias Grosserf1bfd752015-11-05 20:15:37 +00003694 AccList.emplace_back(Stmt, Inst, Type, BaseAddress, ElemBytes, Affine,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003695 Subscripts, Sizes, AccessValue, Origin, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00003696 Stmt->addAccess(&AccList.back());
Michael Kruse7bf39442015-09-10 12:46:52 +00003697}
3698
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003699void ScopInfo::addExplicitAccess(
3700 Instruction *MemAccInst, MemoryAccess::AccessType Type, Value *BaseAddress,
3701 unsigned ElemBytes, bool IsAffine, ArrayRef<const SCEV *> Subscripts,
3702 ArrayRef<const SCEV *> Sizes, Value *AccessValue) {
3703 assert(isa<LoadInst>(MemAccInst) || isa<StoreInst>(MemAccInst));
3704 assert(isa<LoadInst>(MemAccInst) == (Type == MemoryAccess::READ));
3705 addMemoryAccess(MemAccInst->getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003706 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
3707 MemoryAccess::EXPLICIT);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003708}
3709void ScopInfo::addScalarWriteAccess(Instruction *Value) {
3710 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
3711 true, Value, ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003712 ArrayRef<const SCEV *>(), MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003713}
3714void ScopInfo::addScalarReadAccess(Value *Value, Instruction *User) {
3715 assert(!isa<PHINode>(User));
3716 addMemoryAccess(User->getParent(), User, MemoryAccess::READ, Value, 1, true,
3717 Value, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003718 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003719}
3720void ScopInfo::addScalarReadAccess(Value *Value, PHINode *User,
3721 BasicBlock *UserBB) {
3722 addMemoryAccess(UserBB, User, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003723 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3724 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003725}
3726void ScopInfo::addPHIWriteAccess(PHINode *PHI, BasicBlock *IncomingBlock,
3727 Value *IncomingValue, bool IsExitBlock) {
3728 addMemoryAccess(IncomingBlock, IncomingBlock->getTerminator(),
3729 MemoryAccess::MUST_WRITE, PHI, 1, true, IncomingValue,
3730 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003731 IsExitBlock ? MemoryAccess::SCALAR : MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003732}
3733void ScopInfo::addPHIReadAccess(PHINode *PHI) {
3734 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003735 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3736 MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003737}
3738
Michael Kruse76e924d2015-09-30 09:16:07 +00003739void ScopInfo::buildScop(Region &R, DominatorTree &DT) {
Michael Kruse9d080092015-09-11 21:41:48 +00003740 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003741 scop = new Scop(R, AccFuncMap, *SD, *SE, DT, *LI, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00003742
Michael Krusecac948e2015-10-02 13:53:07 +00003743 buildStmts(R);
Michael Kruse7bf39442015-09-10 12:46:52 +00003744 buildAccessFunctions(R, R);
3745
3746 // In case the region does not have an exiting block we will later (during
3747 // code generation) split the exit block. This will move potential PHI nodes
3748 // from the current exit block into the new region exiting block. Hence, PHI
3749 // nodes that are at this point not part of the region will be.
3750 // To handle these PHI nodes later we will now model their operands as scalar
3751 // accesses. Note that we do not model anything in the exit block if we have
3752 // an exiting block in the region, as there will not be any splitting later.
3753 if (!R.getExitingBlock())
3754 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
3755
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003756 scop->init(*AA);
Michael Kruse7bf39442015-09-10 12:46:52 +00003757}
3758
Michael Krused868b5d2015-09-10 15:25:24 +00003759void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00003760 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00003761 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00003762 return;
3763 }
3764
Michael Kruse9d080092015-09-11 21:41:48 +00003765 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00003766}
3767
Michael Krused868b5d2015-09-10 15:25:24 +00003768void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00003769 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00003770 if (scop) {
3771 delete scop;
3772 scop = 0;
3773 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003774}
3775
3776//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00003777ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00003778 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00003779 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00003780}
3781
3782ScopInfo::~ScopInfo() {
3783 clear();
3784 isl_ctx_free(ctx);
3785}
3786
Tobias Grosser75805372011-04-29 06:27:02 +00003787void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00003788 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00003789 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00003790 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00003791 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
3792 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003793 AU.addRequired<AAResultsWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00003794 AU.setPreservesAll();
3795}
3796
3797bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00003798 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00003799
Michael Krused868b5d2015-09-10 15:25:24 +00003800 if (!SD->isMaxRegionInScop(*R))
3801 return false;
3802
3803 Function *F = R->getEntry()->getParent();
3804 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3805 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3806 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3807 TD = &F->getParent()->getDataLayout();
3808 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Krused868b5d2015-09-10 15:25:24 +00003809
Michael Kruse76e924d2015-09-30 09:16:07 +00003810 buildScop(*R, DT);
Tobias Grosser75805372011-04-29 06:27:02 +00003811
Tobias Grosserd6a50b32015-05-30 06:26:21 +00003812 DEBUG(scop->print(dbgs()));
3813
Michael Kruseafe06702015-10-02 16:33:27 +00003814 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003815 delete scop;
3816 scop = nullptr;
3817 return false;
3818 }
3819
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003820 // Statistics.
3821 ++ScopFound;
3822 if (scop->getMaxLoopDepth() > 0)
3823 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00003824 return false;
3825}
3826
3827char ScopInfo::ID = 0;
3828
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003829Pass *polly::createScopInfoPass() { return new ScopInfo(); }
3830
Tobias Grosser73600b82011-10-08 00:30:40 +00003831INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
3832 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003833 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003834INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00003835INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00003836INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00003837INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003838INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003839INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00003840INITIALIZE_PASS_END(ScopInfo, "polly-scops",
3841 "Polly - Create polyhedral description of Scops", false,
3842 false)