blob: 6027cf3481a5d99815460f3f52e1d6c714b59ef5 [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];
1640 if (!ClassRep)
1641 ClassRep = LInst;
1642 else
1643 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001644 }
1645}
1646
Tobias Grosser6be480c2011-11-08 15:41:13 +00001647void Scop::buildContext() {
1648 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001649 Context = isl_set_universe(isl_space_copy(Space));
1650 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001651}
1652
Tobias Grosser18daaca2012-05-22 10:47:27 +00001653void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001654 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001655 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001656
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001657 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001658
Johannes Doerferte7044942015-02-24 11:58:30 +00001659 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001660 }
1661}
1662
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001663void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001664 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001665 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001666
Tobias Grosser083d3d32014-06-28 08:59:45 +00001667 for (const auto &ParamID : ParameterIds) {
1668 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001669 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001670 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001671 }
1672
1673 // Align the parameters of all data structures to the model.
1674 Context = isl_set_align_params(Context, Space);
1675
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001676 for (ScopStmt &Stmt : *this)
1677 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001678}
1679
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001680static __isl_give isl_set *
1681simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1682 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001683 // If we modelt all blocks in the SCoP that have side effects we can simplify
1684 // the context with the constraints that are needed for anything to be
1685 // executed at all. However, if we have error blocks in the SCoP we already
1686 // assumed some parameter combinations cannot occure and removed them from the
1687 // domains, thus we cannot use the remaining domain to simplify the
1688 // assumptions.
1689 if (!S.hasErrorBlock()) {
1690 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1691 AssumptionContext =
1692 isl_set_gist_params(AssumptionContext, DomainParameters);
1693 }
1694
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001695 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1696 return AssumptionContext;
1697}
1698
1699void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001700 // The parameter constraints of the iteration domains give us a set of
1701 // constraints that need to hold for all cases where at least a single
1702 // statement iteration is executed in the whole scop. We now simplify the
1703 // assumed context under the assumption that such constraints hold and at
1704 // least a single statement iteration is executed. For cases where no
1705 // statement instances are executed, the assumptions we have taken about
1706 // the executed code do not matter and can be changed.
1707 //
1708 // WARNING: This only holds if the assumptions we have taken do not reduce
1709 // the set of statement instances that are executed. Otherwise we
1710 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001711 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001712 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001713 // performed. In such a case, modifying the run-time conditions and
1714 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001715 // to not be executed.
1716 //
1717 // Example:
1718 //
1719 // When delinearizing the following code:
1720 //
1721 // for (long i = 0; i < 100; i++)
1722 // for (long j = 0; j < m; j++)
1723 // A[i+p][j] = 1.0;
1724 //
1725 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001726 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001727 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001728 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1729 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001730}
1731
Johannes Doerfertb164c792014-09-18 11:17:17 +00001732/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001733static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001734 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1735 isl_pw_multi_aff *MinPMA, *MaxPMA;
1736 isl_pw_aff *LastDimAff;
1737 isl_aff *OneAff;
1738 unsigned Pos;
1739
Johannes Doerfert9143d672014-09-27 11:02:39 +00001740 // Restrict the number of parameters involved in the access as the lexmin/
1741 // lexmax computation will take too long if this number is high.
1742 //
1743 // Experiments with a simple test case using an i7 4800MQ:
1744 //
1745 // #Parameters involved | Time (in sec)
1746 // 6 | 0.01
1747 // 7 | 0.04
1748 // 8 | 0.12
1749 // 9 | 0.40
1750 // 10 | 1.54
1751 // 11 | 6.78
1752 // 12 | 30.38
1753 //
1754 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1755 unsigned InvolvedParams = 0;
1756 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1757 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1758 InvolvedParams++;
1759
1760 if (InvolvedParams > RunTimeChecksMaxParameters) {
1761 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001762 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001763 }
1764 }
1765
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001766 Set = isl_set_remove_divs(Set);
1767
Johannes Doerfertb164c792014-09-18 11:17:17 +00001768 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1769 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1770
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001771 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1772 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1773
Johannes Doerfertb164c792014-09-18 11:17:17 +00001774 // Adjust the last dimension of the maximal access by one as we want to
1775 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1776 // we test during code generation might now point after the end of the
1777 // allocated array but we will never dereference it anyway.
1778 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1779 "Assumed at least one output dimension");
1780 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1781 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1782 OneAff = isl_aff_zero_on_domain(
1783 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1784 OneAff = isl_aff_add_constant_si(OneAff, 1);
1785 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1786 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1787
1788 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1789
1790 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001791 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001792}
1793
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001794static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1795 isl_set *Domain = MA->getStatement()->getDomain();
1796 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1797 return isl_set_reset_tuple_id(Domain);
1798}
1799
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001800/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1801static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001802 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001803 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001804
1805 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1806 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001807 Locations = isl_union_set_coalesce(Locations);
1808 Locations = isl_union_set_detect_equalities(Locations);
1809 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001810 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001811 isl_union_set_free(Locations);
1812 return Valid;
1813}
1814
Johannes Doerfert96425c22015-08-30 21:13:53 +00001815/// @brief Helper to treat non-affine regions and basic blocks the same.
1816///
1817///{
1818
1819/// @brief Return the block that is the representing block for @p RN.
1820static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1821 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1822 : RN->getNodeAs<BasicBlock>();
1823}
1824
1825/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001826static inline BasicBlock *
1827getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001828 if (RN->isSubRegion()) {
1829 assert(idx == 0);
1830 return RN->getNodeAs<Region>()->getExit();
1831 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001832 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001833}
1834
1835/// @brief Return the smallest loop surrounding @p RN.
1836static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1837 if (!RN->isSubRegion())
1838 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1839
1840 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1841 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1842 while (L && NonAffineSubRegion->contains(L))
1843 L = L->getParentLoop();
1844 return L;
1845}
1846
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001847static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1848 if (!RN->isSubRegion())
1849 return 1;
1850
1851 unsigned NumBlocks = 0;
1852 Region *R = RN->getNodeAs<Region>();
1853 for (auto BB : R->blocks()) {
1854 (void)BB;
1855 NumBlocks++;
1856 }
1857 return NumBlocks;
1858}
1859
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001860static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
1861 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00001862 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001863 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00001864 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001865 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00001866 return true;
1867 return false;
1868}
1869
Johannes Doerfert96425c22015-08-30 21:13:53 +00001870///}
1871
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001872static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1873 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001874 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001875 isl_id *DimId =
1876 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
1877 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
1878}
1879
Johannes Doerfert96425c22015-08-30 21:13:53 +00001880isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1881 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1882 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00001883 return getDomainConditions(BB);
1884}
1885
1886isl_set *Scop::getDomainConditions(BasicBlock *BB) {
1887 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001888 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001889}
1890
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001891void Scop::buildDomains(Region *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001892
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001893 auto *EntryBB = R->getEntry();
1894 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
1895 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001896
1897 Loop *L = LI.getLoopFor(EntryBB);
1898 while (LD-- >= 0) {
1899 S = addDomainDimId(S, LD + 1, L);
1900 L = L->getParentLoop();
1901 }
1902
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001903 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001904
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00001905 if (SD.isNonAffineSubRegion(R, R))
1906 return;
1907
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001908 buildDomainsWithBranchConstraints(R);
1909 propagateDomainConstraints(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001910}
1911
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001912void Scop::buildDomainsWithBranchConstraints(Region *R) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001913 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00001914
1915 // To create the domain for each block in R we iterate over all blocks and
1916 // subregions in R and propagate the conditions under which the current region
1917 // element is executed. To this end we iterate in reverse post order over R as
1918 // it ensures that we first visit all predecessors of a region node (either a
1919 // basic block or a subregion) before we visit the region node itself.
1920 // Initially, only the domain for the SCoP region entry block is set and from
1921 // there we propagate the current domain to all successors, however we add the
1922 // condition that the successor is actually executed next.
1923 // As we are only interested in non-loop carried constraints here we can
1924 // simply skip loop back edges.
1925
1926 ReversePostOrderTraversal<Region *> RTraversal(R);
1927 for (auto *RN : RTraversal) {
1928
1929 // Recurse for affine subregions but go on for basic blocks and non-affine
1930 // subregions.
1931 if (RN->isSubRegion()) {
1932 Region *SubRegion = RN->getNodeAs<Region>();
1933 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001934 buildDomainsWithBranchConstraints(SubRegion);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001935 continue;
1936 }
1937 }
1938
Johannes Doerfertf5673802015-10-01 23:48:18 +00001939 // Error blocks are assumed not to be executed. Therefor they are not
1940 // checked properly in the ScopDetection. Any attempt to generate control
1941 // conditions from them might result in a crash. However, this is only true
1942 // for the first step of the domain generation (this function) where we
1943 // push the control conditions of a block to the successors. In the second
1944 // step (propagateDomainConstraints) we only receive domain constraints from
1945 // the predecessors and can therefor look at the domain of a error block.
1946 // That allows us to generate the assumptions needed for them not to be
1947 // executed at runtime.
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001948 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
1949 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00001950 continue;
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001951 }
Johannes Doerfertf5673802015-10-01 23:48:18 +00001952
Johannes Doerfert96425c22015-08-30 21:13:53 +00001953 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001954 TerminatorInst *TI = BB->getTerminator();
1955
Johannes Doerfertf5673802015-10-01 23:48:18 +00001956 isl_set *Domain = DomainMap.lookup(BB);
1957 if (!Domain) {
1958 DEBUG(dbgs() << "\tSkip: " << BB->getName()
1959 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001960 continue;
1961 }
1962
Johannes Doerfert96425c22015-08-30 21:13:53 +00001963 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001964
1965 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1966 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1967
1968 // Build the condition sets for the successor nodes of the current region
1969 // node. If it is a non-affine subregion we will always execute the single
1970 // exit node, hence the single entry node domain is the condition set. For
1971 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001972 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001973 if (RN->isSubRegion())
1974 ConditionSets.push_back(isl_set_copy(Domain));
1975 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001976 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001977
1978 // Now iterate over the successors and set their initial domain based on
1979 // their condition set. We skip back edges here and have to be careful when
1980 // we leave a loop not to keep constraints over a dimension that doesn't
1981 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001982 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00001983 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001984 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001985 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001986
1987 // Skip back edges.
1988 if (DT.dominates(SuccBB, BB)) {
1989 isl_set_free(CondSet);
1990 continue;
1991 }
1992
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001993 // Do not adjust the number of dimensions if we enter a boxed loop or are
1994 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001995 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001996 Region *SuccRegion = RI.getRegionFor(SuccBB);
Johannes Doerfert634909c2015-10-04 14:57:41 +00001997 if (SD.isNonAffineSubRegion(SuccRegion, &getRegion()))
1998 while (SuccBBLoop && SuccRegion->contains(SuccBBLoop))
1999 SuccBBLoop = SuccBBLoop->getParentLoop();
2000
2001 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002002
2003 // Check if the edge to SuccBB is a loop entry or exit edge. If so
2004 // adjust the dimensionality accordingly. Lastly, if we leave a loop
2005 // and enter a new one we need to drop the old constraints.
2006 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002007 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002008 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002009 CondSet = isl_set_project_out(CondSet, isl_dim_set,
2010 isl_set_n_dim(CondSet) - LoopDepthDiff,
2011 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002012 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002013 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002014 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002015 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002016 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002017 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002018 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
2019 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002020 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002021 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002022 }
2023
2024 // Set the domain for the successor or merge it with an existing domain in
2025 // case there are multiple paths (without loop back edges) to the
2026 // successor block.
2027 isl_set *&SuccDomain = DomainMap[SuccBB];
2028 if (!SuccDomain)
2029 SuccDomain = CondSet;
2030 else
2031 SuccDomain = isl_set_union(SuccDomain, CondSet);
2032
2033 SuccDomain = isl_set_coalesce(SuccDomain);
Johannes Doerfert634909c2015-10-04 14:57:41 +00002034 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
2035 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002036 }
2037 }
2038}
2039
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002040/// @brief Return the domain for @p BB wrt @p DomainMap.
2041///
2042/// This helper function will lookup @p BB in @p DomainMap but also handle the
2043/// case where @p BB is contained in a non-affine subregion using the region
2044/// tree obtained by @p RI.
2045static __isl_give isl_set *
2046getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
2047 RegionInfo &RI) {
2048 auto DIt = DomainMap.find(BB);
2049 if (DIt != DomainMap.end())
2050 return isl_set_copy(DIt->getSecond());
2051
2052 Region *R = RI.getRegionFor(BB);
2053 while (R->getEntry() == BB)
2054 R = R->getParent();
2055 return getDomainForBlock(R->getEntry(), DomainMap, RI);
2056}
2057
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002058void Scop::propagateDomainConstraints(Region *R) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002059 // Iterate over the region R and propagate the domain constrains from the
2060 // predecessors to the current node. In contrast to the
2061 // buildDomainsWithBranchConstraints function, this one will pull the domain
2062 // information from the predecessors instead of pushing it to the successors.
2063 // Additionally, we assume the domains to be already present in the domain
2064 // map here. However, we iterate again in reverse post order so we know all
2065 // predecessors have been visited before a block or non-affine subregion is
2066 // visited.
2067
2068 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2069 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2070
2071 ReversePostOrderTraversal<Region *> RTraversal(R);
2072 for (auto *RN : RTraversal) {
2073
2074 // Recurse for affine subregions but go on for basic blocks and non-affine
2075 // subregions.
2076 if (RN->isSubRegion()) {
2077 Region *SubRegion = RN->getNodeAs<Region>();
2078 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002079 propagateDomainConstraints(SubRegion);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002080 continue;
2081 }
2082 }
2083
Johannes Doerfertf5673802015-10-01 23:48:18 +00002084 // Get the domain for the current block and check if it was initialized or
2085 // not. The only way it was not is if this block is only reachable via error
2086 // blocks, thus will not be executed under the assumptions we make. Such
2087 // blocks have to be skipped as their predecessors might not have domains
2088 // either. It would not benefit us to compute the domain anyway, only the
2089 // domains of the error blocks that are reachable from non-error blocks
2090 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002091 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002092 isl_set *&Domain = DomainMap[BB];
2093 if (!Domain) {
2094 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2095 << ", it is only reachable from error blocks.\n");
2096 DomainMap.erase(BB);
2097 continue;
2098 }
2099 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
2100
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002101 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2102 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2103
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002104 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2105 for (auto *PredBB : predecessors(BB)) {
2106
2107 // Skip backedges
2108 if (DT.dominates(BB, PredBB))
2109 continue;
2110
2111 isl_set *PredBBDom = nullptr;
2112
2113 // Handle the SCoP entry block with its outside predecessors.
2114 if (!getRegion().contains(PredBB))
2115 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
2116
2117 if (!PredBBDom) {
2118 // Determine the loop depth of the predecessor and adjust its domain to
2119 // the domain of the current block. This can mean we have to:
2120 // o) Drop a dimension if this block is the exit of a loop, not the
2121 // header of a new loop and the predecessor was part of the loop.
2122 // o) Add an unconstrainted new dimension if this block is the header
2123 // of a loop and the predecessor is not part of it.
2124 // o) Drop the information about the innermost loop dimension when the
2125 // predecessor and the current block are surrounded by different
2126 // loops in the same depth.
2127 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2128 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2129 while (BoxedLoops.count(PredBBLoop))
2130 PredBBLoop = PredBBLoop->getParentLoop();
2131
2132 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002133 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002134 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002135 PredBBDom = isl_set_project_out(
2136 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2137 LoopDepthDiff);
2138 else if (PredBBLoopDepth < BBLoopDepth) {
2139 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002140 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002141 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2142 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002143 PredBBDom = isl_set_drop_constraints_involving_dims(
2144 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002145 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002146 }
2147
2148 PredDom = isl_set_union(PredDom, PredBBDom);
2149 }
2150
2151 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002152 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002153
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002154 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002155 addLoopBoundsToHeaderDomain(BBLoop);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002156
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002157 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002158 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002159 IsOptimized = true;
2160 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2161 addAssumption(isl_set_complement(DomPar));
2162 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002163 }
2164}
2165
2166/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2167/// is incremented by one and all other dimensions are equal, e.g.,
2168/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2169/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2170static __isl_give isl_map *
2171createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2172 auto *MapSpace = isl_space_map_from_set(SetSpace);
2173 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2174 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2175 if (u != Dim)
2176 NextIterationMap =
2177 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2178 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2179 C = isl_constraint_set_constant_si(C, 1);
2180 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2181 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2182 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2183 return NextIterationMap;
2184}
2185
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002186void Scop::addLoopBoundsToHeaderDomain(Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002187 int LoopDepth = getRelativeLoopDepth(L);
2188 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002189
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002190 BasicBlock *HeaderBB = L->getHeader();
2191 assert(DomainMap.count(HeaderBB));
2192 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002193
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002194 isl_map *NextIterationMap =
2195 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002196
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002197 isl_set *UnionBackedgeCondition =
2198 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002199
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002200 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2201 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002202
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002203 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002204
2205 // If the latch is only reachable via error statements we skip it.
2206 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2207 if (!LatchBBDom)
2208 continue;
2209
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002210 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002211
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002212 TerminatorInst *TI = LatchBB->getTerminator();
2213 BranchInst *BI = dyn_cast<BranchInst>(TI);
2214 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002215 BackedgeCondition = isl_set_copy(LatchBBDom);
2216 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002217 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002218 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002219 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002220
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002221 // Free the non back edge condition set as we do not need it.
2222 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002223
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002224 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002225 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002226
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002227 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2228 assert(LatchLoopDepth >= LoopDepth);
2229 BackedgeCondition =
2230 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2231 LatchLoopDepth - LoopDepth);
2232 UnionBackedgeCondition =
2233 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002234 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002235
2236 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2237 for (int i = 0; i < LoopDepth; i++)
2238 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2239
2240 isl_set *UnionBackedgeConditionComplement =
2241 isl_set_complement(UnionBackedgeCondition);
2242 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2243 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2244 UnionBackedgeConditionComplement =
2245 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2246 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2247 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2248
2249 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2250 HeaderBBDom = Parts.second;
2251
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002252 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2253 // the bounded assumptions to the context as they are already implied by the
2254 // <nsw> tag.
2255 if (Affinator.hasNSWAddRecForLoop(L)) {
2256 isl_set_free(Parts.first);
2257 return;
2258 }
2259
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002260 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2261 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfert707a4062015-09-20 16:38:19 +00002262 addAssumption(BoundedCtx);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002263}
2264
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002265void Scop::buildAliasChecks(AliasAnalysis &AA) {
2266 if (!PollyUseRuntimeAliasChecks)
2267 return;
2268
2269 if (buildAliasGroups(AA))
2270 return;
2271
2272 // If a problem occurs while building the alias groups we need to delete
2273 // this SCoP and pretend it wasn't valid in the first place. To this end
2274 // we make the assumed context infeasible.
2275 addAssumption(isl_set_empty(getParamSpace()));
2276
2277 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2278 << " could not be created as the number of parameters involved "
2279 "is too high. The SCoP will be "
2280 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2281 "the maximal number of parameters but be advised that the "
2282 "compile time might increase exponentially.\n\n");
2283}
2284
Johannes Doerfert9143d672014-09-27 11:02:39 +00002285bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002286 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002287 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002288 // for all memory accesses inside the SCoP.
2289 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002290 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002291 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002292 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002293 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002294 // if their access domains intersect, otherwise they are in different
2295 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002296 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002297 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002298 // and maximal accesses to each array of a group in read only and non
2299 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002300 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2301
2302 AliasSetTracker AST(AA);
2303
2304 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002305 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002306 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002307
2308 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002309 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002310 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2311 isl_set_free(StmtDomain);
2312 if (StmtDomainEmpty)
2313 continue;
2314
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002315 for (MemoryAccess *MA : Stmt) {
Michael Kruse8d0b7342015-09-25 21:21:00 +00002316 if (MA->isImplicit())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002317 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002318 if (!MA->isRead())
2319 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002320 Instruction *Acc = MA->getAccessInstruction();
2321 PtrToAcc[getPointerOperand(*Acc)] = MA;
2322 AST.add(Acc);
2323 }
2324 }
2325
2326 SmallVector<AliasGroupTy, 4> AliasGroups;
2327 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002328 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002329 continue;
2330 AliasGroupTy AG;
2331 for (auto PR : AS)
2332 AG.push_back(PtrToAcc[PR.getValue()]);
2333 assert(AG.size() > 1 &&
2334 "Alias groups should contain at least two accesses");
2335 AliasGroups.push_back(std::move(AG));
2336 }
2337
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002338 // Split the alias groups based on their domain.
2339 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2340 AliasGroupTy NewAG;
2341 AliasGroupTy &AG = AliasGroups[u];
2342 AliasGroupTy::iterator AGI = AG.begin();
2343 isl_set *AGDomain = getAccessDomain(*AGI);
2344 while (AGI != AG.end()) {
2345 MemoryAccess *MA = *AGI;
2346 isl_set *MADomain = getAccessDomain(MA);
2347 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2348 NewAG.push_back(MA);
2349 AGI = AG.erase(AGI);
2350 isl_set_free(MADomain);
2351 } else {
2352 AGDomain = isl_set_union(AGDomain, MADomain);
2353 AGI++;
2354 }
2355 }
2356 if (NewAG.size() > 1)
2357 AliasGroups.push_back(std::move(NewAG));
2358 isl_set_free(AGDomain);
2359 }
2360
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002361 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002362 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2363 for (AliasGroupTy &AG : AliasGroups) {
2364 NonReadOnlyBaseValues.clear();
2365 ReadOnlyPairs.clear();
2366
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002367 if (AG.size() < 2) {
2368 AG.clear();
2369 continue;
2370 }
2371
Johannes Doerfert13771732014-10-01 12:40:46 +00002372 for (auto II = AG.begin(); II != AG.end();) {
2373 Value *BaseAddr = (*II)->getBaseAddr();
2374 if (HasWriteAccess.count(BaseAddr)) {
2375 NonReadOnlyBaseValues.insert(BaseAddr);
2376 II++;
2377 } else {
2378 ReadOnlyPairs[BaseAddr].insert(*II);
2379 II = AG.erase(II);
2380 }
2381 }
2382
2383 // If we don't have read only pointers check if there are at least two
2384 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002385 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002386 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002387 continue;
2388 }
2389
2390 // If we don't have non read only pointers clear the alias group.
2391 if (NonReadOnlyBaseValues.empty()) {
2392 AG.clear();
2393 continue;
2394 }
2395
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002396 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002397 MinMaxAliasGroups.emplace_back();
2398 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2399 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2400 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2401 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002402
2403 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002404
2405 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002406 for (MemoryAccess *MA : AG)
2407 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002408
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002409 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2410 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002411
2412 // Bail out if the number of values we need to compare is too large.
2413 // This is important as the number of comparisions grows quadratically with
2414 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002415 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2416 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002417 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002418
2419 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002420 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002421 Accesses = isl_union_map_empty(getParamSpace());
2422
2423 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2424 for (MemoryAccess *MA : ReadOnlyPair.second)
2425 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2426
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002427 Valid =
2428 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002429
2430 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002431 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002432 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002433
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002434 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002435}
2436
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002437static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
2438 Loop *L = LI.getLoopFor(R.getEntry());
2439 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2440}
2441
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002442static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2443 ScopDetection &SD) {
2444
2445 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2446
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002447 unsigned MinLD = INT_MAX, MaxLD = 0;
2448 for (BasicBlock *BB : R.blocks()) {
2449 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002450 if (!R.contains(L))
2451 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002452 if (BoxedLoops && BoxedLoops->count(L))
2453 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002454 unsigned LD = L->getLoopDepth();
2455 MinLD = std::min(MinLD, LD);
2456 MaxLD = std::max(MaxLD, LD);
2457 }
2458 }
2459
2460 // Handle the case that there is no loop in the SCoP first.
2461 if (MaxLD == 0)
2462 return 1;
2463
2464 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2465 assert(MaxLD >= MinLD &&
2466 "Maximal loop depth was smaller than mininaml loop depth?");
2467 return MaxLD - MinLD + 1;
2468}
2469
Johannes Doerfert478a7de2015-10-02 13:09:31 +00002470Scop::Scop(Region &R, AccFuncMapType &AccFuncMap, ScopDetection &SD,
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002471 ScalarEvolution &ScalarEvolution, DominatorTree &DT, LoopInfo &LI,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002472 isl_ctx *Context, unsigned MaxLoopDepth)
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002473 : LI(LI), DT(DT), SE(&ScalarEvolution), SD(SD), R(R),
2474 AccFuncMap(AccFuncMap), IsOptimized(false),
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002475 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
2476 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Context(nullptr),
2477 Affinator(this), AssumedContext(nullptr), BoundaryContext(nullptr),
2478 Schedule(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002479
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002480void Scop::init(AliasAnalysis &AA) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002481 buildContext();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002482 buildInvariantEquivalenceClasses();
2483
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002484 buildDomains(&R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002485
Michael Krusecac948e2015-10-02 13:53:07 +00002486 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002487 // Exit early in case there are no executable statements left in this scop.
Michael Krusecac948e2015-10-02 13:53:07 +00002488 simplifySCoP(true);
Michael Kruseafe06702015-10-02 16:33:27 +00002489 if (Stmts.empty())
2490 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002491
Michael Krusecac948e2015-10-02 13:53:07 +00002492 // The ScopStmts now have enough information to initialize themselves.
2493 for (ScopStmt &Stmt : Stmts)
2494 Stmt.init();
2495
2496 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002497 Loop *L = getLoopSurroundingRegion(R, LI);
2498 LoopSchedules[L];
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002499 buildSchedule(&R, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002500 Schedule = LoopSchedules[L].first;
Tobias Grosser75805372011-04-29 06:27:02 +00002501
Tobias Grosser8286b832015-11-02 11:29:32 +00002502 if (isl_set_is_empty(AssumedContext))
2503 return;
2504
2505 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002506 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002507 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002508 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002509 buildBoundaryContext();
2510 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002511 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002512
2513 hoistInvariantLoads();
Michael Krusecac948e2015-10-02 13:53:07 +00002514 simplifySCoP(false);
Tobias Grosser75805372011-04-29 06:27:02 +00002515}
2516
2517Scop::~Scop() {
2518 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002519 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002520 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002521 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002522
Johannes Doerfert96425c22015-08-30 21:13:53 +00002523 for (auto It : DomainMap)
2524 isl_set_free(It.second);
2525
Johannes Doerfertb164c792014-09-18 11:17:17 +00002526 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002527 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002528 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002529 isl_pw_multi_aff_free(MMA.first);
2530 isl_pw_multi_aff_free(MMA.second);
2531 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002532 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002533 isl_pw_multi_aff_free(MMA.first);
2534 isl_pw_multi_aff_free(MMA.second);
2535 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002536 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002537
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002538 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002539 isl_set_free(std::get<2>(IAClass));
Tobias Grosser75805372011-04-29 06:27:02 +00002540}
2541
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002542void Scop::updateAccessDimensionality() {
2543 for (auto &Stmt : *this)
2544 for (auto &Access : Stmt)
2545 Access->updateDimensionality();
2546}
2547
Michael Krusecac948e2015-10-02 13:53:07 +00002548void Scop::simplifySCoP(bool RemoveIgnoredStmts) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002549 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2550 ScopStmt &Stmt = *StmtIt;
Michael Krusecac948e2015-10-02 13:53:07 +00002551 RegionNode *RN = Stmt.isRegionStmt()
2552 ? Stmt.getRegion()->getNode()
2553 : getRegion().getBBNode(Stmt.getBasicBlock());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002554
Johannes Doerferteca9e892015-11-03 16:54:49 +00002555 bool RemoveStmt = StmtIt->isEmpty();
2556 if (!RemoveStmt)
2557 RemoveStmt = isl_set_is_empty(DomainMap[getRegionNodeBasicBlock(RN)]);
2558 if (!RemoveStmt)
2559 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002560
Johannes Doerferteca9e892015-11-03 16:54:49 +00002561 // Remove read only statements only after invariant loop hoisting.
2562 if (!RemoveStmt && !RemoveIgnoredStmts) {
2563 bool OnlyRead = true;
2564 for (MemoryAccess *MA : Stmt) {
2565 if (MA->isRead())
2566 continue;
2567
2568 OnlyRead = false;
2569 break;
2570 }
2571
2572 RemoveStmt = OnlyRead;
2573 }
2574
2575 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00002576 // Remove the statement because it is unnecessary.
2577 if (Stmt.isRegionStmt())
2578 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2579 StmtMap.erase(BB);
2580 else
2581 StmtMap.erase(Stmt.getBasicBlock());
2582
2583 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002584 continue;
2585 }
2586
Michael Krusecac948e2015-10-02 13:53:07 +00002587 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002588 }
2589}
2590
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002591const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2592 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2593 if (!LInst)
2594 return nullptr;
2595
2596 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2597 LInst = cast<LoadInst>(Rep);
2598
2599 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2600 for (auto &IAClass : InvariantEquivClasses)
2601 if (PointerSCEV == std::get<0>(IAClass))
2602 return &IAClass;
2603
2604 return nullptr;
2605}
2606
2607void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2608
2609 // Get the context under which the statement is executed.
2610 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2611 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2612 DomainCtx = isl_set_detect_equalities(DomainCtx);
2613 DomainCtx = isl_set_coalesce(DomainCtx);
2614
2615 // Project out all parameters that relate to loads in the statement. Otherwise
2616 // we could have cyclic dependences on the constraints under which the
2617 // hoisted loads are executed and we could not determine an order in which to
2618 // pre-load them. This happens because not only lower bounds are part of the
2619 // domain but also upper bounds.
2620 for (MemoryAccess *MA : InvMAs) {
2621 Instruction *AccInst = MA->getAccessInstruction();
2622 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00002623 SetVector<Value *> Values;
2624 for (const SCEV *Parameter : Parameters) {
2625 Values.clear();
2626 findValues(Parameter, Values);
2627 if (!Values.count(AccInst))
2628 continue;
2629
2630 if (isl_id *ParamId = getIdForParam(Parameter)) {
2631 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2632 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2633 isl_id_free(ParamId);
2634 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002635 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002636 }
2637 }
2638
2639 for (MemoryAccess *MA : InvMAs) {
2640 // Check for another invariant access that accesses the same location as
2641 // MA and if found consolidate them. Otherwise create a new equivalence
2642 // class at the end of InvariantEquivClasses.
2643 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
2644 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2645
2646 bool Consolidated = false;
2647 for (auto &IAClass : InvariantEquivClasses) {
2648 if (PointerSCEV != std::get<0>(IAClass))
2649 continue;
2650
2651 Consolidated = true;
2652
2653 // Add MA to the list of accesses that are in this class.
2654 auto &MAs = std::get<1>(IAClass);
2655 MAs.push_front(MA);
2656
2657 // Unify the execution context of the class and this statement.
2658 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
2659 IAClassDomainCtx = isl_set_coalesce(
2660 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
2661 break;
2662 }
2663
2664 if (Consolidated)
2665 continue;
2666
2667 // If we did not consolidate MA, thus did not find an equivalence class
2668 // for it, we create a new one.
2669 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
2670 isl_set_copy(DomainCtx));
2671 }
2672
2673 isl_set_free(DomainCtx);
2674}
2675
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002676void Scop::hoistInvariantLoads() {
2677 isl_union_map *Writes = getWrites();
2678 for (ScopStmt &Stmt : *this) {
2679
2680 // TODO: Loads that are not loop carried, hence are in a statement with
2681 // zero iterators, are by construction invariant, though we
Johannes Doerfert09e36972015-10-07 20:17:36 +00002682 // currently "hoist" them anyway. This is necessary because we allow
2683 // them to be treated as parameters (e.g., in conditions) and our code
2684 // generation would otherwise use the old value.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002685
Johannes Doerfert8930f482015-10-02 14:51:00 +00002686 BasicBlock *BB = Stmt.isBlockStmt() ? Stmt.getBasicBlock()
2687 : Stmt.getRegion()->getEntry();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002688 isl_set *Domain = Stmt.getDomain();
2689 MemoryAccessList InvMAs;
2690
2691 for (MemoryAccess *MA : Stmt) {
2692 if (MA->isImplicit() || MA->isWrite() || !MA->isAffine())
2693 continue;
2694
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002695 // Skip accesses that have an invariant base pointer which is defined but
2696 // not loaded inside the SCoP. This can happened e.g., if a readnone call
2697 // returns a pointer that is used as a base address. However, as we want
2698 // to hoist indirect pointers, we allow the base pointer to be defined in
Johannes Doerfert654c3282015-10-21 22:14:57 +00002699 // the region if it is also a memory access. Each ScopArrayInfo object
2700 // that has a base pointer origin has a base pointer that is loaded and
2701 // that it is invariant, thus it will be hoisted too. However, if there is
Tobias Grosser27e19a02015-10-25 12:05:14 +00002702 // no base pointer origin we check that the base pointer is defined
Johannes Doerfert654c3282015-10-21 22:14:57 +00002703 // outside the region.
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002704 const ScopArrayInfo *SAI = MA->getScopArrayInfo();
Johannes Doerfert654c3282015-10-21 22:14:57 +00002705 while (auto *BasePtrOriginSAI = SAI->getBasePtrOriginSAI())
2706 SAI = BasePtrOriginSAI;
2707
2708 if (auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr()))
2709 if (R.contains(BasePtrInst))
2710 continue;
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002711
Johannes Doerfert8930f482015-10-02 14:51:00 +00002712 // Skip accesses in non-affine subregions as they might not be executed
2713 // under the same condition as the entry of the non-affine subregion.
2714 if (BB != MA->getAccessInstruction()->getParent())
2715 continue;
2716
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002717 isl_map *AccessRelation = MA->getAccessRelation();
Johannes Doerfertb864c2c2015-10-18 19:50:18 +00002718
2719 // Skip accesses that have an empty access relation. These can be caused
2720 // by multiple offsets with a type cast in-between that cause the overall
2721 // byte offset to be not divisible by the new types sizes.
2722 if (isl_map_is_empty(AccessRelation)) {
2723 isl_map_free(AccessRelation);
2724 continue;
2725 }
2726
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002727 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
2728 Stmt.getNumIterators())) {
2729 isl_map_free(AccessRelation);
2730 continue;
2731 }
2732
2733 AccessRelation =
2734 isl_map_intersect_domain(AccessRelation, isl_set_copy(Domain));
2735 isl_set *AccessRange = isl_map_range(AccessRelation);
2736
2737 isl_union_map *Written = isl_union_map_intersect_range(
2738 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
2739 bool IsWritten = !isl_union_map_is_empty(Written);
2740 isl_union_map_free(Written);
2741
2742 if (IsWritten)
2743 continue;
2744
2745 InvMAs.push_front(MA);
2746 }
2747
2748 // We inserted invariant accesses always in the front but need them to be
2749 // sorted in a "natural order". The statements are already sorted in reverse
2750 // post order and that suffices for the accesses too. The reason we require
2751 // an order in the first place is the dependences between invariant loads
2752 // that can be caused by indirect loads.
2753 InvMAs.reverse();
2754
2755 // Transfer the memory access from the statement to the SCoP.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002756 Stmt.removeMemoryAccesses(InvMAs);
2757 addInvariantLoads(Stmt, InvMAs);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002758
2759 isl_set_free(Domain);
2760 }
2761 isl_union_map_free(Writes);
2762
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002763 if (!InvariantEquivClasses.empty())
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002764 IsOptimized = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00002765
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002766 auto &ScopRIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert09e36972015-10-07 20:17:36 +00002767 // Check required invariant loads that were tagged during SCoP detection.
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002768 for (LoadInst *LI : ScopRIL) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00002769 assert(LI && getRegion().contains(LI));
2770 ScopStmt *Stmt = getStmtForBasicBlock(LI->getParent());
2771 if (Stmt && Stmt->lookupAccessesFor(LI) != nullptr) {
2772 DEBUG(dbgs() << "\n\nWARNING: Load (" << *LI
2773 << ") is required to be invariant but was not marked as "
2774 "such. SCoP for "
2775 << getRegion() << " will be dropped\n\n");
2776 addAssumption(isl_set_empty(getParamSpace()));
2777 return;
2778 }
2779 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002780}
2781
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002782const ScopArrayInfo *
2783Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002784 ArrayRef<const SCEV *> Sizes,
2785 ScopArrayInfo::ARRAYKIND Kind) {
2786 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002787 if (!SAI) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002788 SAI.reset(
2789 new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, Kind, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002790 } else {
Tobias Grosser8286b832015-11-02 11:29:32 +00002791 // In case of mismatching array sizes, we bail out by setting the run-time
2792 // context to false.
2793 if (!SAI->updateSizes(Sizes))
2794 addAssumption(isl_set_empty(getParamSpace()));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002795 }
Tobias Grosserab671442015-05-23 05:58:27 +00002796 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002797}
2798
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002799const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
2800 ScopArrayInfo::ARRAYKIND Kind) {
2801 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002802 assert(SAI && "No ScopArrayInfo available for this base pointer");
2803 return SAI;
2804}
2805
Tobias Grosser74394f02013-01-14 22:40:23 +00002806std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002807std::string Scop::getAssumedContextStr() const {
2808 return stringFromIslObj(AssumedContext);
2809}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002810std::string Scop::getBoundaryContextStr() const {
2811 return stringFromIslObj(BoundaryContext);
2812}
Tobias Grosser75805372011-04-29 06:27:02 +00002813
2814std::string Scop::getNameStr() const {
2815 std::string ExitName, EntryName;
2816 raw_string_ostream ExitStr(ExitName);
2817 raw_string_ostream EntryStr(EntryName);
2818
Tobias Grosserf240b482014-01-09 10:42:15 +00002819 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002820 EntryStr.str();
2821
2822 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00002823 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002824 ExitStr.str();
2825 } else
2826 ExitName = "FunctionExit";
2827
2828 return EntryName + "---" + ExitName;
2829}
2830
Tobias Grosser74394f02013-01-14 22:40:23 +00002831__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00002832__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002833 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00002834}
2835
Tobias Grossere86109f2013-10-29 21:05:49 +00002836__isl_give isl_set *Scop::getAssumedContext() const {
2837 return isl_set_copy(AssumedContext);
2838}
2839
Johannes Doerfert43788c52015-08-20 05:58:56 +00002840__isl_give isl_set *Scop::getRuntimeCheckContext() const {
2841 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002842 RuntimeCheckContext =
2843 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
2844 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002845 return RuntimeCheckContext;
2846}
2847
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002848bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002849 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002850 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002851 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
2852 isl_set_free(RuntimeCheckContext);
2853 return IsFeasible;
2854}
2855
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002856void Scop::addAssumption(__isl_take isl_set *Set) {
2857 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00002858 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002859}
2860
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002861__isl_give isl_set *Scop::getBoundaryContext() const {
2862 return isl_set_copy(BoundaryContext);
2863}
2864
Tobias Grosser75805372011-04-29 06:27:02 +00002865void Scop::printContext(raw_ostream &OS) const {
2866 OS << "Context:\n";
2867
2868 if (!Context) {
2869 OS.indent(4) << "n/a\n\n";
2870 return;
2871 }
2872
2873 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00002874
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002875 OS.indent(4) << "Assumed Context:\n";
2876 if (!AssumedContext) {
2877 OS.indent(4) << "n/a\n\n";
2878 return;
2879 }
2880
2881 OS.indent(4) << getAssumedContextStr() << "\n";
2882
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002883 OS.indent(4) << "Boundary Context:\n";
2884 if (!BoundaryContext) {
2885 OS.indent(4) << "n/a\n\n";
2886 return;
2887 }
2888
2889 OS.indent(4) << getBoundaryContextStr() << "\n";
2890
Tobias Grosser083d3d32014-06-28 08:59:45 +00002891 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00002892 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00002893 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
2894 }
Tobias Grosser75805372011-04-29 06:27:02 +00002895}
2896
Johannes Doerfertb164c792014-09-18 11:17:17 +00002897void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002898 int noOfGroups = 0;
2899 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002900 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002901 noOfGroups += 1;
2902 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002903 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002904 }
2905
Tobias Grosserbb853c22015-07-25 12:31:03 +00002906 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00002907 if (MinMaxAliasGroups.empty()) {
2908 OS.indent(8) << "n/a\n";
2909 return;
2910 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002911
Tobias Grosserbb853c22015-07-25 12:31:03 +00002912 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002913
2914 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002915 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002916 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002917 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002918 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2919 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002920 }
2921 OS << " ]]\n";
2922 }
2923
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002924 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002925 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00002926 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002927 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002928 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2929 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002930 }
2931 OS << " ]]\n";
2932 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002933 }
2934}
2935
Tobias Grosser75805372011-04-29 06:27:02 +00002936void Scop::printStatements(raw_ostream &OS) const {
2937 OS << "Statements {\n";
2938
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002939 for (const ScopStmt &Stmt : *this)
2940 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00002941
2942 OS.indent(4) << "}\n";
2943}
2944
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002945void Scop::printArrayInfo(raw_ostream &OS) const {
2946 OS << "Arrays {\n";
2947
Tobias Grosserab671442015-05-23 05:58:27 +00002948 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002949 Array.second->print(OS);
2950
2951 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002952
2953 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
2954
2955 for (auto &Array : arrays())
2956 Array.second->print(OS, /* SizeAsPwAff */ true);
2957
2958 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002959}
2960
Tobias Grosser75805372011-04-29 06:27:02 +00002961void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00002962 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
2963 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00002964 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00002965 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002966 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002967 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002968 const auto &MAs = std::get<1>(IAClass);
2969 if (MAs.empty()) {
2970 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002971 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002972 MAs.front()->print(OS);
2973 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002974 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002975 }
2976 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00002977 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002978 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002979 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00002980 printStatements(OS.indent(4));
2981}
2982
2983void Scop::dump() const { print(dbgs()); }
2984
Tobias Grosser9a38ab82011-11-08 15:41:03 +00002985isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00002986
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002987__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
2988 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00002989}
2990
Tobias Grosser808cd692015-07-14 09:33:13 +00002991__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002992 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002993
Tobias Grosser808cd692015-07-14 09:33:13 +00002994 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002995 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002996
2997 return Domain;
2998}
2999
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003000__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003001 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003002
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003003 for (ScopStmt &Stmt : *this) {
3004 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003005 if (!MA->isMustWrite())
3006 continue;
3007
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003008 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003009 isl_map *AccessDomain = MA->getAccessRelation();
3010 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3011 Write = isl_union_map_add_map(Write, AccessDomain);
3012 }
3013 }
3014 return isl_union_map_coalesce(Write);
3015}
3016
3017__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003018 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003019
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003020 for (ScopStmt &Stmt : *this) {
3021 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003022 if (!MA->isMayWrite())
3023 continue;
3024
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003025 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003026 isl_map *AccessDomain = MA->getAccessRelation();
3027 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3028 Write = isl_union_map_add_map(Write, AccessDomain);
3029 }
3030 }
3031 return isl_union_map_coalesce(Write);
3032}
3033
Tobias Grosser37eb4222014-02-20 21:43:54 +00003034__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003035 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003036
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003037 for (ScopStmt &Stmt : *this) {
3038 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00003039 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00003040 continue;
3041
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003042 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00003043 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00003044 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3045 Write = isl_union_map_add_map(Write, AccessDomain);
3046 }
3047 }
3048 return isl_union_map_coalesce(Write);
3049}
3050
3051__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003052 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003053
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003054 for (ScopStmt &Stmt : *this) {
3055 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00003056 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00003057 continue;
3058
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003059 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00003060 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00003061
3062 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3063 Read = isl_union_map_add_map(Read, AccessDomain);
3064 }
3065 }
3066 return isl_union_map_coalesce(Read);
3067}
3068
Tobias Grosser808cd692015-07-14 09:33:13 +00003069__isl_give isl_union_map *Scop::getSchedule() const {
3070 auto Tree = getScheduleTree();
3071 auto S = isl_schedule_get_map(Tree);
3072 isl_schedule_free(Tree);
3073 return S;
3074}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003075
Tobias Grosser808cd692015-07-14 09:33:13 +00003076__isl_give isl_schedule *Scop::getScheduleTree() const {
3077 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3078 getDomains());
3079}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003080
Tobias Grosser808cd692015-07-14 09:33:13 +00003081void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3082 auto *S = isl_schedule_from_domain(getDomains());
3083 S = isl_schedule_insert_partial_schedule(
3084 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3085 isl_schedule_free(Schedule);
3086 Schedule = S;
3087}
3088
3089void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3090 isl_schedule_free(Schedule);
3091 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003092}
3093
3094bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3095 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003096 for (ScopStmt &Stmt : *this) {
3097 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003098 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3099 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3100
3101 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3102 isl_union_set_free(StmtDomain);
3103 isl_union_set_free(NewStmtDomain);
3104 continue;
3105 }
3106
3107 Changed = true;
3108
3109 isl_union_set_free(StmtDomain);
3110 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3111
3112 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003113 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003114 isl_union_set_free(NewStmtDomain);
3115 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003116 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003117 }
3118 isl_union_set_free(Domain);
3119 return Changed;
3120}
3121
Tobias Grosser75805372011-04-29 06:27:02 +00003122ScalarEvolution *Scop::getSE() const { return SE; }
3123
Johannes Doerfertf5673802015-10-01 23:48:18 +00003124bool Scop::isIgnored(RegionNode *RN) {
3125 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser75805372011-04-29 06:27:02 +00003126
Johannes Doerfertf5673802015-10-01 23:48:18 +00003127 // Check if there are accesses contained.
3128 bool ContainsAccesses = false;
3129 if (!RN->isSubRegion())
3130 ContainsAccesses = getAccessFunctions(BB);
3131 else
3132 for (BasicBlock *RBB : RN->getNodeAs<Region>()->blocks())
3133 ContainsAccesses |= (getAccessFunctions(RBB) != nullptr);
3134 if (!ContainsAccesses)
3135 return true;
3136
3137 // Check for reachability via non-error blocks.
3138 if (!DomainMap.count(BB))
3139 return true;
3140
3141 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003142 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003143 return true;
3144
3145 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003146}
3147
Tobias Grosser808cd692015-07-14 09:33:13 +00003148struct MapToDimensionDataTy {
3149 int N;
3150 isl_union_pw_multi_aff *Res;
3151};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003152
Tobias Grosser808cd692015-07-14 09:33:13 +00003153// @brief Create a function that maps the elements of 'Set' to its N-th
3154// dimension.
3155//
3156// The result is added to 'User->Res'.
3157//
3158// @param Set The input set.
3159// @param N The dimension to map to.
3160//
3161// @returns Zero if no error occurred, non-zero otherwise.
3162static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3163 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3164 int Dim;
3165 isl_space *Space;
3166 isl_pw_multi_aff *PMA;
3167
3168 Dim = isl_set_dim(Set, isl_dim_set);
3169 Space = isl_set_get_space(Set);
3170 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3171 Dim - Data->N);
3172 if (Data->N > 1)
3173 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3174 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3175
3176 isl_set_free(Set);
3177
3178 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003179}
3180
Tobias Grosser808cd692015-07-14 09:33:13 +00003181// @brief Create a function that maps the elements of Domain to their Nth
3182// dimension.
3183//
3184// @param Domain The set of elements to map.
3185// @param N The dimension to map to.
3186static __isl_give isl_multi_union_pw_aff *
3187mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003188 if (N <= 0 || isl_union_set_is_empty(Domain)) {
3189 isl_union_set_free(Domain);
3190 return nullptr;
3191 }
3192
Tobias Grosser808cd692015-07-14 09:33:13 +00003193 struct MapToDimensionDataTy Data;
3194 isl_space *Space;
3195
3196 Space = isl_union_set_get_space(Domain);
3197 Data.N = N;
3198 Data.Res = isl_union_pw_multi_aff_empty(Space);
3199 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
3200 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
3201
3202 isl_union_set_free(Domain);
3203 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3204}
3205
Michael Kruse9d080092015-09-11 21:41:48 +00003206ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003207 ScopStmt *Stmt;
3208 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003209 Stmts.emplace_back(*this, *BB);
Tobias Grosser808cd692015-07-14 09:33:13 +00003210 Stmt = &Stmts.back();
3211 StmtMap[BB] = Stmt;
3212 } else {
3213 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003214 Stmts.emplace_back(*this, *R);
Tobias Grosser808cd692015-07-14 09:33:13 +00003215 Stmt = &Stmts.back();
3216 for (BasicBlock *BB : R->blocks())
3217 StmtMap[BB] = Stmt;
3218 }
3219 return Stmt;
3220}
3221
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003222void Scop::buildSchedule(
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003223 Region *R,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003224 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00003225
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003226 if (SD.isNonAffineSubRegion(R, &getRegion())) {
Johannes Doerfertc6987c12015-09-26 13:41:43 +00003227 Loop *L = getLoopSurroundingRegion(*R, LI);
3228 auto &LSchedulePair = LoopSchedules[L];
Michael Krusecac948e2015-10-02 13:53:07 +00003229 ScopStmt *Stmt = getStmtForBasicBlock(R->getEntry());
Michael Kruseafe06702015-10-02 16:33:27 +00003230 isl_set *Domain = Stmt->getDomain();
Michael Krusecac948e2015-10-02 13:53:07 +00003231 auto *UDomain = isl_union_set_from_set(Domain);
3232 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003233 LSchedulePair.first = StmtSchedule;
3234 return;
3235 }
3236
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003237 ReversePostOrderTraversal<Region *> RTraversal(R);
3238 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00003239
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003240 if (RN->isSubRegion()) {
3241 Region *SubRegion = RN->getNodeAs<Region>();
3242 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003243 buildSchedule(SubRegion, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003244 continue;
3245 }
Tobias Grosser75805372011-04-29 06:27:02 +00003246 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003247
3248 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert30c22652015-10-18 21:17:11 +00003249 if (!getRegion().contains(L))
3250 L = getLoopSurroundingRegion(getRegion(), LI);
3251
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003252 int LD = getRelativeLoopDepth(L);
3253 auto &LSchedulePair = LoopSchedules[L];
3254 LSchedulePair.second += getNumBlocksInRegionNode(RN);
3255
Michael Krusecac948e2015-10-02 13:53:07 +00003256 BasicBlock *BB = getRegionNodeBasicBlock(RN);
3257 ScopStmt *Stmt = getStmtForBasicBlock(BB);
3258 if (Stmt) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003259 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3260 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
3261 LSchedulePair.first =
3262 combineInSequence(LSchedulePair.first, StmtSchedule);
3263 }
3264
3265 unsigned NumVisited = LSchedulePair.second;
3266 while (L && NumVisited == L->getNumBlocks()) {
3267 auto *LDomain = isl_schedule_get_domain(LSchedulePair.first);
3268 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
3269 LSchedulePair.first =
3270 isl_schedule_insert_partial_schedule(LSchedulePair.first, MUPA);
3271
3272 auto *PL = L->getParentLoop();
Johannes Doerfertdca28372015-11-03 00:28:07 +00003273
3274 // Either we have a proper loop and we also build a schedule for the
3275 // parent loop or we have a infinite loop that does not have a proper
3276 // parent loop. In the former case this conditional will be skipped, in
3277 // the latter case however we will break here as we do not build a domain
3278 // nor a schedule for a infinite loop.
3279 assert(LoopSchedules.count(PL) || LSchedulePair.first == nullptr);
3280 if (!LoopSchedules.count(PL))
3281 break;
3282
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003283 auto &PSchedulePair = LoopSchedules[PL];
3284 PSchedulePair.first =
3285 combineInSequence(PSchedulePair.first, LSchedulePair.first);
3286 PSchedulePair.second += NumVisited;
3287
3288 L = PL;
3289 NumVisited = PSchedulePair.second;
3290 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003291 }
Tobias Grosser75805372011-04-29 06:27:02 +00003292}
3293
Johannes Doerfert7c494212014-10-31 23:13:39 +00003294ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003295 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003296 if (StmtMapIt == StmtMap.end())
3297 return nullptr;
3298 return StmtMapIt->second;
3299}
3300
Johannes Doerfert96425c22015-08-30 21:13:53 +00003301int Scop::getRelativeLoopDepth(const Loop *L) const {
3302 Loop *OuterLoop =
3303 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3304 if (!OuterLoop)
3305 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003306 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3307}
3308
Michael Krused868b5d2015-09-10 15:25:24 +00003309void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003310 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003311
3312 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3313 // true, are not modeled as ordinary PHI nodes as they are not part of the
3314 // region. However, we model the operands in the predecessor blocks that are
3315 // part of the region as regular scalar accesses.
3316
3317 // If we can synthesize a PHI we can skip it, however only if it is in
3318 // the region. If it is not it can only be in the exit block of the region.
3319 // In this case we model the operands but not the PHI itself.
3320 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3321 return;
3322
3323 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3324 // detection. Hence, the PHI is a load of a new memory location in which the
3325 // incoming value was written at the end of the incoming basic block.
3326 bool OnlyNonAffineSubRegionOperands = true;
3327 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3328 Value *Op = PHI->getIncomingValue(u);
3329 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3330
3331 // Do not build scalar dependences inside a non-affine subregion.
3332 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3333 continue;
3334
3335 OnlyNonAffineSubRegionOperands = false;
3336
3337 if (!R.contains(OpBB))
3338 continue;
3339
3340 Instruction *OpI = dyn_cast<Instruction>(Op);
3341 if (OpI) {
3342 BasicBlock *OpIBB = OpI->getParent();
3343 // As we pretend there is a use (or more precise a write) of OpI in OpBB
3344 // we have to insert a scalar dependence from the definition of OpI to
3345 // OpBB if the definition is not in OpBB.
Michael Kruse668af712015-10-15 14:45:48 +00003346 if (scop->getStmtForBasicBlock(OpIBB) !=
3347 scop->getStmtForBasicBlock(OpBB)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003348 addScalarReadAccess(OpI, PHI, OpBB);
3349 addScalarWriteAccess(OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003350 }
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003351 } else if (ModelReadOnlyScalars && !isa<Constant>(Op)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003352 addScalarReadAccess(Op, PHI, OpBB);
Michael Kruse7bf39442015-09-10 12:46:52 +00003353 }
3354
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003355 addPHIWriteAccess(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003356 }
3357
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003358 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3359 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003360 }
3361}
3362
Michael Krused868b5d2015-09-10 15:25:24 +00003363bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
3364 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003365 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
3366 if (isIgnoredIntrinsic(Inst))
3367 return false;
3368
3369 bool AnyCrossStmtUse = false;
3370 BasicBlock *ParentBB = Inst->getParent();
3371
3372 for (User *U : Inst->users()) {
3373 Instruction *UI = dyn_cast<Instruction>(U);
3374
3375 // Ignore the strange user
3376 if (UI == 0)
3377 continue;
3378
3379 BasicBlock *UseParent = UI->getParent();
3380
Tobias Grosserbaffa092015-10-24 20:55:27 +00003381 // Ignore basic block local uses. A value that is defined in a scop, but
3382 // used in a PHI node in the same basic block does not count as basic block
3383 // local, as for such cases a control flow edge is passed between definition
3384 // and use.
3385 if (UseParent == ParentBB && !isa<PHINode>(UI))
Michael Kruse7bf39442015-09-10 12:46:52 +00003386 continue;
3387
Michael Krusef714d472015-11-05 13:18:43 +00003388 // Uses by PHI nodes in the entry node count as external uses in case the
3389 // use is through an incoming block that is itself not contained in the
3390 // region.
3391 if (R->getEntry() == UseParent) {
3392 if (auto *PHI = dyn_cast<PHINode>(UI)) {
3393 bool ExternalUse = false;
3394 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
3395 if (PHI->getIncomingValue(i) == Inst &&
3396 !R->contains(PHI->getIncomingBlock(i))) {
3397 ExternalUse = true;
3398 break;
3399 }
3400 }
3401
3402 if (ExternalUse) {
3403 AnyCrossStmtUse = true;
3404 continue;
3405 }
3406 }
3407 }
3408
Michael Kruse7bf39442015-09-10 12:46:52 +00003409 // Do not build scalar dependences inside a non-affine subregion.
3410 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
3411 continue;
3412
Michael Kruse01cb3792015-10-17 21:07:08 +00003413 // Check for PHI nodes in the region exit and skip them, if they will be
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003414 // modeled as PHI nodes.
Michael Kruse01cb3792015-10-17 21:07:08 +00003415 //
3416 // PHI nodes in the region exit that have more than two incoming edges need
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003417 // to be modeled as PHI-Nodes to correctly model the fact that depending on
3418 // the control flow a different value will be assigned to the PHI node. In
3419 // case this is the case, there is no need to create an additional normal
3420 // scalar dependence. Hence, bail out before we register an "out-of-region"
3421 // use for this definition.
Michael Kruse01cb3792015-10-17 21:07:08 +00003422 if (isa<PHINode>(UI) && UI->getParent() == R->getExit() &&
3423 !R->getExitingBlock())
3424 continue;
3425
Michael Kruse7bf39442015-09-10 12:46:52 +00003426 // Check whether or not the use is in the SCoP.
Tobias Grosserc73d8b02015-10-23 22:36:22 +00003427 if (!R->contains(UseParent)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003428 AnyCrossStmtUse = true;
3429 continue;
3430 }
3431
3432 // If the instruction can be synthesized and the user is in the region
3433 // we do not need to add scalar dependences.
3434 if (canSynthesizeInst)
3435 continue;
3436
3437 // No need to translate these scalar dependences into polyhedral form,
3438 // because synthesizable scalars can be generated by the code generator.
3439 if (canSynthesize(UI, LI, SE, R))
3440 continue;
3441
3442 // Skip PHI nodes in the region as they handle their operands on their own.
3443 if (isa<PHINode>(UI))
3444 continue;
3445
3446 // Now U is used in another statement.
3447 AnyCrossStmtUse = true;
3448
3449 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00003450 // Use the def instruction as base address of the MemoryAccess, so that it
3451 // will become the name of the scalar access in the polyhedral form.
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003452 addScalarReadAccess(Inst, UI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003453 }
3454
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003455 if (ModelReadOnlyScalars && !isa<PHINode>(Inst)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003456 for (Value *Op : Inst->operands()) {
3457 if (canSynthesize(Op, LI, SE, R))
3458 continue;
3459
3460 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
3461 if (R->contains(OpInst))
3462 continue;
3463
3464 if (isa<Constant>(Op))
3465 continue;
3466
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003467 addScalarReadAccess(Op, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003468 }
3469 }
3470
3471 return AnyCrossStmtUse;
3472}
3473
3474extern MapInsnToMemAcc InsnToMemAcc;
3475
Michael Krusee2bccbb2015-09-18 19:59:43 +00003476void ScopInfo::buildMemoryAccess(
3477 Instruction *Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003478 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3479 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003480 unsigned Size;
3481 Type *SizeType;
3482 Value *Val;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003483 enum MemoryAccess::AccessType Type;
Michael Kruse7bf39442015-09-10 12:46:52 +00003484
3485 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
3486 SizeType = Load->getType();
3487 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003488 Type = MemoryAccess::READ;
Michael Kruse7bf39442015-09-10 12:46:52 +00003489 Val = Load;
3490 } else {
3491 StoreInst *Store = cast<StoreInst>(Inst);
3492 SizeType = Store->getValueOperand()->getType();
3493 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003494 Type = MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003495 Val = Store->getValueOperand();
3496 }
3497
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003498 auto Address = getPointerOperand(*Inst);
3499
3500 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003501 const SCEVUnknown *BasePointer =
3502 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3503
3504 assert(BasePointer && "Could not find base pointer");
3505 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
3506
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003507 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3508 auto NewAddress = Address;
3509 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3510 auto Src = BitCast->getOperand(0);
3511 auto SrcTy = Src->getType();
3512 auto DstTy = BitCast->getType();
3513 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3514 NewAddress = Src;
3515 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003516
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003517 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3518 std::vector<const SCEV *> Subscripts;
3519 std::vector<int> Sizes;
3520 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3521 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003522
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003523 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003524
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003525 bool AllAffineSubcripts = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003526 for (auto Subscript : Subscripts) {
3527 InvariantLoadsSetTy AccessILS;
3528 AllAffineSubcripts =
3529 isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS);
3530
3531 for (LoadInst *LInst : AccessILS)
3532 if (!ScopRIL.count(LInst))
3533 AllAffineSubcripts = false;
3534
3535 if (!AllAffineSubcripts)
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003536 break;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003537 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003538
3539 if (AllAffineSubcripts && Sizes.size() > 0) {
3540 for (auto V : Sizes)
3541 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3542 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003543 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003544 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003545
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003546 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3547 Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00003548 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003549 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003550 }
3551 }
3552
Michael Kruse7bf39442015-09-10 12:46:52 +00003553 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003554 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003555 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3556 AccItr->second.DelinearizedSubscripts,
3557 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003558 return;
3559 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003560
3561 // Check if the access depends on a loop contained in a non-affine subregion.
3562 bool isVariantInNonAffineLoop = false;
3563 if (BoxedLoops) {
3564 SetVector<const Loop *> Loops;
3565 findLoops(AccessFunction, Loops);
3566 for (const Loop *L : Loops)
3567 if (BoxedLoops->count(L))
3568 isVariantInNonAffineLoop = true;
3569 }
3570
Johannes Doerfert09e36972015-10-07 20:17:36 +00003571 InvariantLoadsSetTy AccessILS;
3572 bool IsAffine =
3573 !isVariantInNonAffineLoop &&
3574 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3575
3576 for (LoadInst *LInst : AccessILS)
3577 if (!ScopRIL.count(LInst))
3578 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003579
Michael Krusecaac2b62015-09-26 15:51:44 +00003580 // FIXME: Size of the number of bytes of an array element, not the number of
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003581 // elements as probably intended here.
Tobias Grossera43b6e92015-09-27 17:54:50 +00003582 const SCEV *SizeSCEV =
3583 SE->getConstant(TD->getIntPtrType(Inst->getContext()), Size);
Michael Kruse7bf39442015-09-10 12:46:52 +00003584
Michael Krusee2bccbb2015-09-18 19:59:43 +00003585 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3586 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003587
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003588 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, IsAffine,
3589 ArrayRef<const SCEV *>(AccessFunction),
3590 ArrayRef<const SCEV *>(SizeSCEV), Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003591}
3592
Michael Krused868b5d2015-09-10 15:25:24 +00003593void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003594
3595 if (SD->isNonAffineSubRegion(&SR, &R)) {
3596 for (BasicBlock *BB : SR.blocks())
3597 buildAccessFunctions(R, *BB, &SR);
3598 return;
3599 }
3600
3601 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3602 if (I->isSubRegion())
3603 buildAccessFunctions(R, *I->getNodeAs<Region>());
3604 else
3605 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
3606}
3607
Michael Krusecac948e2015-10-02 13:53:07 +00003608void ScopInfo::buildStmts(Region &SR) {
3609 Region *R = getRegion();
3610
3611 if (SD->isNonAffineSubRegion(&SR, R)) {
3612 scop->addScopStmt(nullptr, &SR);
3613 return;
3614 }
3615
3616 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3617 if (I->isSubRegion())
3618 buildStmts(*I->getNodeAs<Region>());
3619 else
3620 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
3621}
3622
Michael Krused868b5d2015-09-10 15:25:24 +00003623void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
3624 Region *NonAffineSubRegion,
3625 bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003626 Loop *L = LI->getLoopFor(&BB);
3627
3628 // The set of loops contained in non-affine subregions that are part of R.
3629 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3630
Johannes Doerfert09e36972015-10-07 20:17:36 +00003631 // The set of loads that are required to be invariant.
3632 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
3633
Michael Kruse7bf39442015-09-10 12:46:52 +00003634 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00003635 Instruction *Inst = &*I;
Michael Kruse7bf39442015-09-10 12:46:52 +00003636
3637 PHINode *PHI = dyn_cast<PHINode>(Inst);
3638 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003639 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003640
3641 // For the exit block we stop modeling after the last PHI node.
3642 if (!PHI && IsExitBlock)
3643 break;
3644
Johannes Doerfert09e36972015-10-07 20:17:36 +00003645 // TODO: At this point we only know that elements of ScopRIL have to be
3646 // invariant and will be hoisted for the SCoP to be processed. Though,
3647 // there might be other invariant accesses that will be hoisted and
3648 // that would allow to make a non-affine access affine.
Michael Kruse7bf39442015-09-10 12:46:52 +00003649 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
Johannes Doerfert09e36972015-10-07 20:17:36 +00003650 buildMemoryAccess(Inst, L, &R, BoxedLoops, ScopRIL);
Michael Kruse7bf39442015-09-10 12:46:52 +00003651
3652 if (isIgnoredIntrinsic(Inst))
3653 continue;
3654
Johannes Doerfert09e36972015-10-07 20:17:36 +00003655 // Do not build scalar dependences for required invariant loads as we will
3656 // hoist them later on anyway or drop the SCoP if we cannot.
3657 if (ScopRIL.count(dyn_cast<LoadInst>(Inst)))
3658 continue;
3659
Michael Kruse7bf39442015-09-10 12:46:52 +00003660 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00003661 if (!isa<StoreInst>(Inst))
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003662 addScalarWriteAccess(Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003663 }
3664 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003665}
Michael Kruse7bf39442015-09-10 12:46:52 +00003666
Michael Kruse2d0ece92015-09-24 11:41:21 +00003667void ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3668 MemoryAccess::AccessType Type,
3669 Value *BaseAddress, unsigned ElemBytes,
3670 bool Affine, Value *AccessValue,
3671 ArrayRef<const SCEV *> Subscripts,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003672 ArrayRef<const SCEV *> Sizes,
3673 MemoryAccess::AccessOrigin Origin) {
Michael Krusecac948e2015-10-02 13:53:07 +00003674 ScopStmt *Stmt = scop->getStmtForBasicBlock(BB);
3675
3676 // Do not create a memory access for anything not in the SCoP. It would be
3677 // ignored anyway.
3678 if (!Stmt)
3679 return;
3680
Michael Krusee2bccbb2015-09-18 19:59:43 +00003681 AccFuncSetType &AccList = AccFuncMap[BB];
Michael Krusee2bccbb2015-09-18 19:59:43 +00003682 Value *BaseAddr = BaseAddress;
3683 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3684
Michael Krusecac948e2015-10-02 13:53:07 +00003685 bool isApproximated =
3686 Stmt->isRegionStmt() && (Stmt->getRegion()->getEntry() != BB);
3687 if (isApproximated && Type == MemoryAccess::MUST_WRITE)
3688 Type = MemoryAccess::MAY_WRITE;
3689
Tobias Grosserf1bfd752015-11-05 20:15:37 +00003690 AccList.emplace_back(Stmt, Inst, Type, BaseAddress, ElemBytes, Affine,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003691 Subscripts, Sizes, AccessValue, Origin, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00003692 Stmt->addAccess(&AccList.back());
Michael Kruse7bf39442015-09-10 12:46:52 +00003693}
3694
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003695void ScopInfo::addExplicitAccess(
3696 Instruction *MemAccInst, MemoryAccess::AccessType Type, Value *BaseAddress,
3697 unsigned ElemBytes, bool IsAffine, ArrayRef<const SCEV *> Subscripts,
3698 ArrayRef<const SCEV *> Sizes, Value *AccessValue) {
3699 assert(isa<LoadInst>(MemAccInst) || isa<StoreInst>(MemAccInst));
3700 assert(isa<LoadInst>(MemAccInst) == (Type == MemoryAccess::READ));
3701 addMemoryAccess(MemAccInst->getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003702 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
3703 MemoryAccess::EXPLICIT);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003704}
3705void ScopInfo::addScalarWriteAccess(Instruction *Value) {
3706 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
3707 true, Value, ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003708 ArrayRef<const SCEV *>(), MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003709}
3710void ScopInfo::addScalarReadAccess(Value *Value, Instruction *User) {
3711 assert(!isa<PHINode>(User));
3712 addMemoryAccess(User->getParent(), User, MemoryAccess::READ, Value, 1, true,
3713 Value, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003714 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003715}
3716void ScopInfo::addScalarReadAccess(Value *Value, PHINode *User,
3717 BasicBlock *UserBB) {
3718 addMemoryAccess(UserBB, User, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003719 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3720 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003721}
3722void ScopInfo::addPHIWriteAccess(PHINode *PHI, BasicBlock *IncomingBlock,
3723 Value *IncomingValue, bool IsExitBlock) {
3724 addMemoryAccess(IncomingBlock, IncomingBlock->getTerminator(),
3725 MemoryAccess::MUST_WRITE, PHI, 1, true, IncomingValue,
3726 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003727 IsExitBlock ? MemoryAccess::SCALAR : MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003728}
3729void ScopInfo::addPHIReadAccess(PHINode *PHI) {
3730 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003731 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3732 MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003733}
3734
Michael Kruse76e924d2015-09-30 09:16:07 +00003735void ScopInfo::buildScop(Region &R, DominatorTree &DT) {
Michael Kruse9d080092015-09-11 21:41:48 +00003736 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003737 scop = new Scop(R, AccFuncMap, *SD, *SE, DT, *LI, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00003738
Michael Krusecac948e2015-10-02 13:53:07 +00003739 buildStmts(R);
Michael Kruse7bf39442015-09-10 12:46:52 +00003740 buildAccessFunctions(R, R);
3741
3742 // In case the region does not have an exiting block we will later (during
3743 // code generation) split the exit block. This will move potential PHI nodes
3744 // from the current exit block into the new region exiting block. Hence, PHI
3745 // nodes that are at this point not part of the region will be.
3746 // To handle these PHI nodes later we will now model their operands as scalar
3747 // accesses. Note that we do not model anything in the exit block if we have
3748 // an exiting block in the region, as there will not be any splitting later.
3749 if (!R.getExitingBlock())
3750 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
3751
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003752 scop->init(*AA);
Michael Kruse7bf39442015-09-10 12:46:52 +00003753}
3754
Michael Krused868b5d2015-09-10 15:25:24 +00003755void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00003756 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00003757 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00003758 return;
3759 }
3760
Michael Kruse9d080092015-09-11 21:41:48 +00003761 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00003762}
3763
Michael Krused868b5d2015-09-10 15:25:24 +00003764void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00003765 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00003766 if (scop) {
3767 delete scop;
3768 scop = 0;
3769 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003770}
3771
3772//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00003773ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00003774 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00003775 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00003776}
3777
3778ScopInfo::~ScopInfo() {
3779 clear();
3780 isl_ctx_free(ctx);
3781}
3782
Tobias Grosser75805372011-04-29 06:27:02 +00003783void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00003784 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00003785 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00003786 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00003787 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
3788 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003789 AU.addRequired<AAResultsWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00003790 AU.setPreservesAll();
3791}
3792
3793bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00003794 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00003795
Michael Krused868b5d2015-09-10 15:25:24 +00003796 if (!SD->isMaxRegionInScop(*R))
3797 return false;
3798
3799 Function *F = R->getEntry()->getParent();
3800 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3801 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3802 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3803 TD = &F->getParent()->getDataLayout();
3804 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Krused868b5d2015-09-10 15:25:24 +00003805
Michael Kruse76e924d2015-09-30 09:16:07 +00003806 buildScop(*R, DT);
Tobias Grosser75805372011-04-29 06:27:02 +00003807
Tobias Grosserd6a50b32015-05-30 06:26:21 +00003808 DEBUG(scop->print(dbgs()));
3809
Michael Kruseafe06702015-10-02 16:33:27 +00003810 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003811 delete scop;
3812 scop = nullptr;
3813 return false;
3814 }
3815
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003816 // Statistics.
3817 ++ScopFound;
3818 if (scop->getMaxLoopDepth() > 0)
3819 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00003820 return false;
3821}
3822
3823char ScopInfo::ID = 0;
3824
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003825Pass *polly::createScopInfoPass() { return new ScopInfo(); }
3826
Tobias Grosser73600b82011-10-08 00:30:40 +00003827INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
3828 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003829 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003830INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00003831INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00003832INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00003833INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003834INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003835INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00003836INITIALIZE_PASS_END(ScopInfo, "polly-scops",
3837 "Polly - Create polyhedral description of Scops", false,
3838 false)