blob: 33c5cdf165a95f708d673f270e35d59763669ff5 [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 Grosser9737c7b2015-11-22 11:06:51 +000026#include "llvm/ADT/DepthFirstIterator.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000027#include "llvm/ADT/MapVector.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000028#include "llvm/ADT/PostOrderIterator.h"
29#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000030#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000031#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000032#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000033#include "llvm/Analysis/AliasAnalysis.h"
Johannes Doerfert2af10e22015-11-12 03:25:01 +000034#include "llvm/Analysis/AssumptionCache.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000035#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000036#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000037#include "llvm/Analysis/RegionIterator.h"
38#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Johannes Doerfert48fe86f2015-11-12 02:32:32 +000039#include "llvm/IR/DiagnosticInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000040#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000041#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000042#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000043#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000044#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000045#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000046#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000047#include "isl/schedule.h"
48#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000049#include "isl/set.h"
50#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000051#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000052#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000053#include <sstream>
54#include <string>
55#include <vector>
56
57using namespace llvm;
58using namespace polly;
59
Chandler Carruth95fef942014-04-22 03:30:19 +000060#define DEBUG_TYPE "polly-scops"
61
Tobias Grosser74394f02013-01-14 22:40:23 +000062STATISTIC(ScopFound, "Number of valid Scops");
63STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000064
Michael Kruse7bf39442015-09-10 12:46:52 +000065static cl::opt<bool> ModelReadOnlyScalars(
66 "polly-analyze-read-only-scalars",
67 cl::desc("Model read-only scalar values in the scop description"),
68 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
69
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000070// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000071// operations can overflow easily. Additive reductions and bit operations
72// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000073static cl::opt<bool> DisableMultiplicativeReductions(
74 "polly-disable-multiplicative-reductions",
75 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
76 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000077
Johannes Doerfert9143d672014-09-27 11:02:39 +000078static cl::opt<unsigned> RunTimeChecksMaxParameters(
79 "polly-rtc-max-parameters",
80 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
81 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
82
Tobias Grosser71500722015-03-28 15:11:14 +000083static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
84 "polly-rtc-max-arrays-per-group",
85 cl::desc("The maximal number of arrays to compare in each alias group."),
86 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000087static cl::opt<std::string> UserContextStr(
88 "polly-context", cl::value_desc("isl parameter set"),
89 cl::desc("Provide additional constraints on the context parameters"),
90 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000091
Tobias Grosserd83b8a82015-08-20 19:08:11 +000092static cl::opt<bool> DetectReductions("polly-detect-reductions",
93 cl::desc("Detect and exploit reductions"),
94 cl::Hidden, cl::ZeroOrMore,
95 cl::init(true), cl::cat(PollyCategory));
96
Tobias Grosser20a4c0c2015-11-11 16:22:36 +000097static cl::opt<int> MaxDisjunctsAssumed(
98 "polly-max-disjuncts-assumed",
99 cl::desc("The maximal number of disjuncts we allow in the assumption "
100 "context (this bounds compile time)"),
101 cl::Hidden, cl::ZeroOrMore, cl::init(150), cl::cat(PollyCategory));
102
Tobias Grosser4927c8e2015-11-24 12:50:02 +0000103static cl::opt<bool> IgnoreIntegerWrapping(
104 "polly-ignore-integer-wrapping",
105 cl::desc("Do not build run-time checks to proof absence of integer "
106 "wrapping"),
107 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
108
Michael Kruse7bf39442015-09-10 12:46:52 +0000109//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000110
Michael Kruse046dde42015-08-10 13:01:57 +0000111// Create a sequence of two schedules. Either argument may be null and is
112// interpreted as the empty schedule. Can also return null if both schedules are
113// empty.
114static __isl_give isl_schedule *
115combineInSequence(__isl_take isl_schedule *Prev,
116 __isl_take isl_schedule *Succ) {
117 if (!Prev)
118 return Succ;
119 if (!Succ)
120 return Prev;
121
122 return isl_schedule_sequence(Prev, Succ);
123}
124
Johannes Doerferte7044942015-02-24 11:58:30 +0000125static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
126 const ConstantRange &Range,
127 int dim,
128 enum isl_dim_type type) {
129 isl_val *V;
130 isl_ctx *ctx = isl_set_get_ctx(S);
131
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000132 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
133 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000134 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000135 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
136
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000137 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000138 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000139 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000140 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000141 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
142
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000143 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000144 return isl_set_union(SLB, SUB);
145 else
146 return isl_set_intersect(SLB, SUB);
147}
148
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000149static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
150 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
151 if (!BasePtrLI)
152 return nullptr;
153
154 if (!S->getRegion().contains(BasePtrLI))
155 return nullptr;
156
157 ScalarEvolution &SE = *S->getSE();
158
159 auto *OriginBaseSCEV =
160 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
161 if (!OriginBaseSCEV)
162 return nullptr;
163
164 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
165 if (!OriginBaseSCEVUnknown)
166 return nullptr;
167
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000168 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
169 ScopArrayInfo::KIND_ARRAY);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000170}
171
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000172ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000173 ArrayRef<const SCEV *> Sizes, enum ARRAYKIND Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000174 const DataLayout &DL, Scop *S)
175 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000176 std::string BasePtrName =
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000177 getIslCompatibleName("MemRef_", BasePtr, Kind == KIND_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000178 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000179
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000180 updateSizes(Sizes);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000181 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
182 if (BasePtrOriginSAI)
183 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000184}
185
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000186__isl_give isl_space *ScopArrayInfo::getSpace() const {
187 auto Space =
188 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
189 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
190 return Space;
191}
192
Tobias Grosser8286b832015-11-02 11:29:32 +0000193bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000194 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
195 int ExtraDimsNew = NewSizes.size() - SharedDims;
196 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Tobias Grosser8286b832015-11-02 11:29:32 +0000197 for (int i = 0; i < SharedDims; i++)
198 if (NewSizes[i + ExtraDimsNew] != DimensionSizes[i + ExtraDimsOld])
199 return false;
200
201 if (DimensionSizes.size() >= NewSizes.size())
202 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000203
204 DimensionSizes.clear();
205 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
206 NewSizes.end());
207 for (isl_pw_aff *Size : DimensionSizesPw)
208 isl_pw_aff_free(Size);
209 DimensionSizesPw.clear();
210 for (const SCEV *Expr : DimensionSizes) {
211 isl_pw_aff *Size = S.getPwAff(Expr);
212 DimensionSizesPw.push_back(Size);
213 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000214 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000215}
216
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000217ScopArrayInfo::~ScopArrayInfo() {
218 isl_id_free(Id);
219 for (isl_pw_aff *Size : DimensionSizesPw)
220 isl_pw_aff_free(Size);
221}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000222
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000223std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
224
225int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000226 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000227}
228
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000229isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
230
231void ScopArrayInfo::dump() const { print(errs()); }
232
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000233void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000234 OS.indent(8) << *getElementType() << " " << getName();
235 if (getNumberOfDimensions() > 0)
236 OS << "[*]";
Tobias Grosser26253842015-11-10 14:24:21 +0000237 for (unsigned u = 1; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000238 OS << "[";
239
Tobias Grosser26253842015-11-10 14:24:21 +0000240 if (SizeAsPwAff) {
241 auto Size = getDimensionSizePw(u);
242 OS << " " << Size << " ";
243 isl_pw_aff_free(Size);
244 } else {
245 OS << *getDimensionSize(u);
246 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000247
248 OS << "]";
249 }
250
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000251 OS << ";";
252
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000253 if (BasePtrOriginSAI)
254 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
255
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000256 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000257}
258
259const ScopArrayInfo *
260ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
261 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
262 assert(Id && "Output dimension didn't have an ID");
263 return getFromId(Id);
264}
265
266const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
267 void *User = isl_id_get_user(Id);
268 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
269 isl_id_free(Id);
270 return SAI;
271}
272
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000273void MemoryAccess::updateDimensionality() {
274 auto ArraySpace = getScopArrayInfo()->getSpace();
275 auto AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
276
277 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
278 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
279 auto DimsMissing = DimsArray - DimsAccess;
280
281 auto Map = isl_map_from_domain_and_range(isl_set_universe(AccessSpace),
282 isl_set_universe(ArraySpace));
283
284 for (unsigned i = 0; i < DimsMissing; i++)
285 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
286
287 for (unsigned i = DimsMissing; i < DimsArray; i++)
288 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
289
290 AccessRelation = isl_map_apply_range(AccessRelation, Map);
291}
292
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000293const std::string
294MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
295 switch (RT) {
296 case MemoryAccess::RT_NONE:
297 llvm_unreachable("Requested a reduction operator string for a memory "
298 "access which isn't a reduction");
299 case MemoryAccess::RT_ADD:
300 return "+";
301 case MemoryAccess::RT_MUL:
302 return "*";
303 case MemoryAccess::RT_BOR:
304 return "|";
305 case MemoryAccess::RT_BXOR:
306 return "^";
307 case MemoryAccess::RT_BAND:
308 return "&";
309 }
310 llvm_unreachable("Unknown reduction type");
311 return "";
312}
313
Johannes Doerfertf6183392014-07-01 20:52:51 +0000314/// @brief Return the reduction type for a given binary operator
315static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
316 const Instruction *Load) {
317 if (!BinOp)
318 return MemoryAccess::RT_NONE;
319 switch (BinOp->getOpcode()) {
320 case Instruction::FAdd:
321 if (!BinOp->hasUnsafeAlgebra())
322 return MemoryAccess::RT_NONE;
323 // Fall through
324 case Instruction::Add:
325 return MemoryAccess::RT_ADD;
326 case Instruction::Or:
327 return MemoryAccess::RT_BOR;
328 case Instruction::Xor:
329 return MemoryAccess::RT_BXOR;
330 case Instruction::And:
331 return MemoryAccess::RT_BAND;
332 case Instruction::FMul:
333 if (!BinOp->hasUnsafeAlgebra())
334 return MemoryAccess::RT_NONE;
335 // Fall through
336 case Instruction::Mul:
337 if (DisableMultiplicativeReductions)
338 return MemoryAccess::RT_NONE;
339 return MemoryAccess::RT_MUL;
340 default:
341 return MemoryAccess::RT_NONE;
342 }
343}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000344
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000345/// @brief Derive the individual index expressions from a GEP instruction
346///
347/// This function optimistically assumes the GEP references into a fixed size
348/// array. If this is actually true, this function returns a list of array
349/// subscript expressions as SCEV as well as a list of integers describing
350/// the size of the individual array dimensions. Both lists have either equal
351/// length of the size list is one element shorter in case there is no known
352/// size available for the outermost array dimension.
353///
354/// @param GEP The GetElementPtr instruction to analyze.
355///
356/// @return A tuple with the subscript expressions and the dimension sizes.
357static std::tuple<std::vector<const SCEV *>, std::vector<int>>
358getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
359 std::vector<const SCEV *> Subscripts;
360 std::vector<int> Sizes;
361
362 Type *Ty = GEP->getPointerOperandType();
363
364 bool DroppedFirstDim = false;
365
Michael Kruse26ed65e2015-09-24 17:32:49 +0000366 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000367
368 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
369
370 if (i == 1) {
371 if (auto PtrTy = dyn_cast<PointerType>(Ty)) {
372 Ty = PtrTy->getElementType();
373 } else if (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
374 Ty = ArrayTy->getElementType();
375 } else {
376 Subscripts.clear();
377 Sizes.clear();
378 break;
379 }
380 if (auto Const = dyn_cast<SCEVConstant>(Expr))
381 if (Const->getValue()->isZero()) {
382 DroppedFirstDim = true;
383 continue;
384 }
385 Subscripts.push_back(Expr);
386 continue;
387 }
388
389 auto ArrayTy = dyn_cast<ArrayType>(Ty);
390 if (!ArrayTy) {
391 Subscripts.clear();
392 Sizes.clear();
393 break;
394 }
395
396 Subscripts.push_back(Expr);
397 if (!(DroppedFirstDim && i == 2))
398 Sizes.push_back(ArrayTy->getNumElements());
399
400 Ty = ArrayTy->getElementType();
401 }
402
403 return std::make_tuple(Subscripts, Sizes);
404}
405
Tobias Grosser75805372011-04-29 06:27:02 +0000406MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000407 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000408 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000409 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000410}
411
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000412const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
413 isl_id *ArrayId = getArrayId();
414 void *User = isl_id_get_user(ArrayId);
415 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
416 isl_id_free(ArrayId);
417 return SAI;
418}
419
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000420__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000421 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
422}
423
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000424__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
425 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000426 isl_map *Schedule, *ScheduledAccRel;
427 isl_union_set *UDomain;
428
429 UDomain = isl_union_set_from_set(getStatement()->getDomain());
430 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
431 Schedule = isl_map_from_union_map(USchedule);
432 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
433 return isl_pw_multi_aff_from_map(ScheduledAccRel);
434}
435
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000436__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000437 return isl_map_copy(AccessRelation);
438}
439
Johannes Doerferta99130f2014-10-13 12:58:03 +0000440std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000441 return stringFromIslObj(AccessRelation);
442}
443
Johannes Doerferta99130f2014-10-13 12:58:03 +0000444__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000445 return isl_map_get_space(AccessRelation);
446}
447
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000448__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000449 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000450}
451
Tobias Grosser6f730082015-09-05 07:46:47 +0000452std::string MemoryAccess::getNewAccessRelationStr() const {
453 return stringFromIslObj(NewAccessRelation);
454}
455
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000456__isl_give isl_basic_map *
457MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000458 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000459 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000460
Tobias Grosser084d8f72012-05-29 09:29:44 +0000461 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000462 isl_basic_set_universe(Statement->getDomainSpace()),
463 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000464}
465
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000466// Formalize no out-of-bound access assumption
467//
468// When delinearizing array accesses we optimistically assume that the
469// delinearized accesses do not access out of bound locations (the subscript
470// expression of each array evaluates for each statement instance that is
471// executed to a value that is larger than zero and strictly smaller than the
472// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000473// dimension for which we do not need to assume any upper bound. At this point
474// we formalize this assumption to ensure that at code generation time the
475// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000476//
477// To find the set of constraints necessary to avoid out of bound accesses, we
478// first build the set of data locations that are not within array bounds. We
479// then apply the reverse access relation to obtain the set of iterations that
480// may contain invalid accesses and reduce this set of iterations to the ones
481// that are actually executed by intersecting them with the domain of the
482// statement. If we now project out all loop dimensions, we obtain a set of
483// parameters that may cause statement instances to be executed that may
484// possibly yield out of bound memory accesses. The complement of these
485// constraints is the set of constraints that needs to be assumed to ensure such
486// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000487void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000488 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000489 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Michael Krusee2bccbb2015-09-18 19:59:43 +0000490 for (int i = 1, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000491 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
492 isl_pw_aff *Var =
493 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
494 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
495
496 isl_set *DimOutside;
497
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000498 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Michael Krusee2bccbb2015-09-18 19:59:43 +0000499 isl_pw_aff *SizeE = Statement->getPwAff(Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000500
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000501 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
502 Statement->getNumIterators());
503 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
504 isl_space_dim(Space, isl_dim_set));
505 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
506 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000507
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000508 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000509
510 Outside = isl_set_union(Outside, DimOutside);
511 }
512
513 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
514 Outside = isl_set_intersect(Outside, Statement->getDomain());
515 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000516
517 // Remove divs to avoid the construction of overly complicated assumptions.
518 // Doing so increases the set of parameter combinations that are assumed to
519 // not appear. This is always save, but may make the resulting run-time check
520 // bail out more often than strictly necessary.
521 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000522 Outside = isl_set_complement(Outside);
Johannes Doerfertd84493e2015-11-12 02:33:38 +0000523 Statement->getParent()->addAssumption(INBOUNDS, Outside,
524 getAccessInstruction()->getDebugLoc());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000525 isl_space_free(Space);
526}
527
Johannes Doerferte7044942015-02-24 11:58:30 +0000528void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
529 ScalarEvolution *SE = Statement->getParent()->getSE();
530
531 Value *Ptr = getPointerOperand(*getAccessInstruction());
532 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
533 return;
534
535 auto *PtrSCEV = SE->getSCEV(Ptr);
536 if (isa<SCEVCouldNotCompute>(PtrSCEV))
537 return;
538
539 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
540 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
541 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
542
543 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
544 if (Range.isFullSet())
545 return;
546
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000547 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000548 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000549 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
550 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
551
552 auto Min = LB.sdiv(APInt(BW, ElementSize));
553 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000554
555 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
556 AccessRange =
557 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
558 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
559}
560
Michael Krusee2bccbb2015-09-18 19:59:43 +0000561__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000562 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000563 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000564
565 for (int i = Size - 2; i >= 0; --i) {
566 isl_space *Space;
567 isl_map *MapOne, *MapTwo;
Michael Krusee2bccbb2015-09-18 19:59:43 +0000568 isl_pw_aff *DimSize = Statement->getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000569
570 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
571 isl_pw_aff_free(DimSize);
572 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
573
574 Space = isl_map_get_space(AccessRelation);
575 Space = isl_space_map_from_set(isl_space_range(Space));
576 Space = isl_space_align_params(Space, SpaceSize);
577
578 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
579 isl_id_free(ParamId);
580
581 MapOne = isl_map_universe(isl_space_copy(Space));
582 for (int j = 0; j < Size; ++j)
583 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
584 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
585
586 MapTwo = isl_map_universe(isl_space_copy(Space));
587 for (int j = 0; j < Size; ++j)
588 if (j < i || j > i + 1)
589 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
590
591 isl_local_space *LS = isl_local_space_from_space(Space);
592 isl_constraint *C;
593 C = isl_equality_alloc(isl_local_space_copy(LS));
594 C = isl_constraint_set_constant_si(C, -1);
595 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
596 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
597 MapTwo = isl_map_add_constraint(MapTwo, C);
598 C = isl_equality_alloc(LS);
599 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
600 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
601 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
602 MapTwo = isl_map_add_constraint(MapTwo, C);
603 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
604
605 MapOne = isl_map_union(MapOne, MapTwo);
606 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
607 }
608 return AccessRelation;
609}
610
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000611/// @brief Check if @p Expr is divisible by @p Size.
612static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
613
614 // Only one factor needs to be divisible.
615 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
616 for (auto *FactorExpr : MulExpr->operands())
617 if (isDivisible(FactorExpr, Size, SE))
618 return true;
619 return false;
620 }
621
622 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
623 // to be divisble.
624 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
625 for (auto *OpExpr : NAryExpr->operands())
626 if (!isDivisible(OpExpr, Size, SE))
627 return false;
628 return true;
629 }
630
631 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
632 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
633 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
634 return MulSCEV == Expr;
635}
636
Michael Krusee2bccbb2015-09-18 19:59:43 +0000637void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
638 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000639
Michael Krusee2bccbb2015-09-18 19:59:43 +0000640 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000641 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000642
Michael Krusee2bccbb2015-09-18 19:59:43 +0000643 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000644 // We overapproximate non-affine accesses with a possible access to the
645 // whole array. For read accesses it does not make a difference, if an
646 // access must or may happen. However, for write accesses it is important to
647 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000648 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000649 AccessRelation =
650 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000651
Michael Krusee2bccbb2015-09-18 19:59:43 +0000652 computeBoundsOnAccessRelation(getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000653 return;
654 }
655
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000656 Scop &S = *getStatement()->getParent();
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000657 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000658 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000659
Michael Krusee2bccbb2015-09-18 19:59:43 +0000660 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
661 isl_pw_aff *Affine = Statement->getPwAff(Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000662
Sebastian Pop422e33f2014-06-03 18:16:31 +0000663 if (Size == 1) {
664 // For the non delinearized arrays, divide the access function of the last
665 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000666 //
667 // A stride one array access in C expressed as A[i] is expressed in
668 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
669 // two subsequent values of 'i' index two values that are stored next to
670 // each other in memory. By this division we make this characteristic
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000671 // obvious again. However, if the index is not divisible by the element
672 // size we will bail out.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000673 isl_val *v = isl_val_int_from_si(Ctx, getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000674 Affine = isl_pw_aff_scale_down_val(Affine, v);
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000675
676 if (!isDivisible(Subscripts[0], getElemSizeInBytes(), *S.getSE()))
677 S.addAssumption(ALIGNMENT, isl_set_empty(S.getParamSpace()),
678 AccessInstruction->getDebugLoc());
Sebastian Pop18016682014-04-08 21:20:44 +0000679 }
680
681 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
682
Tobias Grosser79baa212014-04-10 08:38:02 +0000683 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000684 }
685
Michael Krusee2bccbb2015-09-18 19:59:43 +0000686 if (Sizes.size() > 1 && !isa<SCEVConstant>(Sizes[0]))
687 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000688
Tobias Grosser79baa212014-04-10 08:38:02 +0000689 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000690 AccessRelation = isl_map_set_tuple_id(
691 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000692 AccessRelation =
693 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
694
Michael Krusee2bccbb2015-09-18 19:59:43 +0000695 assumeNoOutOfBound();
Tobias Grosseraa660a92015-03-30 00:07:50 +0000696 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000697 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000698}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000699
Michael Krusecac948e2015-10-02 13:53:07 +0000700MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000701 AccessType Type, Value *BaseAddress,
702 unsigned ElemBytes, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000703 ArrayRef<const SCEV *> Subscripts,
704 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Michael Kruse8d0b7342015-09-25 21:21:00 +0000705 AccessOrigin Origin, StringRef BaseName)
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000706 : Origin(Origin), AccType(Type), RedType(RT_NONE), Statement(Stmt),
Michael Krusecac948e2015-10-02 13:53:07 +0000707 BaseAddr(BaseAddress), BaseName(BaseName), ElemBytes(ElemBytes),
708 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
709 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000710 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000711 NewAccessRelation(nullptr) {
712
713 std::string IdName = "__polly_array_ref";
714 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
715}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000716
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000717void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000718 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000719 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000720}
721
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000722const std::string MemoryAccess::getReductionOperatorStr() const {
723 return MemoryAccess::getReductionOperatorStr(getReductionType());
724}
725
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000726__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
727
Johannes Doerfertf6183392014-07-01 20:52:51 +0000728raw_ostream &polly::operator<<(raw_ostream &OS,
729 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000730 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000731 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000732 else
733 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000734 return OS;
735}
736
Tobias Grosser75805372011-04-29 06:27:02 +0000737void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000738 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000739 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000740 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000741 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000742 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000743 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000744 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000745 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000746 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000747 break;
748 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000749 OS << "[Reduction Type: " << getReductionType() << "] ";
Michael Kruse8d0b7342015-09-25 21:21:00 +0000750 OS << "[Scalar: " << isImplicit() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000751 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000752 if (hasNewAccessRelation())
753 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000754}
755
Tobias Grosser74394f02013-01-14 22:40:23 +0000756void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000757
758// Create a map in the size of the provided set domain, that maps from the
759// one element of the provided set domain to another element of the provided
760// set domain.
761// The mapping is limited to all points that are equal in all but the last
762// dimension and for which the last dimension of the input is strict smaller
763// than the last dimension of the output.
764//
765// getEqualAndLarger(set[i0, i1, ..., iX]):
766//
767// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
768// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
769//
Tobias Grosserf5338802011-10-06 00:03:35 +0000770static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000771 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000772 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000773 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000774
775 // Set all but the last dimension to be equal for the input and output
776 //
777 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
778 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000779 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000780 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000781
782 // Set the last dimension of the input to be strict smaller than the
783 // last dimension of the output.
784 //
785 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000786 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
787 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000788 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000789}
790
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000791__isl_give isl_set *
792MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000793 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000794 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000795 isl_space *Space = isl_space_range(isl_map_get_space(S));
796 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000797
Sebastian Popa00a0292012-12-18 07:46:06 +0000798 S = isl_map_reverse(S);
799 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000800
Sebastian Popa00a0292012-12-18 07:46:06 +0000801 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
802 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
803 NextScatt = isl_map_apply_domain(NextScatt, S);
804 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000805
Sebastian Popa00a0292012-12-18 07:46:06 +0000806 isl_set *Deltas = isl_map_deltas(NextScatt);
807 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000808}
809
Sebastian Popa00a0292012-12-18 07:46:06 +0000810bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000811 int StrideWidth) const {
812 isl_set *Stride, *StrideX;
813 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000814
Sebastian Popa00a0292012-12-18 07:46:06 +0000815 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000816 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000817 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
818 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
819 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
820 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000821 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000822
Tobias Grosser28dd4862012-01-24 16:42:16 +0000823 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000824 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000825
Tobias Grosser28dd4862012-01-24 16:42:16 +0000826 return IsStrideX;
827}
828
Sebastian Popa00a0292012-12-18 07:46:06 +0000829bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
830 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000831}
832
Sebastian Popa00a0292012-12-18 07:46:06 +0000833bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
834 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000835}
836
Tobias Grosser166c4222015-09-05 07:46:40 +0000837void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
838 isl_map_free(NewAccessRelation);
839 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000840}
Tobias Grosser75805372011-04-29 06:27:02 +0000841
842//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000843
Tobias Grosser808cd692015-07-14 09:33:13 +0000844isl_map *ScopStmt::getSchedule() const {
845 isl_set *Domain = getDomain();
846 if (isl_set_is_empty(Domain)) {
847 isl_set_free(Domain);
848 return isl_map_from_aff(
849 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
850 }
851 auto *Schedule = getParent()->getSchedule();
852 Schedule = isl_union_map_intersect_domain(
853 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
854 if (isl_union_map_is_empty(Schedule)) {
855 isl_set_free(Domain);
856 isl_union_map_free(Schedule);
857 return isl_map_from_aff(
858 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
859 }
860 auto *M = isl_map_from_union_map(Schedule);
861 M = isl_map_coalesce(M);
862 M = isl_map_gist_domain(M, Domain);
863 M = isl_map_coalesce(M);
864 return M;
865}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000866
Johannes Doerfert574182d2015-08-12 10:19:50 +0000867__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000868 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
869 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000870}
871
Tobias Grosser37eb4222014-02-20 21:43:54 +0000872void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
873 assert(isl_set_is_subset(NewDomain, Domain) &&
874 "New domain is not a subset of old domain!");
875 isl_set_free(Domain);
876 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000877}
878
Michael Krusecac948e2015-10-02 13:53:07 +0000879void ScopStmt::buildAccessRelations() {
880 for (MemoryAccess *Access : MemAccs) {
881 Type *ElementType = Access->getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000882
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000883 ScopArrayInfo::ARRAYKIND Ty;
884 if (Access->isPHI())
885 Ty = ScopArrayInfo::KIND_PHI;
886 else if (Access->isImplicit())
887 Ty = ScopArrayInfo::KIND_SCALAR;
888 else
889 Ty = ScopArrayInfo::KIND_ARRAY;
890
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000891 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000892 Access->getBaseAddr(), ElementType, Access->Sizes, Ty);
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000893
Michael Krusecac948e2015-10-02 13:53:07 +0000894 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +0000895 }
896}
897
Michael Krusecac948e2015-10-02 13:53:07 +0000898void ScopStmt::addAccess(MemoryAccess *Access) {
899 Instruction *AccessInst = Access->getAccessInstruction();
900
901 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
902 if (!MAL)
903 MAL = new MemoryAccessList();
904 MAL->emplace_front(Access);
905 MemAccs.push_back(MAL->front());
906}
907
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000908void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000909 for (MemoryAccess *MA : *this)
910 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000911
912 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000913}
914
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000915/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
916static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
917 void *User) {
918 isl_set **BoundedParts = static_cast<isl_set **>(User);
919 if (isl_basic_set_is_bounded(BSet))
920 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
921 else
922 isl_basic_set_free(BSet);
923 return isl_stat_ok;
924}
925
926/// @brief Return the bounded parts of @p S.
927static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
928 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
929 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
930 isl_set_free(S);
931 return BoundedParts;
932}
933
934/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
935///
936/// @returns A separation of @p S into first an unbounded then a bounded subset,
937/// both with regards to the dimension @p Dim.
938static std::pair<__isl_give isl_set *, __isl_give isl_set *>
939partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
940
941 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000942 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000943
944 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000945 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000946
947 // Remove dimensions that are greater than Dim as they are not interesting.
948 assert(NumDimsS >= Dim + 1);
949 OnlyDimS =
950 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
951
952 // Create artificial parametric upper bounds for dimensions smaller than Dim
953 // as we are not interested in them.
954 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
955 for (unsigned u = 0; u < Dim; u++) {
956 isl_constraint *C = isl_inequality_alloc(
957 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
958 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
959 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
960 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
961 }
962
963 // Collect all bounded parts of OnlyDimS.
964 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
965
966 // Create the dimensions greater than Dim again.
967 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
968 NumDimsS - Dim - 1);
969
970 // Remove the artificial upper bound parameters again.
971 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
972
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000973 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000974 return std::make_pair(UnboundedParts, BoundedParts);
975}
976
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000977/// @brief Set the dimension Ids from @p From in @p To.
978static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
979 __isl_take isl_set *To) {
980 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
981 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
982 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
983 }
984 return To;
985}
986
987/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000988static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000989 __isl_take isl_pw_aff *L,
990 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +0000991 switch (Pred) {
992 case ICmpInst::ICMP_EQ:
993 return isl_pw_aff_eq_set(L, R);
994 case ICmpInst::ICMP_NE:
995 return isl_pw_aff_ne_set(L, R);
996 case ICmpInst::ICMP_SLT:
997 return isl_pw_aff_lt_set(L, R);
998 case ICmpInst::ICMP_SLE:
999 return isl_pw_aff_le_set(L, R);
1000 case ICmpInst::ICMP_SGT:
1001 return isl_pw_aff_gt_set(L, R);
1002 case ICmpInst::ICMP_SGE:
1003 return isl_pw_aff_ge_set(L, R);
1004 case ICmpInst::ICMP_ULT:
1005 return isl_pw_aff_lt_set(L, R);
1006 case ICmpInst::ICMP_UGT:
1007 return isl_pw_aff_gt_set(L, R);
1008 case ICmpInst::ICMP_ULE:
1009 return isl_pw_aff_le_set(L, R);
1010 case ICmpInst::ICMP_UGE:
1011 return isl_pw_aff_ge_set(L, R);
1012 default:
1013 llvm_unreachable("Non integer predicate not supported");
1014 }
1015}
1016
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001017/// @brief Create the conditions under which @p L @p Pred @p R is true.
1018///
1019/// Helper function that will make sure the dimensions of the result have the
1020/// same isl_id's as the @p Domain.
1021static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1022 __isl_take isl_pw_aff *L,
1023 __isl_take isl_pw_aff *R,
1024 __isl_keep isl_set *Domain) {
1025 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1026 return setDimensionIds(Domain, ConsequenceCondSet);
1027}
1028
1029/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001030///
1031/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001032/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1033/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001034static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001035buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001036 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1037
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001038 Value *Condition = getConditionFromTerminator(SI);
1039 assert(Condition && "No condition for switch");
1040
1041 ScalarEvolution &SE = *S.getSE();
1042 BasicBlock *BB = SI->getParent();
1043 isl_pw_aff *LHS, *RHS;
1044 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
1045
1046 unsigned NumSuccessors = SI->getNumSuccessors();
1047 ConditionSets.resize(NumSuccessors);
1048 for (auto &Case : SI->cases()) {
1049 unsigned Idx = Case.getSuccessorIndex();
1050 ConstantInt *CaseValue = Case.getCaseValue();
1051
1052 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
1053 isl_set *CaseConditionSet =
1054 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1055 ConditionSets[Idx] = isl_set_coalesce(
1056 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1057 }
1058
1059 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1060 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1061 for (unsigned u = 2; u < NumSuccessors; u++)
1062 ConditionSetUnion =
1063 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1064 ConditionSets[0] = setDimensionIds(
1065 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1066
1067 S.markAsOptimized();
1068 isl_pw_aff_free(LHS);
1069}
1070
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001071/// @brief Build the conditions sets for the branch condition @p Condition in
1072/// the @p Domain.
1073///
1074/// This will fill @p ConditionSets with the conditions under which control
1075/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001076/// have as many elements as @p TI has successors. If @p TI is nullptr the
1077/// context under which @p Condition is true/false will be returned as the
1078/// new elements of @p ConditionSets.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001079static void
1080buildConditionSets(Scop &S, Value *Condition, TerminatorInst *TI, Loop *L,
1081 __isl_keep isl_set *Domain,
1082 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1083
1084 isl_set *ConsequenceCondSet = nullptr;
1085 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1086 if (CCond->isZero())
1087 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1088 else
1089 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1090 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1091 auto Opcode = BinOp->getOpcode();
1092 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1093
1094 buildConditionSets(S, BinOp->getOperand(0), TI, L, Domain, ConditionSets);
1095 buildConditionSets(S, BinOp->getOperand(1), TI, L, Domain, ConditionSets);
1096
1097 isl_set_free(ConditionSets.pop_back_val());
1098 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1099 isl_set_free(ConditionSets.pop_back_val());
1100 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1101
1102 if (Opcode == Instruction::And)
1103 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1104 else
1105 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1106 } else {
1107 auto *ICond = dyn_cast<ICmpInst>(Condition);
1108 assert(ICond &&
1109 "Condition of exiting branch was neither constant nor ICmp!");
1110
1111 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001112 BasicBlock *BB = TI ? TI->getParent() : nullptr;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001113 isl_pw_aff *LHS, *RHS;
1114 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1115 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
1116 ConsequenceCondSet =
1117 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1118 }
1119
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001120 // If no terminator was given we are only looking for parameter constraints
1121 // under which @p Condition is true/false.
1122 if (!TI)
1123 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
1124
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001125 assert(ConsequenceCondSet);
1126 isl_set *AlternativeCondSet =
1127 isl_set_complement(isl_set_copy(ConsequenceCondSet));
1128
1129 ConditionSets.push_back(isl_set_coalesce(
1130 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
1131 ConditionSets.push_back(isl_set_coalesce(
1132 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
1133}
1134
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001135/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1136///
1137/// This will fill @p ConditionSets with the conditions under which control
1138/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1139/// have as many elements as @p TI has successors.
1140static void
1141buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1142 __isl_keep isl_set *Domain,
1143 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1144
1145 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1146 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1147
1148 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1149
1150 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001151 ConditionSets.push_back(isl_set_copy(Domain));
1152 return;
1153 }
1154
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001155 Value *Condition = getConditionFromTerminator(TI);
1156 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001157
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001158 return buildConditionSets(S, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001159}
1160
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001161void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +00001162 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +00001163
Tobias Grosser084d8f72012-05-29 09:29:44 +00001164 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1165
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001166 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001167 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001168}
1169
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001170void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001171 isl_ctx *Ctx = Parent.getIslCtx();
1172 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1173 Type *Ty = GEP->getPointerOperandType();
1174 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001175 ScopDetection &SD = Parent.getSD();
1176
1177 // The set of loads that are required to be invariant.
1178 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001179
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001180 std::vector<const SCEV *> Subscripts;
1181 std::vector<int> Sizes;
1182
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001183 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001184
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001185 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001186 Ty = PtrTy->getElementType();
1187 }
1188
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001189 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001190
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001191 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001192
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001193 for (size_t i = 0; i < Sizes.size(); i++) {
1194 auto Expr = Subscripts[i + IndexOffset];
1195 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001196
Johannes Doerfert09e36972015-10-07 20:17:36 +00001197 InvariantLoadsSetTy AccessILS;
1198 if (!isAffineExpr(&Parent.getRegion(), Expr, SE, nullptr, &AccessILS))
1199 continue;
1200
1201 bool NonAffine = false;
1202 for (LoadInst *LInst : AccessILS)
1203 if (!ScopRIL.count(LInst))
1204 NonAffine = true;
1205
1206 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001207 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001208
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001209 isl_pw_aff *AccessOffset = getPwAff(Expr);
1210 AccessOffset =
1211 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001212
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001213 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1214 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001215
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001216 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1217 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1218 OutOfBound = isl_set_params(OutOfBound);
1219 isl_set *InBound = isl_set_complement(OutOfBound);
1220 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001221
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001222 // A => B == !A or B
1223 isl_set *InBoundIfExecuted =
1224 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001225
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001226 Parent.addAssumption(INBOUNDS, InBoundIfExecuted, GEP->getDebugLoc());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001227 }
1228
1229 isl_local_space_free(LSpace);
1230}
1231
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001232void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1233 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001234 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1235 deriveAssumptionsFromGEP(GEP);
1236}
1237
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001238void ScopStmt::collectSurroundingLoops() {
1239 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1240 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1241 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1242 isl_id_free(DimId);
1243 }
1244}
1245
Michael Kruse9d080092015-09-11 21:41:48 +00001246ScopStmt::ScopStmt(Scop &parent, Region &R)
Michael Krusecac948e2015-10-02 13:53:07 +00001247 : Parent(parent), Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001248
Tobias Grosser16c44032015-07-09 07:31:45 +00001249 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001250}
1251
Michael Kruse9d080092015-09-11 21:41:48 +00001252ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Michael Krusecac948e2015-10-02 13:53:07 +00001253 : Parent(parent), Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001254
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001255 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001256}
1257
1258void ScopStmt::init() {
1259 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001260
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001261 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001262 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001263 buildAccessRelations();
1264
1265 if (BB) {
1266 deriveAssumptions(BB);
1267 } else {
1268 for (BasicBlock *Block : R->blocks()) {
1269 deriveAssumptions(Block);
1270 }
1271 }
1272
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001273 if (DetectReductions)
1274 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001275}
1276
Johannes Doerferte58a0122014-06-27 20:31:28 +00001277/// @brief Collect loads which might form a reduction chain with @p StoreMA
1278///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001279/// Check if the stored value for @p StoreMA is a binary operator with one or
1280/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001281/// used only once (by @p StoreMA) and its load operands are also used only
1282/// once, we have found a possible reduction chain. It starts at an operand
1283/// load and includes the binary operator and @p StoreMA.
1284///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001285/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001286/// escape this block or into any other store except @p StoreMA.
1287void ScopStmt::collectCandiateReductionLoads(
1288 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1289 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1290 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001291 return;
1292
1293 // Skip if there is not one binary operator between the load and the store
1294 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001295 if (!BinOp)
1296 return;
1297
1298 // Skip if the binary operators has multiple uses
1299 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001300 return;
1301
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001302 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001303 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1304 return;
1305
Johannes Doerfert9890a052014-07-01 00:32:29 +00001306 // Skip if the binary operator is outside the current SCoP
1307 if (BinOp->getParent() != Store->getParent())
1308 return;
1309
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001310 // Skip if it is a multiplicative reduction and we disabled them
1311 if (DisableMultiplicativeReductions &&
1312 (BinOp->getOpcode() == Instruction::Mul ||
1313 BinOp->getOpcode() == Instruction::FMul))
1314 return;
1315
Johannes Doerferte58a0122014-06-27 20:31:28 +00001316 // Check the binary operator operands for a candidate load
1317 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1318 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1319 if (!PossibleLoad0 && !PossibleLoad1)
1320 return;
1321
1322 // A load is only a candidate if it cannot escape (thus has only this use)
1323 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001324 if (PossibleLoad0->getParent() == Store->getParent())
1325 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001326 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001327 if (PossibleLoad1->getParent() == Store->getParent())
1328 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001329}
1330
1331/// @brief Check for reductions in this ScopStmt
1332///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001333/// Iterate over all store memory accesses and check for valid binary reduction
1334/// like chains. For all candidates we check if they have the same base address
1335/// and there are no other accesses which overlap with them. The base address
1336/// check rules out impossible reductions candidates early. The overlap check,
1337/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001338/// guarantees that none of the intermediate results will escape during
1339/// execution of the loop nest. We basically check here that no other memory
1340/// access can access the same memory as the potential reduction.
1341void ScopStmt::checkForReductions() {
1342 SmallVector<MemoryAccess *, 2> Loads;
1343 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1344
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001345 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001346 // stores and collecting possible reduction loads.
1347 for (MemoryAccess *StoreMA : MemAccs) {
1348 if (StoreMA->isRead())
1349 continue;
1350
1351 Loads.clear();
1352 collectCandiateReductionLoads(StoreMA, Loads);
1353 for (MemoryAccess *LoadMA : Loads)
1354 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1355 }
1356
1357 // Then check each possible candidate pair.
1358 for (const auto &CandidatePair : Candidates) {
1359 bool Valid = true;
1360 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1361 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1362
1363 // Skip those with obviously unequal base addresses.
1364 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1365 isl_map_free(LoadAccs);
1366 isl_map_free(StoreAccs);
1367 continue;
1368 }
1369
1370 // And check if the remaining for overlap with other memory accesses.
1371 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1372 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1373 isl_set *AllAccs = isl_map_range(AllAccsRel);
1374
1375 for (MemoryAccess *MA : MemAccs) {
1376 if (MA == CandidatePair.first || MA == CandidatePair.second)
1377 continue;
1378
1379 isl_map *AccRel =
1380 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1381 isl_set *Accs = isl_map_range(AccRel);
1382
1383 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1384 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1385 Valid = Valid && isl_set_is_empty(OverlapAccs);
1386 isl_set_free(OverlapAccs);
1387 }
1388 }
1389
1390 isl_set_free(AllAccs);
1391 if (!Valid)
1392 continue;
1393
Johannes Doerfertf6183392014-07-01 20:52:51 +00001394 const LoadInst *Load =
1395 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1396 MemoryAccess::ReductionType RT =
1397 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1398
Johannes Doerferte58a0122014-06-27 20:31:28 +00001399 // If no overlapping access was found we mark the load and store as
1400 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001401 CandidatePair.first->markAsReductionLike(RT);
1402 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001403 }
Tobias Grosser75805372011-04-29 06:27:02 +00001404}
1405
Tobias Grosser74394f02013-01-14 22:40:23 +00001406std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001407
Tobias Grosser54839312015-04-21 11:37:25 +00001408std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001409 auto *S = getSchedule();
1410 auto Str = stringFromIslObj(S);
1411 isl_map_free(S);
1412 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001413}
1414
Tobias Grosser74394f02013-01-14 22:40:23 +00001415unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001416
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001417unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001418
Tobias Grosser75805372011-04-29 06:27:02 +00001419const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1420
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001421const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001422 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001423}
1424
Tobias Grosser74394f02013-01-14 22:40:23 +00001425isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001426
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001427__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001428
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001429__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001430 return isl_set_get_space(Domain);
1431}
1432
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001433__isl_give isl_id *ScopStmt::getDomainId() const {
1434 return isl_set_get_tuple_id(Domain);
1435}
Tobias Grossercd95b772012-08-30 11:49:38 +00001436
Tobias Grosser75805372011-04-29 06:27:02 +00001437ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001438 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001439 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001440}
1441
1442void ScopStmt::print(raw_ostream &OS) const {
1443 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001444 OS.indent(12) << "Domain :=\n";
1445
1446 if (Domain) {
1447 OS.indent(16) << getDomainStr() << ";\n";
1448 } else
1449 OS.indent(16) << "n/a\n";
1450
Tobias Grosser54839312015-04-21 11:37:25 +00001451 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001452
1453 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001454 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001455 } else
1456 OS.indent(16) << "n/a\n";
1457
Tobias Grosser083d3d32014-06-28 08:59:45 +00001458 for (MemoryAccess *Access : MemAccs)
1459 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001460}
1461
1462void ScopStmt::dump() const { print(dbgs()); }
1463
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001464void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001465
1466 // Remove all memory accesses in @p InvMAs from this statement together
1467 // with all scalar accesses that were caused by them. The tricky iteration
1468 // order uses is needed because the MemAccs is a vector and the order in
1469 // which the accesses of each memory access list (MAL) are stored in this
1470 // vector is reversed.
1471 for (MemoryAccess *MA : InvMAs) {
1472 auto &MAL = *lookupAccessesFor(MA->getAccessInstruction());
1473 MAL.reverse();
1474
1475 auto MALIt = MAL.begin();
1476 auto MALEnd = MAL.end();
1477 auto MemAccsIt = MemAccs.begin();
1478 while (MALIt != MALEnd) {
1479 while (*MemAccsIt != *MALIt)
1480 MemAccsIt++;
1481
1482 MALIt++;
1483 MemAccs.erase(MemAccsIt);
1484 }
1485
1486 InstructionToAccess.erase(MA->getAccessInstruction());
1487 delete &MAL;
1488 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001489}
1490
Tobias Grosser75805372011-04-29 06:27:02 +00001491//===----------------------------------------------------------------------===//
1492/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001493
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001494void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001495 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1496 isl_set_free(Context);
1497 Context = NewContext;
1498}
1499
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001500/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1501struct SCEVSensitiveParameterRewriter
1502 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1503 ValueToValueMap &VMap;
1504 ScalarEvolution &SE;
1505
1506public:
1507 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1508 : VMap(VMap), SE(SE) {}
1509
1510 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1511 ValueToValueMap &VMap) {
1512 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1513 return SSPR.visit(E);
1514 }
1515
1516 const SCEV *visit(const SCEV *E) {
1517 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1518 }
1519
1520 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1521
1522 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1523 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1524 }
1525
1526 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1527 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1528 }
1529
1530 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1531 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1532 }
1533
1534 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1535 SmallVector<const SCEV *, 4> Operands;
1536 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1537 Operands.push_back(visit(E->getOperand(i)));
1538 return SE.getAddExpr(Operands);
1539 }
1540
1541 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1542 SmallVector<const SCEV *, 4> Operands;
1543 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1544 Operands.push_back(visit(E->getOperand(i)));
1545 return SE.getMulExpr(Operands);
1546 }
1547
1548 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1549 SmallVector<const SCEV *, 4> Operands;
1550 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1551 Operands.push_back(visit(E->getOperand(i)));
1552 return SE.getSMaxExpr(Operands);
1553 }
1554
1555 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1556 SmallVector<const SCEV *, 4> Operands;
1557 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1558 Operands.push_back(visit(E->getOperand(i)));
1559 return SE.getUMaxExpr(Operands);
1560 }
1561
1562 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1563 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1564 }
1565
1566 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1567 auto *Start = visit(E->getStart());
1568 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1569 visit(E->getStepRecurrence(SE)),
1570 E->getLoop(), SCEV::FlagAnyWrap);
1571 return SE.getAddExpr(Start, AddRec);
1572 }
1573
1574 const SCEV *visitUnknown(const SCEVUnknown *E) {
1575 if (auto *NewValue = VMap.lookup(E->getValue()))
1576 return SE.getUnknown(NewValue);
1577 return E;
1578 }
1579};
1580
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001581const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001582 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001583}
1584
Tobias Grosserabfbe632013-02-05 12:09:06 +00001585void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001586 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001587 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001588
1589 // Normalize the SCEV to get the representing element for an invariant load.
1590 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1591
Tobias Grosser60b54f12011-11-08 15:41:28 +00001592 if (ParameterIds.find(Parameter) != ParameterIds.end())
1593 continue;
1594
1595 int dimension = Parameters.size();
1596
1597 Parameters.push_back(Parameter);
1598 ParameterIds[Parameter] = dimension;
1599 }
1600}
1601
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001602__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001603 // Normalize the SCEV to get the representing element for an invariant load.
1604 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1605
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001606 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001607
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001608 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001609 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001610
Tobias Grosser8f99c162011-11-15 11:38:55 +00001611 std::string ParameterName;
1612
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001613 ParameterName = "p_" + utostr_32(IdIter->second);
1614
Tobias Grosser8f99c162011-11-15 11:38:55 +00001615 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1616 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001617
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001618 // If this parameter references a specific Value and this value has a name
1619 // we use this name as it is likely to be unique and more useful than just
1620 // a number.
1621 if (Val->hasName())
1622 ParameterName = Val->getName();
1623 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
1624 auto LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
1625 if (LoadOrigin->hasName()) {
1626 ParameterName += "_loaded_from_";
1627 ParameterName +=
1628 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1629 }
1630 }
1631 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001632
Tobias Grosser20532b82014-04-11 17:56:49 +00001633 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1634 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001635}
Tobias Grosser75805372011-04-29 06:27:02 +00001636
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001637isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1638 isl_set *DomainContext = isl_union_set_params(getDomains());
1639 return isl_set_intersect_params(C, DomainContext);
1640}
1641
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001642void Scop::buildBoundaryContext() {
Tobias Grosser4927c8e2015-11-24 12:50:02 +00001643 if (IgnoreIntegerWrapping) {
1644 BoundaryContext = isl_set_universe(getParamSpace());
1645 return;
1646 }
1647
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001648 BoundaryContext = Affinator.getWrappingContext();
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001649
1650 // The isl_set_complement operation used to create the boundary context
1651 // can possibly become very expensive. We bound the compile time of
1652 // this operation by setting a compute out.
1653 //
1654 // TODO: We can probably get around using isl_set_complement and directly
1655 // AST generate BoundaryContext.
1656 long MaxOpsOld = isl_ctx_get_max_operations(getIslCtx());
Tobias Grosserf920fb12015-11-13 16:56:13 +00001657 isl_ctx_reset_operations(getIslCtx());
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001658 isl_ctx_set_max_operations(getIslCtx(), 300000);
1659 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_CONTINUE);
1660
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001661 BoundaryContext = isl_set_complement(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001662
Tobias Grossera52b4da2015-11-11 17:59:53 +00001663 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
1664 isl_set_free(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001665 BoundaryContext = isl_set_empty(getParamSpace());
Tobias Grossera52b4da2015-11-11 17:59:53 +00001666 }
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001667
1668 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
1669 isl_ctx_reset_operations(getIslCtx());
1670 isl_ctx_set_max_operations(getIslCtx(), MaxOpsOld);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001671 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001672 trackAssumption(WRAPPING, BoundaryContext, DebugLoc());
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001673}
1674
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001675void Scop::addUserAssumptions(AssumptionCache &AC) {
1676 auto *R = &getRegion();
1677 auto &F = *R->getEntry()->getParent();
1678 for (auto &Assumption : AC.assumptions()) {
1679 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1680 if (!CI || CI->getNumArgOperands() != 1)
1681 continue;
1682 if (!DT.dominates(CI->getParent(), R->getEntry()))
1683 continue;
1684
1685 auto *Val = CI->getArgOperand(0);
1686 std::vector<const SCEV *> Params;
1687 if (!isAffineParamConstraint(Val, R, *SE, Params)) {
1688 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1689 CI->getDebugLoc(),
1690 "Non-affine user assumption ignored.");
1691 continue;
1692 }
1693
1694 addParams(Params);
1695
1696 auto *L = LI.getLoopFor(CI->getParent());
1697 SmallVector<isl_set *, 2> ConditionSets;
1698 buildConditionSets(*this, Val, nullptr, L, Context, ConditionSets);
1699 assert(ConditionSets.size() == 2);
1700 isl_set_free(ConditionSets[1]);
1701
1702 auto *AssumptionCtx = ConditionSets[0];
1703 emitOptimizationRemarkAnalysis(
1704 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1705 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1706 Context = isl_set_intersect(Context, AssumptionCtx);
1707 }
1708}
1709
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001710void Scop::addUserContext() {
1711 if (UserContextStr.empty())
1712 return;
1713
1714 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1715 isl_space *Space = getParamSpace();
1716 if (isl_space_dim(Space, isl_dim_param) !=
1717 isl_set_dim(UserContext, isl_dim_param)) {
1718 auto SpaceStr = isl_space_to_str(Space);
1719 errs() << "Error: the context provided in -polly-context has not the same "
1720 << "number of dimensions than the computed context. Due to this "
1721 << "mismatch, the -polly-context option is ignored. Please provide "
1722 << "the context in the parameter space: " << SpaceStr << ".\n";
1723 free(SpaceStr);
1724 isl_set_free(UserContext);
1725 isl_space_free(Space);
1726 return;
1727 }
1728
1729 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1730 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1731 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1732
1733 if (strcmp(NameContext, NameUserContext) != 0) {
1734 auto SpaceStr = isl_space_to_str(Space);
1735 errs() << "Error: the name of dimension " << i
1736 << " provided in -polly-context "
1737 << "is '" << NameUserContext << "', but the name in the computed "
1738 << "context is '" << NameContext
1739 << "'. Due to this name mismatch, "
1740 << "the -polly-context option is ignored. Please provide "
1741 << "the context in the parameter space: " << SpaceStr << ".\n";
1742 free(SpaceStr);
1743 isl_set_free(UserContext);
1744 isl_space_free(Space);
1745 return;
1746 }
1747
1748 UserContext =
1749 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1750 isl_space_get_dim_id(Space, isl_dim_param, i));
1751 }
1752
1753 Context = isl_set_intersect(Context, UserContext);
1754 isl_space_free(Space);
1755}
1756
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001757void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001758 DenseMap<const SCEV *, LoadInst *> EquivClasses;
1759
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001760 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001761 for (LoadInst *LInst : RIL) {
1762 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1763
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001764 LoadInst *&ClassRep = EquivClasses[PointerSCEV];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001765 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001766 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001767 continue;
1768 }
1769
1770 ClassRep = LInst;
1771 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(),
1772 nullptr);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001773 }
1774}
1775
Tobias Grosser6be480c2011-11-08 15:41:13 +00001776void Scop::buildContext() {
1777 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001778 Context = isl_set_universe(isl_space_copy(Space));
1779 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001780}
1781
Tobias Grosser18daaca2012-05-22 10:47:27 +00001782void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001783 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001784 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001785
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001786 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001787
Johannes Doerferte7044942015-02-24 11:58:30 +00001788 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001789 }
1790}
1791
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001792void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001793 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001794 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001795
Tobias Grosser083d3d32014-06-28 08:59:45 +00001796 for (const auto &ParamID : ParameterIds) {
1797 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001798 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001799 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001800 }
1801
1802 // Align the parameters of all data structures to the model.
1803 Context = isl_set_align_params(Context, Space);
1804
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001805 for (ScopStmt &Stmt : *this)
1806 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001807}
1808
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001809static __isl_give isl_set *
1810simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1811 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001812 // If we modelt all blocks in the SCoP that have side effects we can simplify
1813 // the context with the constraints that are needed for anything to be
1814 // executed at all. However, if we have error blocks in the SCoP we already
1815 // assumed some parameter combinations cannot occure and removed them from the
1816 // domains, thus we cannot use the remaining domain to simplify the
1817 // assumptions.
1818 if (!S.hasErrorBlock()) {
1819 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1820 AssumptionContext =
1821 isl_set_gist_params(AssumptionContext, DomainParameters);
1822 }
1823
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001824 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1825 return AssumptionContext;
1826}
1827
1828void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001829 // The parameter constraints of the iteration domains give us a set of
1830 // constraints that need to hold for all cases where at least a single
1831 // statement iteration is executed in the whole scop. We now simplify the
1832 // assumed context under the assumption that such constraints hold and at
1833 // least a single statement iteration is executed. For cases where no
1834 // statement instances are executed, the assumptions we have taken about
1835 // the executed code do not matter and can be changed.
1836 //
1837 // WARNING: This only holds if the assumptions we have taken do not reduce
1838 // the set of statement instances that are executed. Otherwise we
1839 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001840 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001841 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001842 // performed. In such a case, modifying the run-time conditions and
1843 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001844 // to not be executed.
1845 //
1846 // Example:
1847 //
1848 // When delinearizing the following code:
1849 //
1850 // for (long i = 0; i < 100; i++)
1851 // for (long j = 0; j < m; j++)
1852 // A[i+p][j] = 1.0;
1853 //
1854 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001855 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001856 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001857 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1858 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001859}
1860
Johannes Doerfertb164c792014-09-18 11:17:17 +00001861/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001862static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001863 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1864 isl_pw_multi_aff *MinPMA, *MaxPMA;
1865 isl_pw_aff *LastDimAff;
1866 isl_aff *OneAff;
1867 unsigned Pos;
1868
Johannes Doerfert9143d672014-09-27 11:02:39 +00001869 // Restrict the number of parameters involved in the access as the lexmin/
1870 // lexmax computation will take too long if this number is high.
1871 //
1872 // Experiments with a simple test case using an i7 4800MQ:
1873 //
1874 // #Parameters involved | Time (in sec)
1875 // 6 | 0.01
1876 // 7 | 0.04
1877 // 8 | 0.12
1878 // 9 | 0.40
1879 // 10 | 1.54
1880 // 11 | 6.78
1881 // 12 | 30.38
1882 //
1883 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1884 unsigned InvolvedParams = 0;
1885 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1886 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1887 InvolvedParams++;
1888
1889 if (InvolvedParams > RunTimeChecksMaxParameters) {
1890 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001891 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001892 }
1893 }
1894
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001895 Set = isl_set_remove_divs(Set);
1896
Johannes Doerfertb164c792014-09-18 11:17:17 +00001897 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1898 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1899
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001900 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1901 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1902
Johannes Doerfertb164c792014-09-18 11:17:17 +00001903 // Adjust the last dimension of the maximal access by one as we want to
1904 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1905 // we test during code generation might now point after the end of the
1906 // allocated array but we will never dereference it anyway.
1907 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1908 "Assumed at least one output dimension");
1909 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1910 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1911 OneAff = isl_aff_zero_on_domain(
1912 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1913 OneAff = isl_aff_add_constant_si(OneAff, 1);
1914 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1915 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1916
1917 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1918
1919 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001920 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001921}
1922
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001923static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1924 isl_set *Domain = MA->getStatement()->getDomain();
1925 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1926 return isl_set_reset_tuple_id(Domain);
1927}
1928
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001929/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1930static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001931 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001932 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001933
1934 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1935 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001936 Locations = isl_union_set_coalesce(Locations);
1937 Locations = isl_union_set_detect_equalities(Locations);
1938 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001939 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001940 isl_union_set_free(Locations);
1941 return Valid;
1942}
1943
Johannes Doerfert96425c22015-08-30 21:13:53 +00001944/// @brief Helper to treat non-affine regions and basic blocks the same.
1945///
1946///{
1947
1948/// @brief Return the block that is the representing block for @p RN.
1949static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1950 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1951 : RN->getNodeAs<BasicBlock>();
1952}
1953
1954/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001955static inline BasicBlock *
1956getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001957 if (RN->isSubRegion()) {
1958 assert(idx == 0);
1959 return RN->getNodeAs<Region>()->getExit();
1960 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001961 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001962}
1963
1964/// @brief Return the smallest loop surrounding @p RN.
1965static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1966 if (!RN->isSubRegion())
1967 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1968
1969 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1970 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1971 while (L && NonAffineSubRegion->contains(L))
1972 L = L->getParentLoop();
1973 return L;
1974}
1975
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001976static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1977 if (!RN->isSubRegion())
1978 return 1;
1979
1980 unsigned NumBlocks = 0;
1981 Region *R = RN->getNodeAs<Region>();
1982 for (auto BB : R->blocks()) {
1983 (void)BB;
1984 NumBlocks++;
1985 }
1986 return NumBlocks;
1987}
1988
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001989static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
1990 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00001991 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001992 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00001993 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001994 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00001995 return true;
1996 return false;
1997}
1998
Johannes Doerfert96425c22015-08-30 21:13:53 +00001999///}
2000
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002001static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2002 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002003 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002004 isl_id *DimId =
2005 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2006 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2007}
2008
Johannes Doerfert96425c22015-08-30 21:13:53 +00002009isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
2010 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
2011 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002012 return getDomainConditions(BB);
2013}
2014
2015isl_set *Scop::getDomainConditions(BasicBlock *BB) {
2016 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002017 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002018}
2019
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002020void Scop::removeErrorBlockDomains() {
2021 auto removeDomains = [this](BasicBlock *Start) {
2022 auto BBNode = DT.getNode(Start);
2023 for (auto ErrorChild : depth_first(BBNode)) {
2024 auto ErrorChildBlock = ErrorChild->getBlock();
2025 auto CurrentDomain = DomainMap[ErrorChildBlock];
2026 auto Empty = isl_set_empty(isl_set_get_space(CurrentDomain));
2027 DomainMap[ErrorChildBlock] = Empty;
2028 isl_set_free(CurrentDomain);
2029 }
2030 };
2031
Tobias Grosser5ef2bc32015-11-23 10:18:23 +00002032 SmallVector<Region *, 4> Todo = {&R};
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002033
2034 while (!Todo.empty()) {
2035 auto SubRegion = Todo.back();
2036 Todo.pop_back();
2037
2038 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
2039 for (auto &Child : *SubRegion)
2040 Todo.push_back(Child.get());
2041 continue;
2042 }
2043 if (containsErrorBlock(SubRegion->getNode(), getRegion(), LI, DT))
2044 removeDomains(SubRegion->getEntry());
2045 }
2046
2047 for (auto BB : R.blocks())
2048 if (isErrorBlock(*BB, R, LI, DT))
2049 removeDomains(BB);
2050}
2051
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002052void Scop::buildDomains(Region *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002053
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002054 auto *EntryBB = R->getEntry();
2055 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
2056 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002057
2058 Loop *L = LI.getLoopFor(EntryBB);
2059 while (LD-- >= 0) {
2060 S = addDomainDimId(S, LD + 1, L);
2061 L = L->getParentLoop();
2062 }
2063
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002064 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002065
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002066 if (SD.isNonAffineSubRegion(R, R))
2067 return;
2068
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002069 buildDomainsWithBranchConstraints(R);
2070 propagateDomainConstraints(R);
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002071
2072 // Error blocks and blocks dominated by them have been assumed to never be
2073 // executed. Representing them in the Scop does not add any value. In fact,
2074 // it is likely to cause issues during construction of the ScopStmts. The
2075 // contents of error blocks have not been verfied to be expressible and
2076 // will cause problems when building up a ScopStmt for them.
2077 // Furthermore, basic blocks dominated by error blocks may reference
2078 // instructions in the error block which, if the error block is not modeled,
2079 // can themselves not be constructed properly.
2080 removeErrorBlockDomains();
Johannes Doerfert96425c22015-08-30 21:13:53 +00002081}
2082
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002083void Scop::buildDomainsWithBranchConstraints(Region *R) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002084 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00002085
2086 // To create the domain for each block in R we iterate over all blocks and
2087 // subregions in R and propagate the conditions under which the current region
2088 // element is executed. To this end we iterate in reverse post order over R as
2089 // it ensures that we first visit all predecessors of a region node (either a
2090 // basic block or a subregion) before we visit the region node itself.
2091 // Initially, only the domain for the SCoP region entry block is set and from
2092 // there we propagate the current domain to all successors, however we add the
2093 // condition that the successor is actually executed next.
2094 // As we are only interested in non-loop carried constraints here we can
2095 // simply skip loop back edges.
2096
2097 ReversePostOrderTraversal<Region *> RTraversal(R);
2098 for (auto *RN : RTraversal) {
2099
2100 // Recurse for affine subregions but go on for basic blocks and non-affine
2101 // subregions.
2102 if (RN->isSubRegion()) {
2103 Region *SubRegion = RN->getNodeAs<Region>();
2104 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002105 buildDomainsWithBranchConstraints(SubRegion);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002106 continue;
2107 }
2108 }
2109
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002110 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002111 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002112
Johannes Doerfert96425c22015-08-30 21:13:53 +00002113 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002114 TerminatorInst *TI = BB->getTerminator();
2115
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002116 if (isa<UnreachableInst>(TI))
2117 continue;
2118
Johannes Doerfertf5673802015-10-01 23:48:18 +00002119 isl_set *Domain = DomainMap.lookup(BB);
2120 if (!Domain) {
2121 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2122 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002123 continue;
2124 }
2125
Johannes Doerfert96425c22015-08-30 21:13:53 +00002126 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002127
2128 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2129 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2130
2131 // Build the condition sets for the successor nodes of the current region
2132 // node. If it is a non-affine subregion we will always execute the single
2133 // exit node, hence the single entry node domain is the condition set. For
2134 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002135 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002136 if (RN->isSubRegion())
2137 ConditionSets.push_back(isl_set_copy(Domain));
2138 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002139 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002140
2141 // Now iterate over the successors and set their initial domain based on
2142 // their condition set. We skip back edges here and have to be careful when
2143 // we leave a loop not to keep constraints over a dimension that doesn't
2144 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002145 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002146 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002147 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002148 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002149
2150 // Skip back edges.
2151 if (DT.dominates(SuccBB, BB)) {
2152 isl_set_free(CondSet);
2153 continue;
2154 }
2155
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002156 // Do not adjust the number of dimensions if we enter a boxed loop or are
2157 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002158 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002159 Region *SuccRegion = RI.getRegionFor(SuccBB);
Johannes Doerfert634909c2015-10-04 14:57:41 +00002160 if (SD.isNonAffineSubRegion(SuccRegion, &getRegion()))
2161 while (SuccBBLoop && SuccRegion->contains(SuccBBLoop))
2162 SuccBBLoop = SuccBBLoop->getParentLoop();
2163
2164 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002165
2166 // Check if the edge to SuccBB is a loop entry or exit edge. If so
2167 // adjust the dimensionality accordingly. Lastly, if we leave a loop
2168 // and enter a new one we need to drop the old constraints.
2169 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002170 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002171 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002172 CondSet = isl_set_project_out(CondSet, isl_dim_set,
2173 isl_set_n_dim(CondSet) - LoopDepthDiff,
2174 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002175 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002176 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002177 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002178 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002179 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002180 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002181 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
2182 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002183 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002184 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002185 }
2186
2187 // Set the domain for the successor or merge it with an existing domain in
2188 // case there are multiple paths (without loop back edges) to the
2189 // successor block.
2190 isl_set *&SuccDomain = DomainMap[SuccBB];
2191 if (!SuccDomain)
2192 SuccDomain = CondSet;
2193 else
2194 SuccDomain = isl_set_union(SuccDomain, CondSet);
2195
2196 SuccDomain = isl_set_coalesce(SuccDomain);
Johannes Doerfert634909c2015-10-04 14:57:41 +00002197 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
2198 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002199 }
2200 }
2201}
2202
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002203/// @brief Return the domain for @p BB wrt @p DomainMap.
2204///
2205/// This helper function will lookup @p BB in @p DomainMap but also handle the
2206/// case where @p BB is contained in a non-affine subregion using the region
2207/// tree obtained by @p RI.
2208static __isl_give isl_set *
2209getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
2210 RegionInfo &RI) {
2211 auto DIt = DomainMap.find(BB);
2212 if (DIt != DomainMap.end())
2213 return isl_set_copy(DIt->getSecond());
2214
2215 Region *R = RI.getRegionFor(BB);
2216 while (R->getEntry() == BB)
2217 R = R->getParent();
2218 return getDomainForBlock(R->getEntry(), DomainMap, RI);
2219}
2220
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002221void Scop::propagateDomainConstraints(Region *R) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002222 // Iterate over the region R and propagate the domain constrains from the
2223 // predecessors to the current node. In contrast to the
2224 // buildDomainsWithBranchConstraints function, this one will pull the domain
2225 // information from the predecessors instead of pushing it to the successors.
2226 // Additionally, we assume the domains to be already present in the domain
2227 // map here. However, we iterate again in reverse post order so we know all
2228 // predecessors have been visited before a block or non-affine subregion is
2229 // visited.
2230
2231 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2232 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2233
2234 ReversePostOrderTraversal<Region *> RTraversal(R);
2235 for (auto *RN : RTraversal) {
2236
2237 // Recurse for affine subregions but go on for basic blocks and non-affine
2238 // subregions.
2239 if (RN->isSubRegion()) {
2240 Region *SubRegion = RN->getNodeAs<Region>();
2241 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002242 propagateDomainConstraints(SubRegion);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002243 continue;
2244 }
2245 }
2246
Johannes Doerfertf5673802015-10-01 23:48:18 +00002247 // Get the domain for the current block and check if it was initialized or
2248 // not. The only way it was not is if this block is only reachable via error
2249 // blocks, thus will not be executed under the assumptions we make. Such
2250 // blocks have to be skipped as their predecessors might not have domains
2251 // either. It would not benefit us to compute the domain anyway, only the
2252 // domains of the error blocks that are reachable from non-error blocks
2253 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002254 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002255 isl_set *&Domain = DomainMap[BB];
2256 if (!Domain) {
2257 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2258 << ", it is only reachable from error blocks.\n");
2259 DomainMap.erase(BB);
2260 continue;
2261 }
2262 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
2263
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002264 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2265 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2266
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002267 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2268 for (auto *PredBB : predecessors(BB)) {
2269
2270 // Skip backedges
2271 if (DT.dominates(BB, PredBB))
2272 continue;
2273
2274 isl_set *PredBBDom = nullptr;
2275
2276 // Handle the SCoP entry block with its outside predecessors.
2277 if (!getRegion().contains(PredBB))
2278 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
2279
2280 if (!PredBBDom) {
2281 // Determine the loop depth of the predecessor and adjust its domain to
2282 // the domain of the current block. This can mean we have to:
2283 // o) Drop a dimension if this block is the exit of a loop, not the
2284 // header of a new loop and the predecessor was part of the loop.
2285 // o) Add an unconstrainted new dimension if this block is the header
2286 // of a loop and the predecessor is not part of it.
2287 // o) Drop the information about the innermost loop dimension when the
2288 // predecessor and the current block are surrounded by different
2289 // loops in the same depth.
2290 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2291 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2292 while (BoxedLoops.count(PredBBLoop))
2293 PredBBLoop = PredBBLoop->getParentLoop();
2294
2295 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002296 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002297 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002298 PredBBDom = isl_set_project_out(
2299 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2300 LoopDepthDiff);
2301 else if (PredBBLoopDepth < BBLoopDepth) {
2302 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002303 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002304 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2305 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002306 PredBBDom = isl_set_drop_constraints_involving_dims(
2307 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002308 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002309 }
2310
2311 PredDom = isl_set_union(PredDom, PredBBDom);
2312 }
2313
2314 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002315 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002316
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002317 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002318 addLoopBoundsToHeaderDomain(BBLoop);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002319
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002320 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002321 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002322 IsOptimized = true;
2323 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002324 addAssumption(ERRORBLOCK, isl_set_complement(DomPar),
2325 BB->getTerminator()->getDebugLoc());
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002326 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002327 }
2328}
2329
2330/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2331/// is incremented by one and all other dimensions are equal, e.g.,
2332/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2333/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2334static __isl_give isl_map *
2335createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2336 auto *MapSpace = isl_space_map_from_set(SetSpace);
2337 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2338 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2339 if (u != Dim)
2340 NextIterationMap =
2341 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2342 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2343 C = isl_constraint_set_constant_si(C, 1);
2344 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2345 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2346 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2347 return NextIterationMap;
2348}
2349
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002350void Scop::addLoopBoundsToHeaderDomain(Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002351 int LoopDepth = getRelativeLoopDepth(L);
2352 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002353
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002354 BasicBlock *HeaderBB = L->getHeader();
2355 assert(DomainMap.count(HeaderBB));
2356 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002357
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002358 isl_map *NextIterationMap =
2359 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002360
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002361 isl_set *UnionBackedgeCondition =
2362 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002363
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002364 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2365 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002366
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002367 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002368
2369 // If the latch is only reachable via error statements we skip it.
2370 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2371 if (!LatchBBDom)
2372 continue;
2373
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002374 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002375
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002376 TerminatorInst *TI = LatchBB->getTerminator();
2377 BranchInst *BI = dyn_cast<BranchInst>(TI);
2378 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002379 BackedgeCondition = isl_set_copy(LatchBBDom);
2380 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002381 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002382 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002383 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002384
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002385 // Free the non back edge condition set as we do not need it.
2386 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002387
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002388 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002389 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002390
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002391 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2392 assert(LatchLoopDepth >= LoopDepth);
2393 BackedgeCondition =
2394 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2395 LatchLoopDepth - LoopDepth);
2396 UnionBackedgeCondition =
2397 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002398 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002399
2400 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2401 for (int i = 0; i < LoopDepth; i++)
2402 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2403
2404 isl_set *UnionBackedgeConditionComplement =
2405 isl_set_complement(UnionBackedgeCondition);
2406 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2407 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2408 UnionBackedgeConditionComplement =
2409 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2410 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2411 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2412
2413 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2414 HeaderBBDom = Parts.second;
2415
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002416 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2417 // the bounded assumptions to the context as they are already implied by the
2418 // <nsw> tag.
2419 if (Affinator.hasNSWAddRecForLoop(L)) {
2420 isl_set_free(Parts.first);
2421 return;
2422 }
2423
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002424 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2425 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002426 addAssumption(INFINITELOOP, BoundedCtx,
2427 HeaderBB->getTerminator()->getDebugLoc());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002428}
2429
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002430void Scop::buildAliasChecks(AliasAnalysis &AA) {
2431 if (!PollyUseRuntimeAliasChecks)
2432 return;
2433
2434 if (buildAliasGroups(AA))
2435 return;
2436
2437 // If a problem occurs while building the alias groups we need to delete
2438 // this SCoP and pretend it wasn't valid in the first place. To this end
2439 // we make the assumed context infeasible.
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002440 addAssumption(ALIASING, isl_set_empty(getParamSpace()), DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002441
2442 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2443 << " could not be created as the number of parameters involved "
2444 "is too high. The SCoP will be "
2445 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2446 "the maximal number of parameters but be advised that the "
2447 "compile time might increase exponentially.\n\n");
2448}
2449
Johannes Doerfert9143d672014-09-27 11:02:39 +00002450bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002451 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002452 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002453 // for all memory accesses inside the SCoP.
2454 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002455 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002456 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002457 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002458 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002459 // if their access domains intersect, otherwise they are in different
2460 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002461 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002462 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002463 // and maximal accesses to each array of a group in read only and non
2464 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002465 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2466
2467 AliasSetTracker AST(AA);
2468
2469 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002470 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002471 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002472
2473 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002474 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002475 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2476 isl_set_free(StmtDomain);
2477 if (StmtDomainEmpty)
2478 continue;
2479
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002480 for (MemoryAccess *MA : Stmt) {
Michael Kruse8d0b7342015-09-25 21:21:00 +00002481 if (MA->isImplicit())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002482 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002483 if (!MA->isRead())
2484 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002485 Instruction *Acc = MA->getAccessInstruction();
2486 PtrToAcc[getPointerOperand(*Acc)] = MA;
2487 AST.add(Acc);
2488 }
2489 }
2490
2491 SmallVector<AliasGroupTy, 4> AliasGroups;
2492 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002493 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002494 continue;
2495 AliasGroupTy AG;
2496 for (auto PR : AS)
2497 AG.push_back(PtrToAcc[PR.getValue()]);
2498 assert(AG.size() > 1 &&
2499 "Alias groups should contain at least two accesses");
2500 AliasGroups.push_back(std::move(AG));
2501 }
2502
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002503 // Split the alias groups based on their domain.
2504 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2505 AliasGroupTy NewAG;
2506 AliasGroupTy &AG = AliasGroups[u];
2507 AliasGroupTy::iterator AGI = AG.begin();
2508 isl_set *AGDomain = getAccessDomain(*AGI);
2509 while (AGI != AG.end()) {
2510 MemoryAccess *MA = *AGI;
2511 isl_set *MADomain = getAccessDomain(MA);
2512 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2513 NewAG.push_back(MA);
2514 AGI = AG.erase(AGI);
2515 isl_set_free(MADomain);
2516 } else {
2517 AGDomain = isl_set_union(AGDomain, MADomain);
2518 AGI++;
2519 }
2520 }
2521 if (NewAG.size() > 1)
2522 AliasGroups.push_back(std::move(NewAG));
2523 isl_set_free(AGDomain);
2524 }
2525
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002526 auto &F = *getRegion().getEntry()->getParent();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002527 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002528 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2529 for (AliasGroupTy &AG : AliasGroups) {
2530 NonReadOnlyBaseValues.clear();
2531 ReadOnlyPairs.clear();
2532
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002533 if (AG.size() < 2) {
2534 AG.clear();
2535 continue;
2536 }
2537
Johannes Doerfert13771732014-10-01 12:40:46 +00002538 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002539 emitOptimizationRemarkAnalysis(
2540 F.getContext(), DEBUG_TYPE, F,
2541 (*II)->getAccessInstruction()->getDebugLoc(),
2542 "Possibly aliasing pointer, use restrict keyword.");
2543
Johannes Doerfert13771732014-10-01 12:40:46 +00002544 Value *BaseAddr = (*II)->getBaseAddr();
2545 if (HasWriteAccess.count(BaseAddr)) {
2546 NonReadOnlyBaseValues.insert(BaseAddr);
2547 II++;
2548 } else {
2549 ReadOnlyPairs[BaseAddr].insert(*II);
2550 II = AG.erase(II);
2551 }
2552 }
2553
2554 // If we don't have read only pointers check if there are at least two
2555 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002556 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002557 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002558 continue;
2559 }
2560
2561 // If we don't have non read only pointers clear the alias group.
2562 if (NonReadOnlyBaseValues.empty()) {
2563 AG.clear();
2564 continue;
2565 }
2566
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002567 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002568 MinMaxAliasGroups.emplace_back();
2569 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2570 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2571 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2572 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002573
2574 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002575
2576 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002577 for (MemoryAccess *MA : AG)
2578 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002579
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002580 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2581 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002582
2583 // Bail out if the number of values we need to compare is too large.
2584 // This is important as the number of comparisions grows quadratically with
2585 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002586 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2587 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002588 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002589
2590 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002591 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002592 Accesses = isl_union_map_empty(getParamSpace());
2593
2594 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2595 for (MemoryAccess *MA : ReadOnlyPair.second)
2596 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2597
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002598 Valid =
2599 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002600
2601 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002602 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002603 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002604
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002605 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002606}
2607
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002608/// @brief Get the smallest loop that contains @p R but is not in @p R.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002609static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002610 // Start with the smallest loop containing the entry and expand that
2611 // loop until it contains all blocks in the region. If there is a loop
2612 // containing all blocks in the region check if it is itself contained
2613 // and if so take the parent loop as it will be the smallest containing
2614 // the region but not contained by it.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002615 Loop *L = LI.getLoopFor(R.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002616 while (L) {
2617 bool AllContained = true;
2618 for (auto *BB : R.blocks())
2619 AllContained &= L->contains(BB);
2620 if (AllContained)
2621 break;
2622 L = L->getParentLoop();
2623 }
2624
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002625 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2626}
2627
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002628static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2629 ScopDetection &SD) {
2630
2631 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2632
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002633 unsigned MinLD = INT_MAX, MaxLD = 0;
2634 for (BasicBlock *BB : R.blocks()) {
2635 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002636 if (!R.contains(L))
2637 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002638 if (BoxedLoops && BoxedLoops->count(L))
2639 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002640 unsigned LD = L->getLoopDepth();
2641 MinLD = std::min(MinLD, LD);
2642 MaxLD = std::max(MaxLD, LD);
2643 }
2644 }
2645
2646 // Handle the case that there is no loop in the SCoP first.
2647 if (MaxLD == 0)
2648 return 1;
2649
2650 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2651 assert(MaxLD >= MinLD &&
2652 "Maximal loop depth was smaller than mininaml loop depth?");
2653 return MaxLD - MinLD + 1;
2654}
2655
Johannes Doerfert478a7de2015-10-02 13:09:31 +00002656Scop::Scop(Region &R, AccFuncMapType &AccFuncMap, ScopDetection &SD,
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002657 ScalarEvolution &ScalarEvolution, DominatorTree &DT, LoopInfo &LI,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002658 isl_ctx *Context, unsigned MaxLoopDepth)
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002659 : LI(LI), DT(DT), SE(&ScalarEvolution), SD(SD), R(R),
2660 AccFuncMap(AccFuncMap), IsOptimized(false),
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002661 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
2662 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Context(nullptr),
2663 Affinator(this), AssumedContext(nullptr), BoundaryContext(nullptr),
2664 Schedule(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002665
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002666void Scop::init(AliasAnalysis &AA, AssumptionCache &AC) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002667 buildContext();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002668 addUserAssumptions(AC);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002669 buildInvariantEquivalenceClasses();
2670
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002671 buildDomains(&R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002672
Michael Krusecac948e2015-10-02 13:53:07 +00002673 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002674 // Exit early in case there are no executable statements left in this scop.
Michael Krusecac948e2015-10-02 13:53:07 +00002675 simplifySCoP(true);
Michael Kruseafe06702015-10-02 16:33:27 +00002676 if (Stmts.empty())
2677 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002678
Michael Krusecac948e2015-10-02 13:53:07 +00002679 // The ScopStmts now have enough information to initialize themselves.
2680 for (ScopStmt &Stmt : Stmts)
2681 Stmt.init();
2682
2683 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002684 Loop *L = getLoopSurroundingRegion(R, LI);
2685 LoopSchedules[L];
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002686 buildSchedule(&R, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002687 Schedule = LoopSchedules[L].first;
Tobias Grosser75805372011-04-29 06:27:02 +00002688
Tobias Grosser8286b832015-11-02 11:29:32 +00002689 if (isl_set_is_empty(AssumedContext))
2690 return;
2691
2692 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002693 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002694 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002695 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002696 buildBoundaryContext();
2697 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002698 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002699
2700 hoistInvariantLoads();
Michael Krusecac948e2015-10-02 13:53:07 +00002701 simplifySCoP(false);
Tobias Grosser75805372011-04-29 06:27:02 +00002702}
2703
2704Scop::~Scop() {
2705 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002706 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002707 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002708 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002709
Johannes Doerfert96425c22015-08-30 21:13:53 +00002710 for (auto It : DomainMap)
2711 isl_set_free(It.second);
2712
Johannes Doerfertb164c792014-09-18 11:17:17 +00002713 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002714 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002715 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002716 isl_pw_multi_aff_free(MMA.first);
2717 isl_pw_multi_aff_free(MMA.second);
2718 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002719 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002720 isl_pw_multi_aff_free(MMA.first);
2721 isl_pw_multi_aff_free(MMA.second);
2722 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002723 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002724
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002725 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002726 isl_set_free(std::get<2>(IAClass));
Tobias Grosser75805372011-04-29 06:27:02 +00002727}
2728
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002729void Scop::updateAccessDimensionality() {
2730 for (auto &Stmt : *this)
2731 for (auto &Access : Stmt)
2732 Access->updateDimensionality();
2733}
2734
Michael Krusecac948e2015-10-02 13:53:07 +00002735void Scop::simplifySCoP(bool RemoveIgnoredStmts) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002736 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2737 ScopStmt &Stmt = *StmtIt;
Michael Krusecac948e2015-10-02 13:53:07 +00002738 RegionNode *RN = Stmt.isRegionStmt()
2739 ? Stmt.getRegion()->getNode()
2740 : getRegion().getBBNode(Stmt.getBasicBlock());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002741
Johannes Doerferteca9e892015-11-03 16:54:49 +00002742 bool RemoveStmt = StmtIt->isEmpty();
2743 if (!RemoveStmt)
2744 RemoveStmt = isl_set_is_empty(DomainMap[getRegionNodeBasicBlock(RN)]);
2745 if (!RemoveStmt)
2746 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002747
Johannes Doerferteca9e892015-11-03 16:54:49 +00002748 // Remove read only statements only after invariant loop hoisting.
2749 if (!RemoveStmt && !RemoveIgnoredStmts) {
2750 bool OnlyRead = true;
2751 for (MemoryAccess *MA : Stmt) {
2752 if (MA->isRead())
2753 continue;
2754
2755 OnlyRead = false;
2756 break;
2757 }
2758
2759 RemoveStmt = OnlyRead;
2760 }
2761
2762 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00002763 // Remove the statement because it is unnecessary.
2764 if (Stmt.isRegionStmt())
2765 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2766 StmtMap.erase(BB);
2767 else
2768 StmtMap.erase(Stmt.getBasicBlock());
2769
2770 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002771 continue;
2772 }
2773
Michael Krusecac948e2015-10-02 13:53:07 +00002774 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002775 }
2776}
2777
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002778const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2779 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2780 if (!LInst)
2781 return nullptr;
2782
2783 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2784 LInst = cast<LoadInst>(Rep);
2785
2786 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2787 for (auto &IAClass : InvariantEquivClasses)
2788 if (PointerSCEV == std::get<0>(IAClass))
2789 return &IAClass;
2790
2791 return nullptr;
2792}
2793
2794void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2795
2796 // Get the context under which the statement is executed.
2797 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2798 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2799 DomainCtx = isl_set_detect_equalities(DomainCtx);
2800 DomainCtx = isl_set_coalesce(DomainCtx);
2801
2802 // Project out all parameters that relate to loads in the statement. Otherwise
2803 // we could have cyclic dependences on the constraints under which the
2804 // hoisted loads are executed and we could not determine an order in which to
2805 // pre-load them. This happens because not only lower bounds are part of the
2806 // domain but also upper bounds.
2807 for (MemoryAccess *MA : InvMAs) {
2808 Instruction *AccInst = MA->getAccessInstruction();
2809 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00002810 SetVector<Value *> Values;
2811 for (const SCEV *Parameter : Parameters) {
2812 Values.clear();
2813 findValues(Parameter, Values);
2814 if (!Values.count(AccInst))
2815 continue;
2816
2817 if (isl_id *ParamId = getIdForParam(Parameter)) {
2818 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2819 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2820 isl_id_free(ParamId);
2821 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002822 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002823 }
2824 }
2825
2826 for (MemoryAccess *MA : InvMAs) {
2827 // Check for another invariant access that accesses the same location as
2828 // MA and if found consolidate them. Otherwise create a new equivalence
2829 // class at the end of InvariantEquivClasses.
2830 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
2831 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2832
2833 bool Consolidated = false;
2834 for (auto &IAClass : InvariantEquivClasses) {
2835 if (PointerSCEV != std::get<0>(IAClass))
2836 continue;
2837
2838 Consolidated = true;
2839
2840 // Add MA to the list of accesses that are in this class.
2841 auto &MAs = std::get<1>(IAClass);
2842 MAs.push_front(MA);
2843
2844 // Unify the execution context of the class and this statement.
2845 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002846 if (IAClassDomainCtx)
2847 IAClassDomainCtx = isl_set_coalesce(
2848 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
2849 else
2850 IAClassDomainCtx = isl_set_copy(DomainCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002851 break;
2852 }
2853
2854 if (Consolidated)
2855 continue;
2856
2857 // If we did not consolidate MA, thus did not find an equivalence class
2858 // for it, we create a new one.
2859 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
2860 isl_set_copy(DomainCtx));
2861 }
2862
2863 isl_set_free(DomainCtx);
2864}
2865
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002866void Scop::hoistInvariantLoads() {
2867 isl_union_map *Writes = getWrites();
2868 for (ScopStmt &Stmt : *this) {
2869
2870 // TODO: Loads that are not loop carried, hence are in a statement with
2871 // zero iterators, are by construction invariant, though we
Johannes Doerfert09e36972015-10-07 20:17:36 +00002872 // currently "hoist" them anyway. This is necessary because we allow
2873 // them to be treated as parameters (e.g., in conditions) and our code
2874 // generation would otherwise use the old value.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002875
Johannes Doerfert8930f482015-10-02 14:51:00 +00002876 BasicBlock *BB = Stmt.isBlockStmt() ? Stmt.getBasicBlock()
2877 : Stmt.getRegion()->getEntry();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002878 isl_set *Domain = Stmt.getDomain();
2879 MemoryAccessList InvMAs;
2880
2881 for (MemoryAccess *MA : Stmt) {
2882 if (MA->isImplicit() || MA->isWrite() || !MA->isAffine())
2883 continue;
2884
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002885 // Skip accesses that have an invariant base pointer which is defined but
2886 // not loaded inside the SCoP. This can happened e.g., if a readnone call
2887 // returns a pointer that is used as a base address. However, as we want
2888 // to hoist indirect pointers, we allow the base pointer to be defined in
Johannes Doerfert654c3282015-10-21 22:14:57 +00002889 // the region if it is also a memory access. Each ScopArrayInfo object
2890 // that has a base pointer origin has a base pointer that is loaded and
2891 // that it is invariant, thus it will be hoisted too. However, if there is
Tobias Grosser27e19a02015-10-25 12:05:14 +00002892 // no base pointer origin we check that the base pointer is defined
Johannes Doerfert654c3282015-10-21 22:14:57 +00002893 // outside the region.
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002894 const ScopArrayInfo *SAI = MA->getScopArrayInfo();
Johannes Doerfert654c3282015-10-21 22:14:57 +00002895 while (auto *BasePtrOriginSAI = SAI->getBasePtrOriginSAI())
2896 SAI = BasePtrOriginSAI;
2897
2898 if (auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr()))
2899 if (R.contains(BasePtrInst))
2900 continue;
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002901
Johannes Doerfert8930f482015-10-02 14:51:00 +00002902 // Skip accesses in non-affine subregions as they might not be executed
2903 // under the same condition as the entry of the non-affine subregion.
2904 if (BB != MA->getAccessInstruction()->getParent())
2905 continue;
2906
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002907 isl_map *AccessRelation = MA->getAccessRelation();
Johannes Doerfertb864c2c2015-10-18 19:50:18 +00002908
2909 // Skip accesses that have an empty access relation. These can be caused
2910 // by multiple offsets with a type cast in-between that cause the overall
2911 // byte offset to be not divisible by the new types sizes.
2912 if (isl_map_is_empty(AccessRelation)) {
2913 isl_map_free(AccessRelation);
2914 continue;
2915 }
2916
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002917 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
2918 Stmt.getNumIterators())) {
2919 isl_map_free(AccessRelation);
2920 continue;
2921 }
2922
2923 AccessRelation =
2924 isl_map_intersect_domain(AccessRelation, isl_set_copy(Domain));
2925 isl_set *AccessRange = isl_map_range(AccessRelation);
2926
2927 isl_union_map *Written = isl_union_map_intersect_range(
2928 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
2929 bool IsWritten = !isl_union_map_is_empty(Written);
2930 isl_union_map_free(Written);
2931
2932 if (IsWritten)
2933 continue;
2934
2935 InvMAs.push_front(MA);
2936 }
2937
2938 // We inserted invariant accesses always in the front but need them to be
2939 // sorted in a "natural order". The statements are already sorted in reverse
2940 // post order and that suffices for the accesses too. The reason we require
2941 // an order in the first place is the dependences between invariant loads
2942 // that can be caused by indirect loads.
2943 InvMAs.reverse();
2944
2945 // Transfer the memory access from the statement to the SCoP.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002946 Stmt.removeMemoryAccesses(InvMAs);
2947 addInvariantLoads(Stmt, InvMAs);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002948
2949 isl_set_free(Domain);
2950 }
2951 isl_union_map_free(Writes);
2952
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002953 auto &ScopRIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert09e36972015-10-07 20:17:36 +00002954 // Check required invariant loads that were tagged during SCoP detection.
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002955 for (LoadInst *LI : ScopRIL) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00002956 assert(LI && getRegion().contains(LI));
2957 ScopStmt *Stmt = getStmtForBasicBlock(LI->getParent());
2958 if (Stmt && Stmt->lookupAccessesFor(LI) != nullptr) {
2959 DEBUG(dbgs() << "\n\nWARNING: Load (" << *LI
2960 << ") is required to be invariant but was not marked as "
2961 "such. SCoP for "
2962 << getRegion() << " will be dropped\n\n");
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002963 addAssumption(INVARIANTLOAD, isl_set_empty(getParamSpace()),
2964 LI->getDebugLoc());
Johannes Doerfert09e36972015-10-07 20:17:36 +00002965 return;
2966 }
2967 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002968}
2969
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002970const ScopArrayInfo *
2971Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002972 ArrayRef<const SCEV *> Sizes,
2973 ScopArrayInfo::ARRAYKIND Kind) {
2974 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002975 if (!SAI) {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00002976 auto &DL = getRegion().getEntry()->getModule()->getDataLayout();
2977 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, Kind,
2978 DL, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002979 } else {
Tobias Grosser8286b832015-11-02 11:29:32 +00002980 // In case of mismatching array sizes, we bail out by setting the run-time
2981 // context to false.
2982 if (!SAI->updateSizes(Sizes))
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002983 addAssumption(DELINEARIZATION, isl_set_empty(getParamSpace()),
2984 DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002985 }
Tobias Grosserab671442015-05-23 05:58:27 +00002986 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002987}
2988
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002989const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
2990 ScopArrayInfo::ARRAYKIND Kind) {
2991 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002992 assert(SAI && "No ScopArrayInfo available for this base pointer");
2993 return SAI;
2994}
2995
Tobias Grosser74394f02013-01-14 22:40:23 +00002996std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002997std::string Scop::getAssumedContextStr() const {
2998 return stringFromIslObj(AssumedContext);
2999}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003000std::string Scop::getBoundaryContextStr() const {
3001 return stringFromIslObj(BoundaryContext);
3002}
Tobias Grosser75805372011-04-29 06:27:02 +00003003
3004std::string Scop::getNameStr() const {
3005 std::string ExitName, EntryName;
3006 raw_string_ostream ExitStr(ExitName);
3007 raw_string_ostream EntryStr(EntryName);
3008
Tobias Grosserf240b482014-01-09 10:42:15 +00003009 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003010 EntryStr.str();
3011
3012 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003013 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003014 ExitStr.str();
3015 } else
3016 ExitName = "FunctionExit";
3017
3018 return EntryName + "---" + ExitName;
3019}
3020
Tobias Grosser74394f02013-01-14 22:40:23 +00003021__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003022__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003023 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003024}
3025
Tobias Grossere86109f2013-10-29 21:05:49 +00003026__isl_give isl_set *Scop::getAssumedContext() const {
3027 return isl_set_copy(AssumedContext);
3028}
3029
Johannes Doerfert43788c52015-08-20 05:58:56 +00003030__isl_give isl_set *Scop::getRuntimeCheckContext() const {
3031 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003032 RuntimeCheckContext =
3033 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
3034 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00003035 return RuntimeCheckContext;
3036}
3037
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003038bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003039 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003040 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00003041 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
3042 isl_set_free(RuntimeCheckContext);
3043 return IsFeasible;
3044}
3045
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003046static std::string toString(AssumptionKind Kind) {
3047 switch (Kind) {
3048 case ALIASING:
3049 return "No-aliasing";
3050 case INBOUNDS:
3051 return "Inbounds";
3052 case WRAPPING:
3053 return "No-overflows";
Johannes Doerferta4b77c02015-11-12 20:15:32 +00003054 case ALIGNMENT:
3055 return "Alignment";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003056 case ERRORBLOCK:
3057 return "No-error";
3058 case INFINITELOOP:
3059 return "Finite loop";
3060 case INVARIANTLOAD:
3061 return "Invariant load";
3062 case DELINEARIZATION:
3063 return "Delinearization";
3064 }
3065 llvm_unreachable("Unknown AssumptionKind!");
3066}
3067
3068void Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3069 DebugLoc Loc) {
3070 if (isl_set_is_subset(Context, Set))
3071 return;
3072
3073 if (isl_set_is_subset(AssumedContext, Set))
3074 return;
3075
3076 auto &F = *getRegion().getEntry()->getParent();
3077 std::string Msg = toString(Kind) + " assumption:\t" + stringFromIslObj(Set);
3078 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
3079}
3080
3081void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
3082 DebugLoc Loc) {
3083 trackAssumption(Kind, Set, Loc);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003084 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003085
Johannes Doerfert9d7899e2015-11-11 20:01:31 +00003086 int NSets = isl_set_n_basic_set(AssumedContext);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003087 if (NSets >= MaxDisjunctsAssumed) {
3088 isl_space *Space = isl_set_get_space(AssumedContext);
3089 isl_set_free(AssumedContext);
Tobias Grossere19fca42015-11-11 20:21:39 +00003090 AssumedContext = isl_set_empty(Space);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003091 }
3092
Tobias Grosser7b50bee2014-11-25 10:51:12 +00003093 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003094}
3095
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003096__isl_give isl_set *Scop::getBoundaryContext() const {
3097 return isl_set_copy(BoundaryContext);
3098}
3099
Tobias Grosser75805372011-04-29 06:27:02 +00003100void Scop::printContext(raw_ostream &OS) const {
3101 OS << "Context:\n";
3102
3103 if (!Context) {
3104 OS.indent(4) << "n/a\n\n";
3105 return;
3106 }
3107
3108 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003109
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003110 OS.indent(4) << "Assumed Context:\n";
3111 if (!AssumedContext) {
3112 OS.indent(4) << "n/a\n\n";
3113 return;
3114 }
3115
3116 OS.indent(4) << getAssumedContextStr() << "\n";
3117
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003118 OS.indent(4) << "Boundary Context:\n";
3119 if (!BoundaryContext) {
3120 OS.indent(4) << "n/a\n\n";
3121 return;
3122 }
3123
3124 OS.indent(4) << getBoundaryContextStr() << "\n";
3125
Tobias Grosser083d3d32014-06-28 08:59:45 +00003126 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00003127 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00003128 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
3129 }
Tobias Grosser75805372011-04-29 06:27:02 +00003130}
3131
Johannes Doerfertb164c792014-09-18 11:17:17 +00003132void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003133 int noOfGroups = 0;
3134 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003135 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003136 noOfGroups += 1;
3137 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003138 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003139 }
3140
Tobias Grosserbb853c22015-07-25 12:31:03 +00003141 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003142 if (MinMaxAliasGroups.empty()) {
3143 OS.indent(8) << "n/a\n";
3144 return;
3145 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003146
Tobias Grosserbb853c22015-07-25 12:31:03 +00003147 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003148
3149 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003150 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003151 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003152 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003153 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3154 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003155 }
3156 OS << " ]]\n";
3157 }
3158
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003159 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003160 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003161 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003162 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003163 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3164 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003165 }
3166 OS << " ]]\n";
3167 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003168 }
3169}
3170
Tobias Grosser75805372011-04-29 06:27:02 +00003171void Scop::printStatements(raw_ostream &OS) const {
3172 OS << "Statements {\n";
3173
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003174 for (const ScopStmt &Stmt : *this)
3175 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003176
3177 OS.indent(4) << "}\n";
3178}
3179
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003180void Scop::printArrayInfo(raw_ostream &OS) const {
3181 OS << "Arrays {\n";
3182
Tobias Grosserab671442015-05-23 05:58:27 +00003183 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003184 Array.second->print(OS);
3185
3186 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003187
3188 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3189
3190 for (auto &Array : arrays())
3191 Array.second->print(OS, /* SizeAsPwAff */ true);
3192
3193 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003194}
3195
Tobias Grosser75805372011-04-29 06:27:02 +00003196void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00003197 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
3198 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003199 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003200 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003201 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003202 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003203 const auto &MAs = std::get<1>(IAClass);
3204 if (MAs.empty()) {
3205 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003206 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003207 MAs.front()->print(OS);
3208 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003209 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003210 }
3211 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003212 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003213 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003214 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003215 printStatements(OS.indent(4));
3216}
3217
3218void Scop::dump() const { print(dbgs()); }
3219
Tobias Grosser9a38ab82011-11-08 15:41:03 +00003220isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00003221
Johannes Doerfertcef616f2015-09-15 22:49:04 +00003222__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
3223 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003224}
3225
Tobias Grosser808cd692015-07-14 09:33:13 +00003226__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003227 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003228
Tobias Grosser808cd692015-07-14 09:33:13 +00003229 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003230 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003231
3232 return Domain;
3233}
3234
Tobias Grossere5a35142015-11-12 14:07:09 +00003235__isl_give isl_union_map *
3236Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3237 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003238
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003239 for (ScopStmt &Stmt : *this) {
3240 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003241 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003242 continue;
3243
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003244 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003245 isl_map *AccessDomain = MA->getAccessRelation();
3246 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003247 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003248 }
3249 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003250 return isl_union_map_coalesce(Accesses);
3251}
3252
3253__isl_give isl_union_map *Scop::getMustWrites() {
3254 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003255}
3256
3257__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003258 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003259}
3260
Tobias Grosser37eb4222014-02-20 21:43:54 +00003261__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003262 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003263}
3264
3265__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003266 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003267}
3268
Tobias Grosser2ac23382015-11-12 14:07:13 +00003269__isl_give isl_union_map *Scop::getAccesses() {
3270 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3271}
3272
Tobias Grosser808cd692015-07-14 09:33:13 +00003273__isl_give isl_union_map *Scop::getSchedule() const {
3274 auto Tree = getScheduleTree();
3275 auto S = isl_schedule_get_map(Tree);
3276 isl_schedule_free(Tree);
3277 return S;
3278}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003279
Tobias Grosser808cd692015-07-14 09:33:13 +00003280__isl_give isl_schedule *Scop::getScheduleTree() const {
3281 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3282 getDomains());
3283}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003284
Tobias Grosser808cd692015-07-14 09:33:13 +00003285void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3286 auto *S = isl_schedule_from_domain(getDomains());
3287 S = isl_schedule_insert_partial_schedule(
3288 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3289 isl_schedule_free(Schedule);
3290 Schedule = S;
3291}
3292
3293void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3294 isl_schedule_free(Schedule);
3295 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003296}
3297
3298bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3299 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003300 for (ScopStmt &Stmt : *this) {
3301 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003302 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3303 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3304
3305 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3306 isl_union_set_free(StmtDomain);
3307 isl_union_set_free(NewStmtDomain);
3308 continue;
3309 }
3310
3311 Changed = true;
3312
3313 isl_union_set_free(StmtDomain);
3314 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3315
3316 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003317 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003318 isl_union_set_free(NewStmtDomain);
3319 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003320 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003321 }
3322 isl_union_set_free(Domain);
3323 return Changed;
3324}
3325
Tobias Grosser75805372011-04-29 06:27:02 +00003326ScalarEvolution *Scop::getSE() const { return SE; }
3327
Johannes Doerfertf5673802015-10-01 23:48:18 +00003328bool Scop::isIgnored(RegionNode *RN) {
3329 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser75805372011-04-29 06:27:02 +00003330
Johannes Doerfertf5673802015-10-01 23:48:18 +00003331 // Check if there are accesses contained.
3332 bool ContainsAccesses = false;
3333 if (!RN->isSubRegion())
3334 ContainsAccesses = getAccessFunctions(BB);
3335 else
3336 for (BasicBlock *RBB : RN->getNodeAs<Region>()->blocks())
3337 ContainsAccesses |= (getAccessFunctions(RBB) != nullptr);
3338 if (!ContainsAccesses)
3339 return true;
3340
3341 // Check for reachability via non-error blocks.
3342 if (!DomainMap.count(BB))
3343 return true;
3344
3345 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003346 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003347 return true;
3348
3349 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003350}
3351
Tobias Grosser808cd692015-07-14 09:33:13 +00003352struct MapToDimensionDataTy {
3353 int N;
3354 isl_union_pw_multi_aff *Res;
3355};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003356
Tobias Grosser808cd692015-07-14 09:33:13 +00003357// @brief Create a function that maps the elements of 'Set' to its N-th
3358// dimension.
3359//
3360// The result is added to 'User->Res'.
3361//
3362// @param Set The input set.
3363// @param N The dimension to map to.
3364//
3365// @returns Zero if no error occurred, non-zero otherwise.
3366static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3367 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3368 int Dim;
3369 isl_space *Space;
3370 isl_pw_multi_aff *PMA;
3371
3372 Dim = isl_set_dim(Set, isl_dim_set);
3373 Space = isl_set_get_space(Set);
3374 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3375 Dim - Data->N);
3376 if (Data->N > 1)
3377 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3378 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3379
3380 isl_set_free(Set);
3381
3382 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003383}
3384
Tobias Grosser808cd692015-07-14 09:33:13 +00003385// @brief Create a function that maps the elements of Domain to their Nth
3386// dimension.
3387//
3388// @param Domain The set of elements to map.
3389// @param N The dimension to map to.
3390static __isl_give isl_multi_union_pw_aff *
3391mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003392 if (N <= 0 || isl_union_set_is_empty(Domain)) {
3393 isl_union_set_free(Domain);
3394 return nullptr;
3395 }
3396
Tobias Grosser808cd692015-07-14 09:33:13 +00003397 struct MapToDimensionDataTy Data;
3398 isl_space *Space;
3399
3400 Space = isl_union_set_get_space(Domain);
3401 Data.N = N;
3402 Data.Res = isl_union_pw_multi_aff_empty(Space);
3403 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
3404 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
3405
3406 isl_union_set_free(Domain);
3407 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3408}
3409
Tobias Grosser316b5b22015-11-11 19:28:14 +00003410void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003411 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003412 Stmts.emplace_back(*this, *BB);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003413 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003414 StmtMap[BB] = Stmt;
3415 } else {
3416 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003417 Stmts.emplace_back(*this, *R);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003418 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003419 for (BasicBlock *BB : R->blocks())
3420 StmtMap[BB] = Stmt;
3421 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003422}
3423
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003424void Scop::buildSchedule(
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003425 Region *R,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003426 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00003427
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003428 if (SD.isNonAffineSubRegion(R, &getRegion())) {
Johannes Doerfertc6987c12015-09-26 13:41:43 +00003429 Loop *L = getLoopSurroundingRegion(*R, LI);
3430 auto &LSchedulePair = LoopSchedules[L];
Michael Krusecac948e2015-10-02 13:53:07 +00003431 ScopStmt *Stmt = getStmtForBasicBlock(R->getEntry());
Michael Kruseafe06702015-10-02 16:33:27 +00003432 isl_set *Domain = Stmt->getDomain();
Michael Krusecac948e2015-10-02 13:53:07 +00003433 auto *UDomain = isl_union_set_from_set(Domain);
3434 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003435 LSchedulePair.first = StmtSchedule;
3436 return;
3437 }
3438
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003439 ReversePostOrderTraversal<Region *> RTraversal(R);
3440 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00003441
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003442 if (RN->isSubRegion()) {
3443 Region *SubRegion = RN->getNodeAs<Region>();
3444 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003445 buildSchedule(SubRegion, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003446 continue;
3447 }
Tobias Grosser75805372011-04-29 06:27:02 +00003448 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003449
3450 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert30c22652015-10-18 21:17:11 +00003451 if (!getRegion().contains(L))
3452 L = getLoopSurroundingRegion(getRegion(), LI);
3453
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003454 int LD = getRelativeLoopDepth(L);
3455 auto &LSchedulePair = LoopSchedules[L];
3456 LSchedulePair.second += getNumBlocksInRegionNode(RN);
3457
Michael Krusecac948e2015-10-02 13:53:07 +00003458 BasicBlock *BB = getRegionNodeBasicBlock(RN);
3459 ScopStmt *Stmt = getStmtForBasicBlock(BB);
3460 if (Stmt) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003461 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3462 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
3463 LSchedulePair.first =
3464 combineInSequence(LSchedulePair.first, StmtSchedule);
3465 }
3466
3467 unsigned NumVisited = LSchedulePair.second;
3468 while (L && NumVisited == L->getNumBlocks()) {
3469 auto *LDomain = isl_schedule_get_domain(LSchedulePair.first);
3470 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
3471 LSchedulePair.first =
3472 isl_schedule_insert_partial_schedule(LSchedulePair.first, MUPA);
3473
3474 auto *PL = L->getParentLoop();
Johannes Doerfertdca28372015-11-03 00:28:07 +00003475
3476 // Either we have a proper loop and we also build a schedule for the
3477 // parent loop or we have a infinite loop that does not have a proper
3478 // parent loop. In the former case this conditional will be skipped, in
3479 // the latter case however we will break here as we do not build a domain
3480 // nor a schedule for a infinite loop.
3481 assert(LoopSchedules.count(PL) || LSchedulePair.first == nullptr);
3482 if (!LoopSchedules.count(PL))
3483 break;
3484
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003485 auto &PSchedulePair = LoopSchedules[PL];
3486 PSchedulePair.first =
3487 combineInSequence(PSchedulePair.first, LSchedulePair.first);
3488 PSchedulePair.second += NumVisited;
3489
3490 L = PL;
3491 NumVisited = PSchedulePair.second;
3492 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003493 }
Tobias Grosser75805372011-04-29 06:27:02 +00003494}
3495
Johannes Doerfert7c494212014-10-31 23:13:39 +00003496ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003497 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003498 if (StmtMapIt == StmtMap.end())
3499 return nullptr;
3500 return StmtMapIt->second;
3501}
3502
Johannes Doerfert96425c22015-08-30 21:13:53 +00003503int Scop::getRelativeLoopDepth(const Loop *L) const {
3504 Loop *OuterLoop =
3505 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3506 if (!OuterLoop)
3507 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003508 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3509}
3510
Michael Krused868b5d2015-09-10 15:25:24 +00003511void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003512 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003513
3514 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3515 // true, are not modeled as ordinary PHI nodes as they are not part of the
3516 // region. However, we model the operands in the predecessor blocks that are
3517 // part of the region as regular scalar accesses.
3518
3519 // If we can synthesize a PHI we can skip it, however only if it is in
3520 // the region. If it is not it can only be in the exit block of the region.
3521 // In this case we model the operands but not the PHI itself.
3522 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3523 return;
3524
3525 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3526 // detection. Hence, the PHI is a load of a new memory location in which the
3527 // incoming value was written at the end of the incoming basic block.
3528 bool OnlyNonAffineSubRegionOperands = true;
3529 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3530 Value *Op = PHI->getIncomingValue(u);
3531 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3532
3533 // Do not build scalar dependences inside a non-affine subregion.
3534 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3535 continue;
3536
3537 OnlyNonAffineSubRegionOperands = false;
3538
3539 if (!R.contains(OpBB))
3540 continue;
3541
3542 Instruction *OpI = dyn_cast<Instruction>(Op);
3543 if (OpI) {
3544 BasicBlock *OpIBB = OpI->getParent();
3545 // As we pretend there is a use (or more precise a write) of OpI in OpBB
3546 // we have to insert a scalar dependence from the definition of OpI to
3547 // OpBB if the definition is not in OpBB.
Michael Kruse668af712015-10-15 14:45:48 +00003548 if (scop->getStmtForBasicBlock(OpIBB) !=
3549 scop->getStmtForBasicBlock(OpBB)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003550 addScalarReadAccess(OpI, PHI, OpBB);
3551 addScalarWriteAccess(OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003552 }
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003553 } else if (ModelReadOnlyScalars && !isa<Constant>(Op)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003554 addScalarReadAccess(Op, PHI, OpBB);
Michael Kruse7bf39442015-09-10 12:46:52 +00003555 }
3556
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003557 addPHIWriteAccess(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003558 }
3559
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003560 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3561 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003562 }
3563}
3564
Michael Krused868b5d2015-09-10 15:25:24 +00003565bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
3566 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003567 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
3568 if (isIgnoredIntrinsic(Inst))
3569 return false;
3570
3571 bool AnyCrossStmtUse = false;
3572 BasicBlock *ParentBB = Inst->getParent();
3573
3574 for (User *U : Inst->users()) {
3575 Instruction *UI = dyn_cast<Instruction>(U);
3576
3577 // Ignore the strange user
3578 if (UI == 0)
3579 continue;
3580
3581 BasicBlock *UseParent = UI->getParent();
3582
Tobias Grosserbaffa092015-10-24 20:55:27 +00003583 // Ignore basic block local uses. A value that is defined in a scop, but
3584 // used in a PHI node in the same basic block does not count as basic block
3585 // local, as for such cases a control flow edge is passed between definition
3586 // and use.
3587 if (UseParent == ParentBB && !isa<PHINode>(UI))
Michael Kruse7bf39442015-09-10 12:46:52 +00003588 continue;
3589
Michael Krusef714d472015-11-05 13:18:43 +00003590 // Uses by PHI nodes in the entry node count as external uses in case the
3591 // use is through an incoming block that is itself not contained in the
3592 // region.
3593 if (R->getEntry() == UseParent) {
3594 if (auto *PHI = dyn_cast<PHINode>(UI)) {
3595 bool ExternalUse = false;
3596 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
3597 if (PHI->getIncomingValue(i) == Inst &&
3598 !R->contains(PHI->getIncomingBlock(i))) {
3599 ExternalUse = true;
3600 break;
3601 }
3602 }
3603
3604 if (ExternalUse) {
3605 AnyCrossStmtUse = true;
3606 continue;
3607 }
3608 }
3609 }
3610
Michael Kruse7bf39442015-09-10 12:46:52 +00003611 // Do not build scalar dependences inside a non-affine subregion.
3612 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
3613 continue;
3614
Michael Kruse01cb3792015-10-17 21:07:08 +00003615 // Check for PHI nodes in the region exit and skip them, if they will be
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003616 // modeled as PHI nodes.
Michael Kruse01cb3792015-10-17 21:07:08 +00003617 //
3618 // PHI nodes in the region exit that have more than two incoming edges need
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003619 // to be modeled as PHI-Nodes to correctly model the fact that depending on
3620 // the control flow a different value will be assigned to the PHI node. In
3621 // case this is the case, there is no need to create an additional normal
3622 // scalar dependence. Hence, bail out before we register an "out-of-region"
3623 // use for this definition.
Michael Kruse01cb3792015-10-17 21:07:08 +00003624 if (isa<PHINode>(UI) && UI->getParent() == R->getExit() &&
3625 !R->getExitingBlock())
3626 continue;
3627
Michael Kruse7bf39442015-09-10 12:46:52 +00003628 // Check whether or not the use is in the SCoP.
Tobias Grosserc73d8b02015-10-23 22:36:22 +00003629 if (!R->contains(UseParent)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003630 AnyCrossStmtUse = true;
3631 continue;
3632 }
3633
3634 // If the instruction can be synthesized and the user is in the region
3635 // we do not need to add scalar dependences.
3636 if (canSynthesizeInst)
3637 continue;
3638
3639 // No need to translate these scalar dependences into polyhedral form,
3640 // because synthesizable scalars can be generated by the code generator.
3641 if (canSynthesize(UI, LI, SE, R))
3642 continue;
3643
3644 // Skip PHI nodes in the region as they handle their operands on their own.
3645 if (isa<PHINode>(UI))
3646 continue;
3647
3648 // Now U is used in another statement.
3649 AnyCrossStmtUse = true;
3650
3651 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00003652 // Use the def instruction as base address of the MemoryAccess, so that it
3653 // will become the name of the scalar access in the polyhedral form.
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003654 addScalarReadAccess(Inst, UI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003655 }
3656
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003657 if (ModelReadOnlyScalars && !isa<PHINode>(Inst)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003658 for (Value *Op : Inst->operands()) {
3659 if (canSynthesize(Op, LI, SE, R))
3660 continue;
3661
3662 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
3663 if (R->contains(OpInst))
3664 continue;
3665
3666 if (isa<Constant>(Op))
3667 continue;
3668
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003669 addScalarReadAccess(Op, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003670 }
3671 }
3672
3673 return AnyCrossStmtUse;
3674}
3675
3676extern MapInsnToMemAcc InsnToMemAcc;
3677
Michael Krusee2bccbb2015-09-18 19:59:43 +00003678void ScopInfo::buildMemoryAccess(
3679 Instruction *Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003680 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3681 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003682 unsigned Size;
3683 Type *SizeType;
3684 Value *Val;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003685 enum MemoryAccess::AccessType Type;
Michael Kruse7bf39442015-09-10 12:46:52 +00003686
3687 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
3688 SizeType = Load->getType();
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003689 Size = TD->getTypeAllocSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003690 Type = MemoryAccess::READ;
Michael Kruse7bf39442015-09-10 12:46:52 +00003691 Val = Load;
3692 } else {
3693 StoreInst *Store = cast<StoreInst>(Inst);
3694 SizeType = Store->getValueOperand()->getType();
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003695 Size = TD->getTypeAllocSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003696 Type = MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003697 Val = Store->getValueOperand();
3698 }
3699
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003700 auto Address = getPointerOperand(*Inst);
3701
3702 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003703 const SCEVUnknown *BasePointer =
3704 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3705
3706 assert(BasePointer && "Could not find base pointer");
3707 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
3708
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003709 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3710 auto NewAddress = Address;
3711 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3712 auto Src = BitCast->getOperand(0);
3713 auto SrcTy = Src->getType();
3714 auto DstTy = BitCast->getType();
3715 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3716 NewAddress = Src;
3717 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003718
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003719 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3720 std::vector<const SCEV *> Subscripts;
3721 std::vector<int> Sizes;
3722 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3723 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003724
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003725 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003726
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003727 bool AllAffineSubcripts = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003728 for (auto Subscript : Subscripts) {
3729 InvariantLoadsSetTy AccessILS;
3730 AllAffineSubcripts =
3731 isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS);
3732
3733 for (LoadInst *LInst : AccessILS)
3734 if (!ScopRIL.count(LInst))
3735 AllAffineSubcripts = false;
3736
3737 if (!AllAffineSubcripts)
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003738 break;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003739 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003740
3741 if (AllAffineSubcripts && Sizes.size() > 0) {
3742 for (auto V : Sizes)
3743 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3744 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003745 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003746 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003747
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003748 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3749 Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00003750 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003751 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003752 }
3753 }
3754
Michael Kruse7bf39442015-09-10 12:46:52 +00003755 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003756 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003757 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3758 AccItr->second.DelinearizedSubscripts,
3759 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003760 return;
3761 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003762
3763 // Check if the access depends on a loop contained in a non-affine subregion.
3764 bool isVariantInNonAffineLoop = false;
3765 if (BoxedLoops) {
3766 SetVector<const Loop *> Loops;
3767 findLoops(AccessFunction, Loops);
3768 for (const Loop *L : Loops)
3769 if (BoxedLoops->count(L))
3770 isVariantInNonAffineLoop = true;
3771 }
3772
Johannes Doerfert09e36972015-10-07 20:17:36 +00003773 InvariantLoadsSetTy AccessILS;
3774 bool IsAffine =
3775 !isVariantInNonAffineLoop &&
3776 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3777
3778 for (LoadInst *LInst : AccessILS)
3779 if (!ScopRIL.count(LInst))
3780 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003781
Michael Krusecaac2b62015-09-26 15:51:44 +00003782 // FIXME: Size of the number of bytes of an array element, not the number of
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003783 // elements as probably intended here.
Tobias Grossera43b6e92015-09-27 17:54:50 +00003784 const SCEV *SizeSCEV =
3785 SE->getConstant(TD->getIntPtrType(Inst->getContext()), Size);
Michael Kruse7bf39442015-09-10 12:46:52 +00003786
Michael Krusee2bccbb2015-09-18 19:59:43 +00003787 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3788 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003789
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003790 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, IsAffine,
3791 ArrayRef<const SCEV *>(AccessFunction),
3792 ArrayRef<const SCEV *>(SizeSCEV), Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003793}
3794
Michael Krused868b5d2015-09-10 15:25:24 +00003795void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003796
3797 if (SD->isNonAffineSubRegion(&SR, &R)) {
3798 for (BasicBlock *BB : SR.blocks())
3799 buildAccessFunctions(R, *BB, &SR);
3800 return;
3801 }
3802
3803 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3804 if (I->isSubRegion())
3805 buildAccessFunctions(R, *I->getNodeAs<Region>());
3806 else
3807 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
3808}
3809
Michael Krusecac948e2015-10-02 13:53:07 +00003810void ScopInfo::buildStmts(Region &SR) {
3811 Region *R = getRegion();
3812
3813 if (SD->isNonAffineSubRegion(&SR, R)) {
3814 scop->addScopStmt(nullptr, &SR);
3815 return;
3816 }
3817
3818 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3819 if (I->isSubRegion())
3820 buildStmts(*I->getNodeAs<Region>());
3821 else
3822 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
3823}
3824
Michael Krused868b5d2015-09-10 15:25:24 +00003825void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
3826 Region *NonAffineSubRegion,
3827 bool IsExitBlock) {
Tobias Grosser910cf262015-11-11 20:15:49 +00003828 // We do not build access functions for error blocks, as they may contain
3829 // instructions we can not model.
3830 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3831 if (isErrorBlock(BB, R, *LI, DT) && !IsExitBlock)
3832 return;
3833
Michael Kruse7bf39442015-09-10 12:46:52 +00003834 Loop *L = LI->getLoopFor(&BB);
3835
3836 // The set of loops contained in non-affine subregions that are part of R.
3837 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3838
Johannes Doerfert09e36972015-10-07 20:17:36 +00003839 // The set of loads that are required to be invariant.
3840 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
3841
Michael Kruse7bf39442015-09-10 12:46:52 +00003842 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00003843 Instruction *Inst = &*I;
Michael Kruse7bf39442015-09-10 12:46:52 +00003844
3845 PHINode *PHI = dyn_cast<PHINode>(Inst);
3846 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003847 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003848
3849 // For the exit block we stop modeling after the last PHI node.
3850 if (!PHI && IsExitBlock)
3851 break;
3852
Johannes Doerfert09e36972015-10-07 20:17:36 +00003853 // TODO: At this point we only know that elements of ScopRIL have to be
3854 // invariant and will be hoisted for the SCoP to be processed. Though,
3855 // there might be other invariant accesses that will be hoisted and
3856 // that would allow to make a non-affine access affine.
Michael Kruse7bf39442015-09-10 12:46:52 +00003857 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
Johannes Doerfert09e36972015-10-07 20:17:36 +00003858 buildMemoryAccess(Inst, L, &R, BoxedLoops, ScopRIL);
Michael Kruse7bf39442015-09-10 12:46:52 +00003859
3860 if (isIgnoredIntrinsic(Inst))
3861 continue;
3862
Johannes Doerfert09e36972015-10-07 20:17:36 +00003863 // Do not build scalar dependences for required invariant loads as we will
3864 // hoist them later on anyway or drop the SCoP if we cannot.
3865 if (ScopRIL.count(dyn_cast<LoadInst>(Inst)))
3866 continue;
3867
Michael Kruse7bf39442015-09-10 12:46:52 +00003868 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00003869 if (!isa<StoreInst>(Inst))
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003870 addScalarWriteAccess(Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003871 }
3872 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003873}
Michael Kruse7bf39442015-09-10 12:46:52 +00003874
Michael Kruse2d0ece92015-09-24 11:41:21 +00003875void ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3876 MemoryAccess::AccessType Type,
3877 Value *BaseAddress, unsigned ElemBytes,
3878 bool Affine, Value *AccessValue,
3879 ArrayRef<const SCEV *> Subscripts,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003880 ArrayRef<const SCEV *> Sizes,
3881 MemoryAccess::AccessOrigin Origin) {
Michael Krusecac948e2015-10-02 13:53:07 +00003882 ScopStmt *Stmt = scop->getStmtForBasicBlock(BB);
3883
3884 // Do not create a memory access for anything not in the SCoP. It would be
3885 // ignored anyway.
3886 if (!Stmt)
3887 return;
3888
Michael Krusee2bccbb2015-09-18 19:59:43 +00003889 AccFuncSetType &AccList = AccFuncMap[BB];
Michael Krusee2bccbb2015-09-18 19:59:43 +00003890 Value *BaseAddr = BaseAddress;
3891 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3892
Michael Krusecac948e2015-10-02 13:53:07 +00003893 bool isApproximated =
3894 Stmt->isRegionStmt() && (Stmt->getRegion()->getEntry() != BB);
3895 if (isApproximated && Type == MemoryAccess::MUST_WRITE)
3896 Type = MemoryAccess::MAY_WRITE;
3897
Tobias Grosserf1bfd752015-11-05 20:15:37 +00003898 AccList.emplace_back(Stmt, Inst, Type, BaseAddress, ElemBytes, Affine,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003899 Subscripts, Sizes, AccessValue, Origin, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00003900 Stmt->addAccess(&AccList.back());
Michael Kruse7bf39442015-09-10 12:46:52 +00003901}
3902
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003903void ScopInfo::addExplicitAccess(
3904 Instruction *MemAccInst, MemoryAccess::AccessType Type, Value *BaseAddress,
3905 unsigned ElemBytes, bool IsAffine, ArrayRef<const SCEV *> Subscripts,
3906 ArrayRef<const SCEV *> Sizes, Value *AccessValue) {
3907 assert(isa<LoadInst>(MemAccInst) || isa<StoreInst>(MemAccInst));
3908 assert(isa<LoadInst>(MemAccInst) == (Type == MemoryAccess::READ));
3909 addMemoryAccess(MemAccInst->getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003910 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
3911 MemoryAccess::EXPLICIT);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003912}
3913void ScopInfo::addScalarWriteAccess(Instruction *Value) {
3914 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
3915 true, Value, ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003916 ArrayRef<const SCEV *>(), MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003917}
3918void ScopInfo::addScalarReadAccess(Value *Value, Instruction *User) {
3919 assert(!isa<PHINode>(User));
3920 addMemoryAccess(User->getParent(), User, MemoryAccess::READ, Value, 1, true,
3921 Value, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003922 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003923}
3924void ScopInfo::addScalarReadAccess(Value *Value, PHINode *User,
3925 BasicBlock *UserBB) {
3926 addMemoryAccess(UserBB, User, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003927 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3928 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003929}
3930void ScopInfo::addPHIWriteAccess(PHINode *PHI, BasicBlock *IncomingBlock,
3931 Value *IncomingValue, bool IsExitBlock) {
3932 addMemoryAccess(IncomingBlock, IncomingBlock->getTerminator(),
3933 MemoryAccess::MUST_WRITE, PHI, 1, true, IncomingValue,
3934 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003935 IsExitBlock ? MemoryAccess::SCALAR : MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003936}
3937void ScopInfo::addPHIReadAccess(PHINode *PHI) {
3938 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003939 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3940 MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003941}
3942
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003943void ScopInfo::buildScop(Region &R, DominatorTree &DT, AssumptionCache &AC) {
Michael Kruse9d080092015-09-11 21:41:48 +00003944 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003945 scop = new Scop(R, AccFuncMap, *SD, *SE, DT, *LI, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00003946
Michael Krusecac948e2015-10-02 13:53:07 +00003947 buildStmts(R);
Michael Kruse7bf39442015-09-10 12:46:52 +00003948 buildAccessFunctions(R, R);
3949
3950 // In case the region does not have an exiting block we will later (during
3951 // code generation) split the exit block. This will move potential PHI nodes
3952 // from the current exit block into the new region exiting block. Hence, PHI
3953 // nodes that are at this point not part of the region will be.
3954 // To handle these PHI nodes later we will now model their operands as scalar
3955 // accesses. Note that we do not model anything in the exit block if we have
3956 // an exiting block in the region, as there will not be any splitting later.
3957 if (!R.getExitingBlock())
3958 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
3959
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003960 scop->init(*AA, AC);
Michael Kruse7bf39442015-09-10 12:46:52 +00003961}
3962
Michael Krused868b5d2015-09-10 15:25:24 +00003963void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00003964 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00003965 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00003966 return;
3967 }
3968
Michael Kruse9d080092015-09-11 21:41:48 +00003969 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00003970}
3971
Michael Krused868b5d2015-09-10 15:25:24 +00003972void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00003973 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00003974 if (scop) {
3975 delete scop;
3976 scop = 0;
3977 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003978}
3979
3980//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00003981ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00003982 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00003983 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00003984}
3985
3986ScopInfo::~ScopInfo() {
3987 clear();
3988 isl_ctx_free(ctx);
3989}
3990
Tobias Grosser75805372011-04-29 06:27:02 +00003991void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00003992 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00003993 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00003994 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00003995 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
3996 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003997 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003998 AU.addRequired<AssumptionCacheTracker>();
Tobias Grosser75805372011-04-29 06:27:02 +00003999 AU.setPreservesAll();
4000}
4001
4002bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00004003 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00004004
Michael Krused868b5d2015-09-10 15:25:24 +00004005 if (!SD->isMaxRegionInScop(*R))
4006 return false;
4007
4008 Function *F = R->getEntry()->getParent();
4009 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4010 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4011 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
4012 TD = &F->getParent()->getDataLayout();
4013 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004014 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krused868b5d2015-09-10 15:25:24 +00004015
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004016 DebugLoc Beg, End;
4017 getDebugLocations(R, Beg, End);
4018 std::string Msg = "SCoP begins here.";
4019 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg);
4020
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004021 buildScop(*R, DT, AC);
Tobias Grosser75805372011-04-29 06:27:02 +00004022
Tobias Grosserd6a50b32015-05-30 06:26:21 +00004023 DEBUG(scop->print(dbgs()));
4024
Michael Kruseafe06702015-10-02 16:33:27 +00004025 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004026 Msg = "SCoP ends here but was dismissed.";
Johannes Doerfert43788c52015-08-20 05:58:56 +00004027 delete scop;
4028 scop = nullptr;
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004029 } else {
4030 Msg = "SCoP ends here.";
4031 ++ScopFound;
4032 if (scop->getMaxLoopDepth() > 0)
4033 ++RichScopFound;
Johannes Doerfert43788c52015-08-20 05:58:56 +00004034 }
4035
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004036 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg);
4037
Tobias Grosser75805372011-04-29 06:27:02 +00004038 return false;
4039}
4040
4041char ScopInfo::ID = 0;
4042
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004043Pass *polly::createScopInfoPass() { return new ScopInfo(); }
4044
Tobias Grosser73600b82011-10-08 00:30:40 +00004045INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
4046 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004047 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004048INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004049INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004050INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004051INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004052INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004053INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004054INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00004055INITIALIZE_PASS_END(ScopInfo, "polly-scops",
4056 "Polly - Create polyhedral description of Scops", false,
4057 false)