blob: a3f6f3a54c9cc060e352995fd40a7c92654683fa [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(),
Tobias Grossera535dff2015-12-13 19:59:01 +0000169 ScopArrayInfo::MK_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 Grossera535dff2015-12-13 19:59:01 +0000173 ArrayRef<const SCEV *> Sizes, enum MemoryKind 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 Grossera535dff2015-12-13 19:59:01 +0000177 getIslCompatibleName("MemRef_", BasePtr, Kind == MK_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()))
Tobias Grosser8d4f6262015-12-12 09:52:26 +0000677 S.invalidate(ALIGNMENT, AccessInstruction->getDebugLoc());
Sebastian Pop18016682014-04-08 21:20:44 +0000678 }
679
680 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
681
Tobias Grosser79baa212014-04-10 08:38:02 +0000682 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000683 }
684
Michael Krusee2bccbb2015-09-18 19:59:43 +0000685 if (Sizes.size() > 1 && !isa<SCEVConstant>(Sizes[0]))
686 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000687
Tobias Grosser79baa212014-04-10 08:38:02 +0000688 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000689 AccessRelation = isl_map_set_tuple_id(
690 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000691 AccessRelation =
692 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
693
Michael Krusee2bccbb2015-09-18 19:59:43 +0000694 assumeNoOutOfBound();
Tobias Grosseraa660a92015-03-30 00:07:50 +0000695 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000696 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000697}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000698
Michael Krusecac948e2015-10-02 13:53:07 +0000699MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000700 AccessType Type, Value *BaseAddress,
701 unsigned ElemBytes, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000702 ArrayRef<const SCEV *> Subscripts,
703 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000704 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
705 : Kind(Kind), AccType(Type), RedType(RT_NONE), Statement(Stmt),
Michael Krusecac948e2015-10-02 13:53:07 +0000706 BaseAddr(BaseAddress), BaseName(BaseName), ElemBytes(ElemBytes),
707 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
708 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000709 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000710 NewAccessRelation(nullptr) {
711
712 std::string IdName = "__polly_array_ref";
713 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
714}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000715
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000716void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000717 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000718 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000719}
720
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000721const std::string MemoryAccess::getReductionOperatorStr() const {
722 return MemoryAccess::getReductionOperatorStr(getReductionType());
723}
724
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000725__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
726
Johannes Doerfertf6183392014-07-01 20:52:51 +0000727raw_ostream &polly::operator<<(raw_ostream &OS,
728 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000729 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000730 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000731 else
732 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000733 return OS;
734}
735
Tobias Grosser75805372011-04-29 06:27:02 +0000736void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000737 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000738 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000739 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000740 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000741 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000742 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000743 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000744 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000745 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000746 break;
747 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000748 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000749 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000750 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000751 if (hasNewAccessRelation())
752 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000753}
754
Tobias Grosser74394f02013-01-14 22:40:23 +0000755void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000756
757// Create a map in the size of the provided set domain, that maps from the
758// one element of the provided set domain to another element of the provided
759// set domain.
760// The mapping is limited to all points that are equal in all but the last
761// dimension and for which the last dimension of the input is strict smaller
762// than the last dimension of the output.
763//
764// getEqualAndLarger(set[i0, i1, ..., iX]):
765//
766// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
767// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
768//
Tobias Grosserf5338802011-10-06 00:03:35 +0000769static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000770 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000771 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000772 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000773
774 // Set all but the last dimension to be equal for the input and output
775 //
776 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
777 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000778 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000779 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000780
781 // Set the last dimension of the input to be strict smaller than the
782 // last dimension of the output.
783 //
784 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000785 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
786 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000787 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000788}
789
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000790__isl_give isl_set *
791MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000792 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000793 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000794 isl_space *Space = isl_space_range(isl_map_get_space(S));
795 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000796
Sebastian Popa00a0292012-12-18 07:46:06 +0000797 S = isl_map_reverse(S);
798 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000799
Sebastian Popa00a0292012-12-18 07:46:06 +0000800 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
801 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
802 NextScatt = isl_map_apply_domain(NextScatt, S);
803 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000804
Sebastian Popa00a0292012-12-18 07:46:06 +0000805 isl_set *Deltas = isl_map_deltas(NextScatt);
806 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000807}
808
Sebastian Popa00a0292012-12-18 07:46:06 +0000809bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000810 int StrideWidth) const {
811 isl_set *Stride, *StrideX;
812 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000813
Sebastian Popa00a0292012-12-18 07:46:06 +0000814 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000815 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000816 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
817 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
818 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
819 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000820 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000821
Tobias Grosser28dd4862012-01-24 16:42:16 +0000822 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000823 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000824
Tobias Grosser28dd4862012-01-24 16:42:16 +0000825 return IsStrideX;
826}
827
Sebastian Popa00a0292012-12-18 07:46:06 +0000828bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
829 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000830}
831
Sebastian Popa00a0292012-12-18 07:46:06 +0000832bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
833 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000834}
835
Tobias Grosser166c4222015-09-05 07:46:40 +0000836void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
837 isl_map_free(NewAccessRelation);
838 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000839}
Tobias Grosser75805372011-04-29 06:27:02 +0000840
841//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000842
Tobias Grosser808cd692015-07-14 09:33:13 +0000843isl_map *ScopStmt::getSchedule() const {
844 isl_set *Domain = getDomain();
845 if (isl_set_is_empty(Domain)) {
846 isl_set_free(Domain);
847 return isl_map_from_aff(
848 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
849 }
850 auto *Schedule = getParent()->getSchedule();
851 Schedule = isl_union_map_intersect_domain(
852 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
853 if (isl_union_map_is_empty(Schedule)) {
854 isl_set_free(Domain);
855 isl_union_map_free(Schedule);
856 return isl_map_from_aff(
857 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
858 }
859 auto *M = isl_map_from_union_map(Schedule);
860 M = isl_map_coalesce(M);
861 M = isl_map_gist_domain(M, Domain);
862 M = isl_map_coalesce(M);
863 return M;
864}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000865
Johannes Doerfert574182d2015-08-12 10:19:50 +0000866__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000867 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
868 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000869}
870
Tobias Grosser37eb4222014-02-20 21:43:54 +0000871void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
872 assert(isl_set_is_subset(NewDomain, Domain) &&
873 "New domain is not a subset of old domain!");
874 isl_set_free(Domain);
875 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000876}
877
Michael Krusecac948e2015-10-02 13:53:07 +0000878void ScopStmt::buildAccessRelations() {
879 for (MemoryAccess *Access : MemAccs) {
880 Type *ElementType = Access->getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000881
Tobias Grossera535dff2015-12-13 19:59:01 +0000882 ScopArrayInfo::MemoryKind Ty;
883 if (Access->isPHIKind())
884 Ty = ScopArrayInfo::MK_PHI;
885 else if (Access->isExitPHIKind())
886 Ty = ScopArrayInfo::MK_ExitPHI;
887 else if (Access->isValueKind())
888 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000889 else
Tobias Grossera535dff2015-12-13 19:59:01 +0000890 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000891
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000892 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000893 Access->getBaseAddr(), ElementType, Access->Sizes, Ty);
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000894
Michael Krusecac948e2015-10-02 13:53:07 +0000895 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +0000896 }
897}
898
Michael Krusecac948e2015-10-02 13:53:07 +0000899void ScopStmt::addAccess(MemoryAccess *Access) {
900 Instruction *AccessInst = Access->getAccessInstruction();
901
902 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
903 if (!MAL)
904 MAL = new MemoryAccessList();
905 MAL->emplace_front(Access);
906 MemAccs.push_back(MAL->front());
907}
908
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000909void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000910 for (MemoryAccess *MA : *this)
911 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000912
913 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000914}
915
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000916/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
917static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
918 void *User) {
919 isl_set **BoundedParts = static_cast<isl_set **>(User);
920 if (isl_basic_set_is_bounded(BSet))
921 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
922 else
923 isl_basic_set_free(BSet);
924 return isl_stat_ok;
925}
926
927/// @brief Return the bounded parts of @p S.
928static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
929 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
930 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
931 isl_set_free(S);
932 return BoundedParts;
933}
934
935/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
936///
937/// @returns A separation of @p S into first an unbounded then a bounded subset,
938/// both with regards to the dimension @p Dim.
939static std::pair<__isl_give isl_set *, __isl_give isl_set *>
940partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
941
942 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000943 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000944
945 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000946 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000947
948 // Remove dimensions that are greater than Dim as they are not interesting.
949 assert(NumDimsS >= Dim + 1);
950 OnlyDimS =
951 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
952
953 // Create artificial parametric upper bounds for dimensions smaller than Dim
954 // as we are not interested in them.
955 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
956 for (unsigned u = 0; u < Dim; u++) {
957 isl_constraint *C = isl_inequality_alloc(
958 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
959 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
960 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
961 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
962 }
963
964 // Collect all bounded parts of OnlyDimS.
965 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
966
967 // Create the dimensions greater than Dim again.
968 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
969 NumDimsS - Dim - 1);
970
971 // Remove the artificial upper bound parameters again.
972 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
973
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000974 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000975 return std::make_pair(UnboundedParts, BoundedParts);
976}
977
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000978/// @brief Set the dimension Ids from @p From in @p To.
979static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
980 __isl_take isl_set *To) {
981 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
982 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
983 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
984 }
985 return To;
986}
987
988/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000989static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000990 __isl_take isl_pw_aff *L,
991 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +0000992 switch (Pred) {
993 case ICmpInst::ICMP_EQ:
994 return isl_pw_aff_eq_set(L, R);
995 case ICmpInst::ICMP_NE:
996 return isl_pw_aff_ne_set(L, R);
997 case ICmpInst::ICMP_SLT:
998 return isl_pw_aff_lt_set(L, R);
999 case ICmpInst::ICMP_SLE:
1000 return isl_pw_aff_le_set(L, R);
1001 case ICmpInst::ICMP_SGT:
1002 return isl_pw_aff_gt_set(L, R);
1003 case ICmpInst::ICMP_SGE:
1004 return isl_pw_aff_ge_set(L, R);
1005 case ICmpInst::ICMP_ULT:
1006 return isl_pw_aff_lt_set(L, R);
1007 case ICmpInst::ICMP_UGT:
1008 return isl_pw_aff_gt_set(L, R);
1009 case ICmpInst::ICMP_ULE:
1010 return isl_pw_aff_le_set(L, R);
1011 case ICmpInst::ICMP_UGE:
1012 return isl_pw_aff_ge_set(L, R);
1013 default:
1014 llvm_unreachable("Non integer predicate not supported");
1015 }
1016}
1017
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001018/// @brief Create the conditions under which @p L @p Pred @p R is true.
1019///
1020/// Helper function that will make sure the dimensions of the result have the
1021/// same isl_id's as the @p Domain.
1022static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1023 __isl_take isl_pw_aff *L,
1024 __isl_take isl_pw_aff *R,
1025 __isl_keep isl_set *Domain) {
1026 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1027 return setDimensionIds(Domain, ConsequenceCondSet);
1028}
1029
1030/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001031///
1032/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001033/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1034/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001035static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001036buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001037 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1038
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001039 Value *Condition = getConditionFromTerminator(SI);
1040 assert(Condition && "No condition for switch");
1041
1042 ScalarEvolution &SE = *S.getSE();
1043 BasicBlock *BB = SI->getParent();
1044 isl_pw_aff *LHS, *RHS;
1045 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
1046
1047 unsigned NumSuccessors = SI->getNumSuccessors();
1048 ConditionSets.resize(NumSuccessors);
1049 for (auto &Case : SI->cases()) {
1050 unsigned Idx = Case.getSuccessorIndex();
1051 ConstantInt *CaseValue = Case.getCaseValue();
1052
1053 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
1054 isl_set *CaseConditionSet =
1055 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1056 ConditionSets[Idx] = isl_set_coalesce(
1057 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1058 }
1059
1060 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1061 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1062 for (unsigned u = 2; u < NumSuccessors; u++)
1063 ConditionSetUnion =
1064 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1065 ConditionSets[0] = setDimensionIds(
1066 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1067
1068 S.markAsOptimized();
1069 isl_pw_aff_free(LHS);
1070}
1071
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001072/// @brief Build the conditions sets for the branch condition @p Condition in
1073/// the @p Domain.
1074///
1075/// This will fill @p ConditionSets with the conditions under which control
1076/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001077/// have as many elements as @p TI has successors. If @p TI is nullptr the
1078/// context under which @p Condition is true/false will be returned as the
1079/// new elements of @p ConditionSets.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001080static void
1081buildConditionSets(Scop &S, Value *Condition, TerminatorInst *TI, Loop *L,
1082 __isl_keep isl_set *Domain,
1083 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1084
1085 isl_set *ConsequenceCondSet = nullptr;
1086 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1087 if (CCond->isZero())
1088 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1089 else
1090 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1091 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1092 auto Opcode = BinOp->getOpcode();
1093 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1094
1095 buildConditionSets(S, BinOp->getOperand(0), TI, L, Domain, ConditionSets);
1096 buildConditionSets(S, BinOp->getOperand(1), TI, L, Domain, ConditionSets);
1097
1098 isl_set_free(ConditionSets.pop_back_val());
1099 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1100 isl_set_free(ConditionSets.pop_back_val());
1101 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1102
1103 if (Opcode == Instruction::And)
1104 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1105 else
1106 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1107 } else {
1108 auto *ICond = dyn_cast<ICmpInst>(Condition);
1109 assert(ICond &&
1110 "Condition of exiting branch was neither constant nor ICmp!");
1111
1112 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001113 BasicBlock *BB = TI ? TI->getParent() : nullptr;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001114 isl_pw_aff *LHS, *RHS;
1115 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1116 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
1117 ConsequenceCondSet =
1118 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1119 }
1120
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001121 // If no terminator was given we are only looking for parameter constraints
1122 // under which @p Condition is true/false.
1123 if (!TI)
1124 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
1125
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001126 assert(ConsequenceCondSet);
1127 isl_set *AlternativeCondSet =
1128 isl_set_complement(isl_set_copy(ConsequenceCondSet));
1129
1130 ConditionSets.push_back(isl_set_coalesce(
1131 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
1132 ConditionSets.push_back(isl_set_coalesce(
1133 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
1134}
1135
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001136/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1137///
1138/// This will fill @p ConditionSets with the conditions under which control
1139/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1140/// have as many elements as @p TI has successors.
1141static void
1142buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1143 __isl_keep isl_set *Domain,
1144 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1145
1146 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1147 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1148
1149 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1150
1151 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001152 ConditionSets.push_back(isl_set_copy(Domain));
1153 return;
1154 }
1155
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001156 Value *Condition = getConditionFromTerminator(TI);
1157 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001158
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001159 return buildConditionSets(S, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001160}
1161
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001162void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +00001163 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +00001164
Tobias Grosser084d8f72012-05-29 09:29:44 +00001165 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1166
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001167 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001168 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001169}
1170
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001171void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001172 isl_ctx *Ctx = Parent.getIslCtx();
1173 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1174 Type *Ty = GEP->getPointerOperandType();
1175 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001176 ScopDetection &SD = Parent.getSD();
1177
1178 // The set of loads that are required to be invariant.
1179 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001180
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001181 std::vector<const SCEV *> Subscripts;
1182 std::vector<int> Sizes;
1183
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001184 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001185
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001186 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001187 Ty = PtrTy->getElementType();
1188 }
1189
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001190 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001191
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001192 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001193
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001194 for (size_t i = 0; i < Sizes.size(); i++) {
1195 auto Expr = Subscripts[i + IndexOffset];
1196 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001197
Johannes Doerfert09e36972015-10-07 20:17:36 +00001198 InvariantLoadsSetTy AccessILS;
1199 if (!isAffineExpr(&Parent.getRegion(), Expr, SE, nullptr, &AccessILS))
1200 continue;
1201
1202 bool NonAffine = false;
1203 for (LoadInst *LInst : AccessILS)
1204 if (!ScopRIL.count(LInst))
1205 NonAffine = true;
1206
1207 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001208 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001209
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001210 isl_pw_aff *AccessOffset = getPwAff(Expr);
1211 AccessOffset =
1212 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001213
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001214 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1215 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001216
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001217 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1218 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1219 OutOfBound = isl_set_params(OutOfBound);
1220 isl_set *InBound = isl_set_complement(OutOfBound);
1221 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001222
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001223 // A => B == !A or B
1224 isl_set *InBoundIfExecuted =
1225 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001226
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001227 Parent.addAssumption(INBOUNDS, InBoundIfExecuted, GEP->getDebugLoc());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001228 }
1229
1230 isl_local_space_free(LSpace);
1231}
1232
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001233void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1234 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001235 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1236 deriveAssumptionsFromGEP(GEP);
1237}
1238
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001239void ScopStmt::collectSurroundingLoops() {
1240 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1241 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1242 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1243 isl_id_free(DimId);
1244 }
1245}
1246
Michael Kruse9d080092015-09-11 21:41:48 +00001247ScopStmt::ScopStmt(Scop &parent, Region &R)
Michael Krusecac948e2015-10-02 13:53:07 +00001248 : Parent(parent), Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001249
Tobias Grosser16c44032015-07-09 07:31:45 +00001250 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001251}
1252
Michael Kruse9d080092015-09-11 21:41:48 +00001253ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Michael Krusecac948e2015-10-02 13:53:07 +00001254 : Parent(parent), Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001255
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001256 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001257}
1258
1259void ScopStmt::init() {
1260 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001261
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001262 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001263 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001264 buildAccessRelations();
1265
1266 if (BB) {
1267 deriveAssumptions(BB);
1268 } else {
1269 for (BasicBlock *Block : R->blocks()) {
1270 deriveAssumptions(Block);
1271 }
1272 }
1273
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001274 if (DetectReductions)
1275 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001276}
1277
Johannes Doerferte58a0122014-06-27 20:31:28 +00001278/// @brief Collect loads which might form a reduction chain with @p StoreMA
1279///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001280/// Check if the stored value for @p StoreMA is a binary operator with one or
1281/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001282/// used only once (by @p StoreMA) and its load operands are also used only
1283/// once, we have found a possible reduction chain. It starts at an operand
1284/// load and includes the binary operator and @p StoreMA.
1285///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001286/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001287/// escape this block or into any other store except @p StoreMA.
1288void ScopStmt::collectCandiateReductionLoads(
1289 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1290 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1291 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001292 return;
1293
1294 // Skip if there is not one binary operator between the load and the store
1295 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001296 if (!BinOp)
1297 return;
1298
1299 // Skip if the binary operators has multiple uses
1300 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001301 return;
1302
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001303 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001304 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1305 return;
1306
Johannes Doerfert9890a052014-07-01 00:32:29 +00001307 // Skip if the binary operator is outside the current SCoP
1308 if (BinOp->getParent() != Store->getParent())
1309 return;
1310
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001311 // Skip if it is a multiplicative reduction and we disabled them
1312 if (DisableMultiplicativeReductions &&
1313 (BinOp->getOpcode() == Instruction::Mul ||
1314 BinOp->getOpcode() == Instruction::FMul))
1315 return;
1316
Johannes Doerferte58a0122014-06-27 20:31:28 +00001317 // Check the binary operator operands for a candidate load
1318 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1319 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1320 if (!PossibleLoad0 && !PossibleLoad1)
1321 return;
1322
1323 // A load is only a candidate if it cannot escape (thus has only this use)
1324 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001325 if (PossibleLoad0->getParent() == Store->getParent())
1326 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001327 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001328 if (PossibleLoad1->getParent() == Store->getParent())
1329 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001330}
1331
1332/// @brief Check for reductions in this ScopStmt
1333///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001334/// Iterate over all store memory accesses and check for valid binary reduction
1335/// like chains. For all candidates we check if they have the same base address
1336/// and there are no other accesses which overlap with them. The base address
1337/// check rules out impossible reductions candidates early. The overlap check,
1338/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001339/// guarantees that none of the intermediate results will escape during
1340/// execution of the loop nest. We basically check here that no other memory
1341/// access can access the same memory as the potential reduction.
1342void ScopStmt::checkForReductions() {
1343 SmallVector<MemoryAccess *, 2> Loads;
1344 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1345
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001346 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001347 // stores and collecting possible reduction loads.
1348 for (MemoryAccess *StoreMA : MemAccs) {
1349 if (StoreMA->isRead())
1350 continue;
1351
1352 Loads.clear();
1353 collectCandiateReductionLoads(StoreMA, Loads);
1354 for (MemoryAccess *LoadMA : Loads)
1355 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1356 }
1357
1358 // Then check each possible candidate pair.
1359 for (const auto &CandidatePair : Candidates) {
1360 bool Valid = true;
1361 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1362 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1363
1364 // Skip those with obviously unequal base addresses.
1365 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1366 isl_map_free(LoadAccs);
1367 isl_map_free(StoreAccs);
1368 continue;
1369 }
1370
1371 // And check if the remaining for overlap with other memory accesses.
1372 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1373 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1374 isl_set *AllAccs = isl_map_range(AllAccsRel);
1375
1376 for (MemoryAccess *MA : MemAccs) {
1377 if (MA == CandidatePair.first || MA == CandidatePair.second)
1378 continue;
1379
1380 isl_map *AccRel =
1381 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1382 isl_set *Accs = isl_map_range(AccRel);
1383
1384 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1385 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1386 Valid = Valid && isl_set_is_empty(OverlapAccs);
1387 isl_set_free(OverlapAccs);
1388 }
1389 }
1390
1391 isl_set_free(AllAccs);
1392 if (!Valid)
1393 continue;
1394
Johannes Doerfertf6183392014-07-01 20:52:51 +00001395 const LoadInst *Load =
1396 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1397 MemoryAccess::ReductionType RT =
1398 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1399
Johannes Doerferte58a0122014-06-27 20:31:28 +00001400 // If no overlapping access was found we mark the load and store as
1401 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001402 CandidatePair.first->markAsReductionLike(RT);
1403 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001404 }
Tobias Grosser75805372011-04-29 06:27:02 +00001405}
1406
Tobias Grosser74394f02013-01-14 22:40:23 +00001407std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001408
Tobias Grosser54839312015-04-21 11:37:25 +00001409std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001410 auto *S = getSchedule();
1411 auto Str = stringFromIslObj(S);
1412 isl_map_free(S);
1413 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001414}
1415
Tobias Grosser74394f02013-01-14 22:40:23 +00001416unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001417
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001418unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001419
Tobias Grosser75805372011-04-29 06:27:02 +00001420const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1421
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001422const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001423 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001424}
1425
Tobias Grosser74394f02013-01-14 22:40:23 +00001426isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001427
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001428__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001429
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001430__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001431 return isl_set_get_space(Domain);
1432}
1433
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001434__isl_give isl_id *ScopStmt::getDomainId() const {
1435 return isl_set_get_tuple_id(Domain);
1436}
Tobias Grossercd95b772012-08-30 11:49:38 +00001437
Tobias Grosser75805372011-04-29 06:27:02 +00001438ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001439 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001440 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001441}
1442
1443void ScopStmt::print(raw_ostream &OS) const {
1444 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001445 OS.indent(12) << "Domain :=\n";
1446
1447 if (Domain) {
1448 OS.indent(16) << getDomainStr() << ";\n";
1449 } else
1450 OS.indent(16) << "n/a\n";
1451
Tobias Grosser54839312015-04-21 11:37:25 +00001452 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001453
1454 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001455 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001456 } else
1457 OS.indent(16) << "n/a\n";
1458
Tobias Grosser083d3d32014-06-28 08:59:45 +00001459 for (MemoryAccess *Access : MemAccs)
1460 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001461}
1462
1463void ScopStmt::dump() const { print(dbgs()); }
1464
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001465void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001466 // Remove all memory accesses in @p InvMAs from this statement
1467 // together with all scalar accesses that were caused by them.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001468 for (MemoryAccess *MA : InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001469 auto Predicate = [&](MemoryAccess *Acc) {
Tobias Grosser3a6ac9f2015-11-30 21:13:43 +00001470 return Acc->getAccessInstruction() == MA->getAccessInstruction();
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001471 };
1472 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1473 MemAccs.end());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001474 InstructionToAccess.erase(MA->getAccessInstruction());
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001475 delete lookupAccessesFor(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001476 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001477}
1478
Tobias Grosser75805372011-04-29 06:27:02 +00001479//===----------------------------------------------------------------------===//
1480/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001481
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001482void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001483 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1484 isl_set_free(Context);
1485 Context = NewContext;
1486}
1487
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001488/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1489struct SCEVSensitiveParameterRewriter
1490 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1491 ValueToValueMap &VMap;
1492 ScalarEvolution &SE;
1493
1494public:
1495 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1496 : VMap(VMap), SE(SE) {}
1497
1498 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1499 ValueToValueMap &VMap) {
1500 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1501 return SSPR.visit(E);
1502 }
1503
1504 const SCEV *visit(const SCEV *E) {
1505 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1506 }
1507
1508 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1509
1510 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1511 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1512 }
1513
1514 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1515 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1516 }
1517
1518 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1519 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1520 }
1521
1522 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1523 SmallVector<const SCEV *, 4> Operands;
1524 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1525 Operands.push_back(visit(E->getOperand(i)));
1526 return SE.getAddExpr(Operands);
1527 }
1528
1529 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1530 SmallVector<const SCEV *, 4> Operands;
1531 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1532 Operands.push_back(visit(E->getOperand(i)));
1533 return SE.getMulExpr(Operands);
1534 }
1535
1536 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1537 SmallVector<const SCEV *, 4> Operands;
1538 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1539 Operands.push_back(visit(E->getOperand(i)));
1540 return SE.getSMaxExpr(Operands);
1541 }
1542
1543 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1544 SmallVector<const SCEV *, 4> Operands;
1545 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1546 Operands.push_back(visit(E->getOperand(i)));
1547 return SE.getUMaxExpr(Operands);
1548 }
1549
1550 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1551 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1552 }
1553
1554 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1555 auto *Start = visit(E->getStart());
1556 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1557 visit(E->getStepRecurrence(SE)),
1558 E->getLoop(), SCEV::FlagAnyWrap);
1559 return SE.getAddExpr(Start, AddRec);
1560 }
1561
1562 const SCEV *visitUnknown(const SCEVUnknown *E) {
1563 if (auto *NewValue = VMap.lookup(E->getValue()))
1564 return SE.getUnknown(NewValue);
1565 return E;
1566 }
1567};
1568
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001569const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001570 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001571}
1572
Tobias Grosserabfbe632013-02-05 12:09:06 +00001573void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001574 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001575 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001576
1577 // Normalize the SCEV to get the representing element for an invariant load.
1578 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1579
Tobias Grosser60b54f12011-11-08 15:41:28 +00001580 if (ParameterIds.find(Parameter) != ParameterIds.end())
1581 continue;
1582
1583 int dimension = Parameters.size();
1584
1585 Parameters.push_back(Parameter);
1586 ParameterIds[Parameter] = dimension;
1587 }
1588}
1589
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001590__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001591 // Normalize the SCEV to get the representing element for an invariant load.
1592 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1593
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001594 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001595
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001596 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001597 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001598
Tobias Grosser8f99c162011-11-15 11:38:55 +00001599 std::string ParameterName;
1600
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001601 ParameterName = "p_" + utostr_32(IdIter->second);
1602
Tobias Grosser8f99c162011-11-15 11:38:55 +00001603 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1604 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001605
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001606 // If this parameter references a specific Value and this value has a name
1607 // we use this name as it is likely to be unique and more useful than just
1608 // a number.
1609 if (Val->hasName())
1610 ParameterName = Val->getName();
1611 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
1612 auto LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
1613 if (LoadOrigin->hasName()) {
1614 ParameterName += "_loaded_from_";
1615 ParameterName +=
1616 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1617 }
1618 }
1619 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001620
Tobias Grosser20532b82014-04-11 17:56:49 +00001621 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1622 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001623}
Tobias Grosser75805372011-04-29 06:27:02 +00001624
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001625isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1626 isl_set *DomainContext = isl_union_set_params(getDomains());
1627 return isl_set_intersect_params(C, DomainContext);
1628}
1629
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001630void Scop::buildBoundaryContext() {
Tobias Grosser4927c8e2015-11-24 12:50:02 +00001631 if (IgnoreIntegerWrapping) {
1632 BoundaryContext = isl_set_universe(getParamSpace());
1633 return;
1634 }
1635
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001636 BoundaryContext = Affinator.getWrappingContext();
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001637
1638 // The isl_set_complement operation used to create the boundary context
1639 // can possibly become very expensive. We bound the compile time of
1640 // this operation by setting a compute out.
1641 //
1642 // TODO: We can probably get around using isl_set_complement and directly
1643 // AST generate BoundaryContext.
1644 long MaxOpsOld = isl_ctx_get_max_operations(getIslCtx());
Tobias Grosserf920fb12015-11-13 16:56:13 +00001645 isl_ctx_reset_operations(getIslCtx());
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001646 isl_ctx_set_max_operations(getIslCtx(), 300000);
1647 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_CONTINUE);
1648
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001649 BoundaryContext = isl_set_complement(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001650
Tobias Grossera52b4da2015-11-11 17:59:53 +00001651 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
1652 isl_set_free(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001653 BoundaryContext = isl_set_empty(getParamSpace());
Tobias Grossera52b4da2015-11-11 17:59:53 +00001654 }
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001655
1656 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
1657 isl_ctx_reset_operations(getIslCtx());
1658 isl_ctx_set_max_operations(getIslCtx(), MaxOpsOld);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001659 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001660 trackAssumption(WRAPPING, BoundaryContext, DebugLoc());
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001661}
1662
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001663void Scop::addUserAssumptions(AssumptionCache &AC) {
1664 auto *R = &getRegion();
1665 auto &F = *R->getEntry()->getParent();
1666 for (auto &Assumption : AC.assumptions()) {
1667 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1668 if (!CI || CI->getNumArgOperands() != 1)
1669 continue;
1670 if (!DT.dominates(CI->getParent(), R->getEntry()))
1671 continue;
1672
1673 auto *Val = CI->getArgOperand(0);
1674 std::vector<const SCEV *> Params;
1675 if (!isAffineParamConstraint(Val, R, *SE, Params)) {
1676 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1677 CI->getDebugLoc(),
1678 "Non-affine user assumption ignored.");
1679 continue;
1680 }
1681
1682 addParams(Params);
1683
1684 auto *L = LI.getLoopFor(CI->getParent());
1685 SmallVector<isl_set *, 2> ConditionSets;
1686 buildConditionSets(*this, Val, nullptr, L, Context, ConditionSets);
1687 assert(ConditionSets.size() == 2);
1688 isl_set_free(ConditionSets[1]);
1689
1690 auto *AssumptionCtx = ConditionSets[0];
1691 emitOptimizationRemarkAnalysis(
1692 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1693 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1694 Context = isl_set_intersect(Context, AssumptionCtx);
1695 }
1696}
1697
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001698void Scop::addUserContext() {
1699 if (UserContextStr.empty())
1700 return;
1701
1702 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1703 isl_space *Space = getParamSpace();
1704 if (isl_space_dim(Space, isl_dim_param) !=
1705 isl_set_dim(UserContext, isl_dim_param)) {
1706 auto SpaceStr = isl_space_to_str(Space);
1707 errs() << "Error: the context provided in -polly-context has not the same "
1708 << "number of dimensions than the computed context. Due to this "
1709 << "mismatch, the -polly-context option is ignored. Please provide "
1710 << "the context in the parameter space: " << SpaceStr << ".\n";
1711 free(SpaceStr);
1712 isl_set_free(UserContext);
1713 isl_space_free(Space);
1714 return;
1715 }
1716
1717 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1718 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1719 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1720
1721 if (strcmp(NameContext, NameUserContext) != 0) {
1722 auto SpaceStr = isl_space_to_str(Space);
1723 errs() << "Error: the name of dimension " << i
1724 << " provided in -polly-context "
1725 << "is '" << NameUserContext << "', but the name in the computed "
1726 << "context is '" << NameContext
1727 << "'. Due to this name mismatch, "
1728 << "the -polly-context option is ignored. Please provide "
1729 << "the context in the parameter space: " << SpaceStr << ".\n";
1730 free(SpaceStr);
1731 isl_set_free(UserContext);
1732 isl_space_free(Space);
1733 return;
1734 }
1735
1736 UserContext =
1737 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1738 isl_space_get_dim_id(Space, isl_dim_param, i));
1739 }
1740
1741 Context = isl_set_intersect(Context, UserContext);
1742 isl_space_free(Space);
1743}
1744
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001745void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001746 DenseMap<const SCEV *, LoadInst *> EquivClasses;
1747
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001748 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001749 for (LoadInst *LInst : RIL) {
1750 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1751
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001752 LoadInst *&ClassRep = EquivClasses[PointerSCEV];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001753 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001754 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001755 continue;
1756 }
1757
1758 ClassRep = LInst;
1759 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(),
1760 nullptr);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001761 }
1762}
1763
Tobias Grosser6be480c2011-11-08 15:41:13 +00001764void Scop::buildContext() {
1765 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001766 Context = isl_set_universe(isl_space_copy(Space));
1767 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001768}
1769
Tobias Grosser18daaca2012-05-22 10:47:27 +00001770void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001771 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001772 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001773
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001774 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001775
Johannes Doerferte7044942015-02-24 11:58:30 +00001776 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001777 }
1778}
1779
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001780void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001781 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001782 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001783
Tobias Grosser083d3d32014-06-28 08:59:45 +00001784 for (const auto &ParamID : ParameterIds) {
1785 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001786 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001787 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001788 }
1789
1790 // Align the parameters of all data structures to the model.
1791 Context = isl_set_align_params(Context, Space);
1792
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001793 for (ScopStmt &Stmt : *this)
1794 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001795}
1796
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001797static __isl_give isl_set *
1798simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1799 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001800 // If we modelt all blocks in the SCoP that have side effects we can simplify
1801 // the context with the constraints that are needed for anything to be
1802 // executed at all. However, if we have error blocks in the SCoP we already
1803 // assumed some parameter combinations cannot occure and removed them from the
1804 // domains, thus we cannot use the remaining domain to simplify the
1805 // assumptions.
1806 if (!S.hasErrorBlock()) {
1807 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1808 AssumptionContext =
1809 isl_set_gist_params(AssumptionContext, DomainParameters);
1810 }
1811
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001812 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1813 return AssumptionContext;
1814}
1815
1816void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001817 // The parameter constraints of the iteration domains give us a set of
1818 // constraints that need to hold for all cases where at least a single
1819 // statement iteration is executed in the whole scop. We now simplify the
1820 // assumed context under the assumption that such constraints hold and at
1821 // least a single statement iteration is executed. For cases where no
1822 // statement instances are executed, the assumptions we have taken about
1823 // the executed code do not matter and can be changed.
1824 //
1825 // WARNING: This only holds if the assumptions we have taken do not reduce
1826 // the set of statement instances that are executed. Otherwise we
1827 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001828 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001829 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001830 // performed. In such a case, modifying the run-time conditions and
1831 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001832 // to not be executed.
1833 //
1834 // Example:
1835 //
1836 // When delinearizing the following code:
1837 //
1838 // for (long i = 0; i < 100; i++)
1839 // for (long j = 0; j < m; j++)
1840 // A[i+p][j] = 1.0;
1841 //
1842 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001843 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001844 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001845 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1846 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001847}
1848
Johannes Doerfertb164c792014-09-18 11:17:17 +00001849/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001850static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001851 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1852 isl_pw_multi_aff *MinPMA, *MaxPMA;
1853 isl_pw_aff *LastDimAff;
1854 isl_aff *OneAff;
1855 unsigned Pos;
1856
Johannes Doerfert9143d672014-09-27 11:02:39 +00001857 // Restrict the number of parameters involved in the access as the lexmin/
1858 // lexmax computation will take too long if this number is high.
1859 //
1860 // Experiments with a simple test case using an i7 4800MQ:
1861 //
1862 // #Parameters involved | Time (in sec)
1863 // 6 | 0.01
1864 // 7 | 0.04
1865 // 8 | 0.12
1866 // 9 | 0.40
1867 // 10 | 1.54
1868 // 11 | 6.78
1869 // 12 | 30.38
1870 //
1871 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1872 unsigned InvolvedParams = 0;
1873 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1874 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1875 InvolvedParams++;
1876
1877 if (InvolvedParams > RunTimeChecksMaxParameters) {
1878 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001879 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001880 }
1881 }
1882
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001883 Set = isl_set_remove_divs(Set);
1884
Johannes Doerfertb164c792014-09-18 11:17:17 +00001885 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1886 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1887
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001888 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1889 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1890
Johannes Doerfertb164c792014-09-18 11:17:17 +00001891 // Adjust the last dimension of the maximal access by one as we want to
1892 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1893 // we test during code generation might now point after the end of the
1894 // allocated array but we will never dereference it anyway.
1895 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1896 "Assumed at least one output dimension");
1897 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1898 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1899 OneAff = isl_aff_zero_on_domain(
1900 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1901 OneAff = isl_aff_add_constant_si(OneAff, 1);
1902 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1903 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1904
1905 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1906
1907 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001908 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001909}
1910
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001911static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1912 isl_set *Domain = MA->getStatement()->getDomain();
1913 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1914 return isl_set_reset_tuple_id(Domain);
1915}
1916
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001917/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1918static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001919 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001920 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001921
1922 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1923 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001924 Locations = isl_union_set_coalesce(Locations);
1925 Locations = isl_union_set_detect_equalities(Locations);
1926 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001927 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001928 isl_union_set_free(Locations);
1929 return Valid;
1930}
1931
Johannes Doerfert96425c22015-08-30 21:13:53 +00001932/// @brief Helper to treat non-affine regions and basic blocks the same.
1933///
1934///{
1935
1936/// @brief Return the block that is the representing block for @p RN.
1937static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1938 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1939 : RN->getNodeAs<BasicBlock>();
1940}
1941
1942/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001943static inline BasicBlock *
1944getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001945 if (RN->isSubRegion()) {
1946 assert(idx == 0);
1947 return RN->getNodeAs<Region>()->getExit();
1948 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001949 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001950}
1951
1952/// @brief Return the smallest loop surrounding @p RN.
1953static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1954 if (!RN->isSubRegion())
1955 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1956
1957 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1958 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1959 while (L && NonAffineSubRegion->contains(L))
1960 L = L->getParentLoop();
1961 return L;
1962}
1963
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001964static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1965 if (!RN->isSubRegion())
1966 return 1;
1967
1968 unsigned NumBlocks = 0;
1969 Region *R = RN->getNodeAs<Region>();
1970 for (auto BB : R->blocks()) {
1971 (void)BB;
1972 NumBlocks++;
1973 }
1974 return NumBlocks;
1975}
1976
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001977static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
1978 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00001979 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001980 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00001981 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001982 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00001983 return true;
1984 return false;
1985}
1986
Johannes Doerfert96425c22015-08-30 21:13:53 +00001987///}
1988
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001989static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1990 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001991 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001992 isl_id *DimId =
1993 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
1994 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
1995}
1996
Johannes Doerfert96425c22015-08-30 21:13:53 +00001997isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1998 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1999 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002000 return getDomainConditions(BB);
2001}
2002
2003isl_set *Scop::getDomainConditions(BasicBlock *BB) {
2004 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002005 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002006}
2007
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002008void Scop::removeErrorBlockDomains() {
2009 auto removeDomains = [this](BasicBlock *Start) {
2010 auto BBNode = DT.getNode(Start);
2011 for (auto ErrorChild : depth_first(BBNode)) {
2012 auto ErrorChildBlock = ErrorChild->getBlock();
2013 auto CurrentDomain = DomainMap[ErrorChildBlock];
2014 auto Empty = isl_set_empty(isl_set_get_space(CurrentDomain));
2015 DomainMap[ErrorChildBlock] = Empty;
2016 isl_set_free(CurrentDomain);
2017 }
2018 };
2019
Tobias Grosser5ef2bc32015-11-23 10:18:23 +00002020 SmallVector<Region *, 4> Todo = {&R};
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002021
2022 while (!Todo.empty()) {
2023 auto SubRegion = Todo.back();
2024 Todo.pop_back();
2025
2026 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
2027 for (auto &Child : *SubRegion)
2028 Todo.push_back(Child.get());
2029 continue;
2030 }
2031 if (containsErrorBlock(SubRegion->getNode(), getRegion(), LI, DT))
2032 removeDomains(SubRegion->getEntry());
2033 }
2034
2035 for (auto BB : R.blocks())
2036 if (isErrorBlock(*BB, R, LI, DT))
2037 removeDomains(BB);
2038}
2039
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002040void Scop::buildDomains(Region *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002041
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002042 auto *EntryBB = R->getEntry();
2043 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
2044 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002045
2046 Loop *L = LI.getLoopFor(EntryBB);
2047 while (LD-- >= 0) {
2048 S = addDomainDimId(S, LD + 1, L);
2049 L = L->getParentLoop();
2050 }
2051
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002052 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002053
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002054 if (SD.isNonAffineSubRegion(R, R))
2055 return;
2056
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002057 buildDomainsWithBranchConstraints(R);
2058 propagateDomainConstraints(R);
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002059
2060 // Error blocks and blocks dominated by them have been assumed to never be
2061 // executed. Representing them in the Scop does not add any value. In fact,
2062 // it is likely to cause issues during construction of the ScopStmts. The
2063 // contents of error blocks have not been verfied to be expressible and
2064 // will cause problems when building up a ScopStmt for them.
2065 // Furthermore, basic blocks dominated by error blocks may reference
2066 // instructions in the error block which, if the error block is not modeled,
2067 // can themselves not be constructed properly.
2068 removeErrorBlockDomains();
Johannes Doerfert96425c22015-08-30 21:13:53 +00002069}
2070
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002071void Scop::buildDomainsWithBranchConstraints(Region *R) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002072 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00002073
2074 // To create the domain for each block in R we iterate over all blocks and
2075 // subregions in R and propagate the conditions under which the current region
2076 // element is executed. To this end we iterate in reverse post order over R as
2077 // it ensures that we first visit all predecessors of a region node (either a
2078 // basic block or a subregion) before we visit the region node itself.
2079 // Initially, only the domain for the SCoP region entry block is set and from
2080 // there we propagate the current domain to all successors, however we add the
2081 // condition that the successor is actually executed next.
2082 // As we are only interested in non-loop carried constraints here we can
2083 // simply skip loop back edges.
2084
2085 ReversePostOrderTraversal<Region *> RTraversal(R);
2086 for (auto *RN : RTraversal) {
2087
2088 // Recurse for affine subregions but go on for basic blocks and non-affine
2089 // subregions.
2090 if (RN->isSubRegion()) {
2091 Region *SubRegion = RN->getNodeAs<Region>();
2092 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002093 buildDomainsWithBranchConstraints(SubRegion);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002094 continue;
2095 }
2096 }
2097
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002098 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002099 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002100
Johannes Doerfert96425c22015-08-30 21:13:53 +00002101 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002102 TerminatorInst *TI = BB->getTerminator();
2103
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002104 if (isa<UnreachableInst>(TI))
2105 continue;
2106
Johannes Doerfertf5673802015-10-01 23:48:18 +00002107 isl_set *Domain = DomainMap.lookup(BB);
2108 if (!Domain) {
2109 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2110 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002111 continue;
2112 }
2113
Johannes Doerfert96425c22015-08-30 21:13:53 +00002114 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002115
2116 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2117 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2118
2119 // Build the condition sets for the successor nodes of the current region
2120 // node. If it is a non-affine subregion we will always execute the single
2121 // exit node, hence the single entry node domain is the condition set. For
2122 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002123 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002124 if (RN->isSubRegion())
2125 ConditionSets.push_back(isl_set_copy(Domain));
2126 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002127 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002128
2129 // Now iterate over the successors and set their initial domain based on
2130 // their condition set. We skip back edges here and have to be careful when
2131 // we leave a loop not to keep constraints over a dimension that doesn't
2132 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002133 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002134 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002135 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002136 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002137
2138 // Skip back edges.
2139 if (DT.dominates(SuccBB, BB)) {
2140 isl_set_free(CondSet);
2141 continue;
2142 }
2143
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002144 // Do not adjust the number of dimensions if we enter a boxed loop or are
2145 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002146 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002147 Region *SuccRegion = RI.getRegionFor(SuccBB);
Johannes Doerfert634909c2015-10-04 14:57:41 +00002148 if (SD.isNonAffineSubRegion(SuccRegion, &getRegion()))
2149 while (SuccBBLoop && SuccRegion->contains(SuccBBLoop))
2150 SuccBBLoop = SuccBBLoop->getParentLoop();
2151
2152 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002153
2154 // Check if the edge to SuccBB is a loop entry or exit edge. If so
2155 // adjust the dimensionality accordingly. Lastly, if we leave a loop
2156 // and enter a new one we need to drop the old constraints.
2157 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002158 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002159 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002160 CondSet = isl_set_project_out(CondSet, isl_dim_set,
2161 isl_set_n_dim(CondSet) - LoopDepthDiff,
2162 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002163 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002164 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002165 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002166 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002167 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002168 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002169 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
2170 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002171 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002172 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002173 }
2174
2175 // Set the domain for the successor or merge it with an existing domain in
2176 // case there are multiple paths (without loop back edges) to the
2177 // successor block.
2178 isl_set *&SuccDomain = DomainMap[SuccBB];
2179 if (!SuccDomain)
2180 SuccDomain = CondSet;
2181 else
2182 SuccDomain = isl_set_union(SuccDomain, CondSet);
2183
2184 SuccDomain = isl_set_coalesce(SuccDomain);
Johannes Doerfert634909c2015-10-04 14:57:41 +00002185 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
2186 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002187 }
2188 }
2189}
2190
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002191/// @brief Return the domain for @p BB wrt @p DomainMap.
2192///
2193/// This helper function will lookup @p BB in @p DomainMap but also handle the
2194/// case where @p BB is contained in a non-affine subregion using the region
2195/// tree obtained by @p RI.
2196static __isl_give isl_set *
2197getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
2198 RegionInfo &RI) {
2199 auto DIt = DomainMap.find(BB);
2200 if (DIt != DomainMap.end())
2201 return isl_set_copy(DIt->getSecond());
2202
2203 Region *R = RI.getRegionFor(BB);
2204 while (R->getEntry() == BB)
2205 R = R->getParent();
2206 return getDomainForBlock(R->getEntry(), DomainMap, RI);
2207}
2208
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002209void Scop::propagateDomainConstraints(Region *R) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002210 // Iterate over the region R and propagate the domain constrains from the
2211 // predecessors to the current node. In contrast to the
2212 // buildDomainsWithBranchConstraints function, this one will pull the domain
2213 // information from the predecessors instead of pushing it to the successors.
2214 // Additionally, we assume the domains to be already present in the domain
2215 // map here. However, we iterate again in reverse post order so we know all
2216 // predecessors have been visited before a block or non-affine subregion is
2217 // visited.
2218
2219 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2220 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2221
2222 ReversePostOrderTraversal<Region *> RTraversal(R);
2223 for (auto *RN : RTraversal) {
2224
2225 // Recurse for affine subregions but go on for basic blocks and non-affine
2226 // subregions.
2227 if (RN->isSubRegion()) {
2228 Region *SubRegion = RN->getNodeAs<Region>();
2229 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002230 propagateDomainConstraints(SubRegion);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002231 continue;
2232 }
2233 }
2234
Johannes Doerfertf5673802015-10-01 23:48:18 +00002235 // Get the domain for the current block and check if it was initialized or
2236 // not. The only way it was not is if this block is only reachable via error
2237 // blocks, thus will not be executed under the assumptions we make. Such
2238 // blocks have to be skipped as their predecessors might not have domains
2239 // either. It would not benefit us to compute the domain anyway, only the
2240 // domains of the error blocks that are reachable from non-error blocks
2241 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002242 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002243 isl_set *&Domain = DomainMap[BB];
2244 if (!Domain) {
2245 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2246 << ", it is only reachable from error blocks.\n");
2247 DomainMap.erase(BB);
2248 continue;
2249 }
2250 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
2251
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002252 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2253 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2254
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002255 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2256 for (auto *PredBB : predecessors(BB)) {
2257
2258 // Skip backedges
2259 if (DT.dominates(BB, PredBB))
2260 continue;
2261
2262 isl_set *PredBBDom = nullptr;
2263
2264 // Handle the SCoP entry block with its outside predecessors.
2265 if (!getRegion().contains(PredBB))
2266 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
2267
2268 if (!PredBBDom) {
2269 // Determine the loop depth of the predecessor and adjust its domain to
2270 // the domain of the current block. This can mean we have to:
2271 // o) Drop a dimension if this block is the exit of a loop, not the
2272 // header of a new loop and the predecessor was part of the loop.
2273 // o) Add an unconstrainted new dimension if this block is the header
2274 // of a loop and the predecessor is not part of it.
2275 // o) Drop the information about the innermost loop dimension when the
2276 // predecessor and the current block are surrounded by different
2277 // loops in the same depth.
2278 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2279 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2280 while (BoxedLoops.count(PredBBLoop))
2281 PredBBLoop = PredBBLoop->getParentLoop();
2282
2283 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002284 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002285 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002286 PredBBDom = isl_set_project_out(
2287 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2288 LoopDepthDiff);
2289 else if (PredBBLoopDepth < BBLoopDepth) {
2290 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002291 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002292 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2293 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002294 PredBBDom = isl_set_drop_constraints_involving_dims(
2295 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002296 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002297 }
2298
2299 PredDom = isl_set_union(PredDom, PredBBDom);
2300 }
2301
2302 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002303 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002304
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002305 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002306 addLoopBoundsToHeaderDomain(BBLoop);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002307
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002308 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002309 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002310 IsOptimized = true;
2311 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002312 addAssumption(ERRORBLOCK, isl_set_complement(DomPar),
2313 BB->getTerminator()->getDebugLoc());
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002314 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002315 }
2316}
2317
2318/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2319/// is incremented by one and all other dimensions are equal, e.g.,
2320/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2321/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2322static __isl_give isl_map *
2323createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2324 auto *MapSpace = isl_space_map_from_set(SetSpace);
2325 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2326 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2327 if (u != Dim)
2328 NextIterationMap =
2329 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2330 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2331 C = isl_constraint_set_constant_si(C, 1);
2332 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2333 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2334 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2335 return NextIterationMap;
2336}
2337
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002338void Scop::addLoopBoundsToHeaderDomain(Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002339 int LoopDepth = getRelativeLoopDepth(L);
2340 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002341
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002342 BasicBlock *HeaderBB = L->getHeader();
2343 assert(DomainMap.count(HeaderBB));
2344 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002345
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002346 isl_map *NextIterationMap =
2347 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002348
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002349 isl_set *UnionBackedgeCondition =
2350 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002351
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002352 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2353 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002354
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002355 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002356
2357 // If the latch is only reachable via error statements we skip it.
2358 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2359 if (!LatchBBDom)
2360 continue;
2361
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002362 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002363
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002364 TerminatorInst *TI = LatchBB->getTerminator();
2365 BranchInst *BI = dyn_cast<BranchInst>(TI);
2366 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002367 BackedgeCondition = isl_set_copy(LatchBBDom);
2368 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002369 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002370 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002371 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002372
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002373 // Free the non back edge condition set as we do not need it.
2374 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002375
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002376 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002377 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002378
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002379 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2380 assert(LatchLoopDepth >= LoopDepth);
2381 BackedgeCondition =
2382 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2383 LatchLoopDepth - LoopDepth);
2384 UnionBackedgeCondition =
2385 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002386 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002387
2388 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2389 for (int i = 0; i < LoopDepth; i++)
2390 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2391
2392 isl_set *UnionBackedgeConditionComplement =
2393 isl_set_complement(UnionBackedgeCondition);
2394 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2395 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2396 UnionBackedgeConditionComplement =
2397 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2398 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2399 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2400
2401 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2402 HeaderBBDom = Parts.second;
2403
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002404 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2405 // the bounded assumptions to the context as they are already implied by the
2406 // <nsw> tag.
2407 if (Affinator.hasNSWAddRecForLoop(L)) {
2408 isl_set_free(Parts.first);
2409 return;
2410 }
2411
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002412 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2413 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002414 addAssumption(INFINITELOOP, BoundedCtx,
2415 HeaderBB->getTerminator()->getDebugLoc());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002416}
2417
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002418void Scop::buildAliasChecks(AliasAnalysis &AA) {
2419 if (!PollyUseRuntimeAliasChecks)
2420 return;
2421
2422 if (buildAliasGroups(AA))
2423 return;
2424
2425 // If a problem occurs while building the alias groups we need to delete
2426 // this SCoP and pretend it wasn't valid in the first place. To this end
2427 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002428 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002429
2430 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2431 << " could not be created as the number of parameters involved "
2432 "is too high. The SCoP will be "
2433 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2434 "the maximal number of parameters but be advised that the "
2435 "compile time might increase exponentially.\n\n");
2436}
2437
Johannes Doerfert9143d672014-09-27 11:02:39 +00002438bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002439 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002440 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002441 // for all memory accesses inside the SCoP.
2442 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002443 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002444 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002445 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002446 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002447 // if their access domains intersect, otherwise they are in different
2448 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002449 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002450 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002451 // and maximal accesses to each array of a group in read only and non
2452 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002453 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2454
2455 AliasSetTracker AST(AA);
2456
2457 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002458 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002459 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002460
2461 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002462 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002463 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2464 isl_set_free(StmtDomain);
2465 if (StmtDomainEmpty)
2466 continue;
2467
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002468 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002469 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002470 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002471 if (!MA->isRead())
2472 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002473 Instruction *Acc = MA->getAccessInstruction();
2474 PtrToAcc[getPointerOperand(*Acc)] = MA;
2475 AST.add(Acc);
2476 }
2477 }
2478
2479 SmallVector<AliasGroupTy, 4> AliasGroups;
2480 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002481 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002482 continue;
2483 AliasGroupTy AG;
2484 for (auto PR : AS)
2485 AG.push_back(PtrToAcc[PR.getValue()]);
2486 assert(AG.size() > 1 &&
2487 "Alias groups should contain at least two accesses");
2488 AliasGroups.push_back(std::move(AG));
2489 }
2490
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002491 // Split the alias groups based on their domain.
2492 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2493 AliasGroupTy NewAG;
2494 AliasGroupTy &AG = AliasGroups[u];
2495 AliasGroupTy::iterator AGI = AG.begin();
2496 isl_set *AGDomain = getAccessDomain(*AGI);
2497 while (AGI != AG.end()) {
2498 MemoryAccess *MA = *AGI;
2499 isl_set *MADomain = getAccessDomain(MA);
2500 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2501 NewAG.push_back(MA);
2502 AGI = AG.erase(AGI);
2503 isl_set_free(MADomain);
2504 } else {
2505 AGDomain = isl_set_union(AGDomain, MADomain);
2506 AGI++;
2507 }
2508 }
2509 if (NewAG.size() > 1)
2510 AliasGroups.push_back(std::move(NewAG));
2511 isl_set_free(AGDomain);
2512 }
2513
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002514 auto &F = *getRegion().getEntry()->getParent();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002515 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002516 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2517 for (AliasGroupTy &AG : AliasGroups) {
2518 NonReadOnlyBaseValues.clear();
2519 ReadOnlyPairs.clear();
2520
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002521 if (AG.size() < 2) {
2522 AG.clear();
2523 continue;
2524 }
2525
Johannes Doerfert13771732014-10-01 12:40:46 +00002526 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002527 emitOptimizationRemarkAnalysis(
2528 F.getContext(), DEBUG_TYPE, F,
2529 (*II)->getAccessInstruction()->getDebugLoc(),
2530 "Possibly aliasing pointer, use restrict keyword.");
2531
Johannes Doerfert13771732014-10-01 12:40:46 +00002532 Value *BaseAddr = (*II)->getBaseAddr();
2533 if (HasWriteAccess.count(BaseAddr)) {
2534 NonReadOnlyBaseValues.insert(BaseAddr);
2535 II++;
2536 } else {
2537 ReadOnlyPairs[BaseAddr].insert(*II);
2538 II = AG.erase(II);
2539 }
2540 }
2541
2542 // If we don't have read only pointers check if there are at least two
2543 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002544 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002545 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002546 continue;
2547 }
2548
2549 // If we don't have non read only pointers clear the alias group.
2550 if (NonReadOnlyBaseValues.empty()) {
2551 AG.clear();
2552 continue;
2553 }
2554
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002555 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002556 MinMaxAliasGroups.emplace_back();
2557 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2558 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2559 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2560 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002561
2562 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002563
2564 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002565 for (MemoryAccess *MA : AG)
2566 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002567
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002568 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2569 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002570
2571 // Bail out if the number of values we need to compare is too large.
2572 // This is important as the number of comparisions grows quadratically with
2573 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002574 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2575 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002576 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002577
2578 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002579 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002580 Accesses = isl_union_map_empty(getParamSpace());
2581
2582 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2583 for (MemoryAccess *MA : ReadOnlyPair.second)
2584 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2585
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002586 Valid =
2587 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002588
2589 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002590 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002591 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002592
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002593 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002594}
2595
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002596/// @brief Get the smallest loop that contains @p R but is not in @p R.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002597static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002598 // Start with the smallest loop containing the entry and expand that
2599 // loop until it contains all blocks in the region. If there is a loop
2600 // containing all blocks in the region check if it is itself contained
2601 // and if so take the parent loop as it will be the smallest containing
2602 // the region but not contained by it.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002603 Loop *L = LI.getLoopFor(R.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002604 while (L) {
2605 bool AllContained = true;
2606 for (auto *BB : R.blocks())
2607 AllContained &= L->contains(BB);
2608 if (AllContained)
2609 break;
2610 L = L->getParentLoop();
2611 }
2612
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002613 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2614}
2615
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002616static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2617 ScopDetection &SD) {
2618
2619 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2620
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002621 unsigned MinLD = INT_MAX, MaxLD = 0;
2622 for (BasicBlock *BB : R.blocks()) {
2623 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002624 if (!R.contains(L))
2625 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002626 if (BoxedLoops && BoxedLoops->count(L))
2627 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002628 unsigned LD = L->getLoopDepth();
2629 MinLD = std::min(MinLD, LD);
2630 MaxLD = std::max(MaxLD, LD);
2631 }
2632 }
2633
2634 // Handle the case that there is no loop in the SCoP first.
2635 if (MaxLD == 0)
2636 return 1;
2637
2638 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2639 assert(MaxLD >= MinLD &&
2640 "Maximal loop depth was smaller than mininaml loop depth?");
2641 return MaxLD - MinLD + 1;
2642}
2643
Johannes Doerfert478a7de2015-10-02 13:09:31 +00002644Scop::Scop(Region &R, AccFuncMapType &AccFuncMap, ScopDetection &SD,
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002645 ScalarEvolution &ScalarEvolution, DominatorTree &DT, LoopInfo &LI,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002646 isl_ctx *Context, unsigned MaxLoopDepth)
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002647 : LI(LI), DT(DT), SE(&ScalarEvolution), SD(SD), R(R),
2648 AccFuncMap(AccFuncMap), IsOptimized(false),
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002649 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
2650 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Context(nullptr),
2651 Affinator(this), AssumedContext(nullptr), BoundaryContext(nullptr),
2652 Schedule(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002653
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002654void Scop::init(AliasAnalysis &AA, AssumptionCache &AC) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002655 buildContext();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002656 addUserAssumptions(AC);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002657 buildInvariantEquivalenceClasses();
2658
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002659 buildDomains(&R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002660
Michael Krusecac948e2015-10-02 13:53:07 +00002661 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002662 // Exit early in case there are no executable statements left in this scop.
Michael Krusecac948e2015-10-02 13:53:07 +00002663 simplifySCoP(true);
Michael Kruseafe06702015-10-02 16:33:27 +00002664 if (Stmts.empty())
2665 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002666
Michael Krusecac948e2015-10-02 13:53:07 +00002667 // The ScopStmts now have enough information to initialize themselves.
2668 for (ScopStmt &Stmt : Stmts)
2669 Stmt.init();
2670
2671 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002672 Loop *L = getLoopSurroundingRegion(R, LI);
2673 LoopSchedules[L];
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002674 buildSchedule(&R, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002675 Schedule = LoopSchedules[L].first;
Tobias Grosser75805372011-04-29 06:27:02 +00002676
Tobias Grosser8286b832015-11-02 11:29:32 +00002677 if (isl_set_is_empty(AssumedContext))
2678 return;
2679
2680 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002681 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002682 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002683 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002684 buildBoundaryContext();
2685 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002686 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002687
2688 hoistInvariantLoads();
Michael Krusecac948e2015-10-02 13:53:07 +00002689 simplifySCoP(false);
Tobias Grosser75805372011-04-29 06:27:02 +00002690}
2691
2692Scop::~Scop() {
2693 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002694 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002695 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002696 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002697
Johannes Doerfert96425c22015-08-30 21:13:53 +00002698 for (auto It : DomainMap)
2699 isl_set_free(It.second);
2700
Johannes Doerfertb164c792014-09-18 11:17:17 +00002701 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002702 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002703 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002704 isl_pw_multi_aff_free(MMA.first);
2705 isl_pw_multi_aff_free(MMA.second);
2706 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002707 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002708 isl_pw_multi_aff_free(MMA.first);
2709 isl_pw_multi_aff_free(MMA.second);
2710 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002711 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002712
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002713 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002714 isl_set_free(std::get<2>(IAClass));
Tobias Grosser75805372011-04-29 06:27:02 +00002715}
2716
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002717void Scop::updateAccessDimensionality() {
2718 for (auto &Stmt : *this)
2719 for (auto &Access : Stmt)
2720 Access->updateDimensionality();
2721}
2722
Michael Krusecac948e2015-10-02 13:53:07 +00002723void Scop::simplifySCoP(bool RemoveIgnoredStmts) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002724 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2725 ScopStmt &Stmt = *StmtIt;
Michael Krusecac948e2015-10-02 13:53:07 +00002726 RegionNode *RN = Stmt.isRegionStmt()
2727 ? Stmt.getRegion()->getNode()
2728 : getRegion().getBBNode(Stmt.getBasicBlock());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002729
Johannes Doerferteca9e892015-11-03 16:54:49 +00002730 bool RemoveStmt = StmtIt->isEmpty();
2731 if (!RemoveStmt)
2732 RemoveStmt = isl_set_is_empty(DomainMap[getRegionNodeBasicBlock(RN)]);
2733 if (!RemoveStmt)
2734 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002735
Johannes Doerferteca9e892015-11-03 16:54:49 +00002736 // Remove read only statements only after invariant loop hoisting.
2737 if (!RemoveStmt && !RemoveIgnoredStmts) {
2738 bool OnlyRead = true;
2739 for (MemoryAccess *MA : Stmt) {
2740 if (MA->isRead())
2741 continue;
2742
2743 OnlyRead = false;
2744 break;
2745 }
2746
2747 RemoveStmt = OnlyRead;
2748 }
2749
2750 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00002751 // Remove the statement because it is unnecessary.
2752 if (Stmt.isRegionStmt())
2753 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2754 StmtMap.erase(BB);
2755 else
2756 StmtMap.erase(Stmt.getBasicBlock());
2757
2758 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002759 continue;
2760 }
2761
Michael Krusecac948e2015-10-02 13:53:07 +00002762 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002763 }
2764}
2765
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002766const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2767 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2768 if (!LInst)
2769 return nullptr;
2770
2771 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2772 LInst = cast<LoadInst>(Rep);
2773
2774 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2775 for (auto &IAClass : InvariantEquivClasses)
2776 if (PointerSCEV == std::get<0>(IAClass))
2777 return &IAClass;
2778
2779 return nullptr;
2780}
2781
2782void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2783
2784 // Get the context under which the statement is executed.
2785 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2786 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2787 DomainCtx = isl_set_detect_equalities(DomainCtx);
2788 DomainCtx = isl_set_coalesce(DomainCtx);
2789
2790 // Project out all parameters that relate to loads in the statement. Otherwise
2791 // we could have cyclic dependences on the constraints under which the
2792 // hoisted loads are executed and we could not determine an order in which to
2793 // pre-load them. This happens because not only lower bounds are part of the
2794 // domain but also upper bounds.
2795 for (MemoryAccess *MA : InvMAs) {
2796 Instruction *AccInst = MA->getAccessInstruction();
2797 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00002798 SetVector<Value *> Values;
2799 for (const SCEV *Parameter : Parameters) {
2800 Values.clear();
2801 findValues(Parameter, Values);
2802 if (!Values.count(AccInst))
2803 continue;
2804
2805 if (isl_id *ParamId = getIdForParam(Parameter)) {
2806 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2807 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2808 isl_id_free(ParamId);
2809 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002810 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002811 }
2812 }
2813
2814 for (MemoryAccess *MA : InvMAs) {
2815 // Check for another invariant access that accesses the same location as
2816 // MA and if found consolidate them. Otherwise create a new equivalence
2817 // class at the end of InvariantEquivClasses.
2818 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
2819 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2820
2821 bool Consolidated = false;
2822 for (auto &IAClass : InvariantEquivClasses) {
2823 if (PointerSCEV != std::get<0>(IAClass))
2824 continue;
2825
2826 Consolidated = true;
2827
2828 // Add MA to the list of accesses that are in this class.
2829 auto &MAs = std::get<1>(IAClass);
2830 MAs.push_front(MA);
2831
2832 // Unify the execution context of the class and this statement.
2833 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002834 if (IAClassDomainCtx)
2835 IAClassDomainCtx = isl_set_coalesce(
2836 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
2837 else
2838 IAClassDomainCtx = isl_set_copy(DomainCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002839 break;
2840 }
2841
2842 if (Consolidated)
2843 continue;
2844
2845 // If we did not consolidate MA, thus did not find an equivalence class
2846 // for it, we create a new one.
2847 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
2848 isl_set_copy(DomainCtx));
2849 }
2850
2851 isl_set_free(DomainCtx);
2852}
2853
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002854bool Scop::isHoistableAccess(MemoryAccess *Access,
2855 __isl_keep isl_union_map *Writes) {
2856 // TODO: Loads that are not loop carried, hence are in a statement with
2857 // zero iterators, are by construction invariant, though we
2858 // currently "hoist" them anyway. This is necessary because we allow
2859 // them to be treated as parameters (e.g., in conditions) and our code
2860 // generation would otherwise use the old value.
2861
2862 auto &Stmt = *Access->getStatement();
2863 BasicBlock *BB =
2864 Stmt.isBlockStmt() ? Stmt.getBasicBlock() : Stmt.getRegion()->getEntry();
2865
2866 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
2867 return false;
2868
2869 // Skip accesses that have an invariant base pointer which is defined but
2870 // not loaded inside the SCoP. This can happened e.g., if a readnone call
2871 // returns a pointer that is used as a base address. However, as we want
2872 // to hoist indirect pointers, we allow the base pointer to be defined in
2873 // the region if it is also a memory access. Each ScopArrayInfo object
2874 // that has a base pointer origin has a base pointer that is loaded and
2875 // that it is invariant, thus it will be hoisted too. However, if there is
2876 // no base pointer origin we check that the base pointer is defined
2877 // outside the region.
2878 const ScopArrayInfo *SAI = Access->getScopArrayInfo();
2879 while (auto *BasePtrOriginSAI = SAI->getBasePtrOriginSAI())
2880 SAI = BasePtrOriginSAI;
2881
2882 if (auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr()))
2883 if (R.contains(BasePtrInst))
2884 return false;
2885
2886 // Skip accesses in non-affine subregions as they might not be executed
2887 // under the same condition as the entry of the non-affine subregion.
2888 if (BB != Access->getAccessInstruction()->getParent())
2889 return false;
2890
2891 isl_map *AccessRelation = Access->getAccessRelation();
2892
2893 // Skip accesses that have an empty access relation. These can be caused
2894 // by multiple offsets with a type cast in-between that cause the overall
2895 // byte offset to be not divisible by the new types sizes.
2896 if (isl_map_is_empty(AccessRelation)) {
2897 isl_map_free(AccessRelation);
2898 return false;
2899 }
2900
2901 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
2902 Stmt.getNumIterators())) {
2903 isl_map_free(AccessRelation);
2904 return false;
2905 }
2906
2907 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
2908 isl_set *AccessRange = isl_map_range(AccessRelation);
2909
2910 isl_union_map *Written = isl_union_map_intersect_range(
2911 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
2912 bool IsWritten = !isl_union_map_is_empty(Written);
2913 isl_union_map_free(Written);
2914
2915 if (IsWritten)
2916 return false;
2917
2918 return true;
2919}
2920
2921void Scop::verifyInvariantLoads() {
2922 auto &RIL = *SD.getRequiredInvariantLoads(&getRegion());
2923 for (LoadInst *LI : RIL) {
2924 assert(LI && getRegion().contains(LI));
2925 ScopStmt *Stmt = getStmtForBasicBlock(LI->getParent());
2926 if (Stmt && Stmt->lookupAccessesFor(LI)) {
2927 invalidate(INVARIANTLOAD, LI->getDebugLoc());
2928 return;
2929 }
2930 }
2931}
2932
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002933void Scop::hoistInvariantLoads() {
2934 isl_union_map *Writes = getWrites();
2935 for (ScopStmt &Stmt : *this) {
2936
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002937 MemoryAccessList InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002938
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002939 for (MemoryAccess *Access : Stmt)
2940 if (isHoistableAccess(Access, Writes))
2941 InvariantAccesses.push_front(Access);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002942
2943 // We inserted invariant accesses always in the front but need them to be
2944 // sorted in a "natural order". The statements are already sorted in reverse
2945 // post order and that suffices for the accesses too. The reason we require
2946 // an order in the first place is the dependences between invariant loads
2947 // that can be caused by indirect loads.
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002948 InvariantAccesses.reverse();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002949
2950 // Transfer the memory access from the statement to the SCoP.
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002951 Stmt.removeMemoryAccesses(InvariantAccesses);
2952 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002953 }
2954 isl_union_map_free(Writes);
2955
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002956 verifyInvariantLoads();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002957}
2958
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002959const ScopArrayInfo *
2960Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002961 ArrayRef<const SCEV *> Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00002962 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002963 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002964 if (!SAI) {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00002965 auto &DL = getRegion().getEntry()->getModule()->getDataLayout();
2966 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, Kind,
2967 DL, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002968 } else {
Tobias Grosser8286b832015-11-02 11:29:32 +00002969 // In case of mismatching array sizes, we bail out by setting the run-time
2970 // context to false.
2971 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002972 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002973 }
Tobias Grosserab671442015-05-23 05:58:27 +00002974 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002975}
2976
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002977const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00002978 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002979 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002980 assert(SAI && "No ScopArrayInfo available for this base pointer");
2981 return SAI;
2982}
2983
Tobias Grosser74394f02013-01-14 22:40:23 +00002984std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002985std::string Scop::getAssumedContextStr() const {
2986 return stringFromIslObj(AssumedContext);
2987}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002988std::string Scop::getBoundaryContextStr() const {
2989 return stringFromIslObj(BoundaryContext);
2990}
Tobias Grosser75805372011-04-29 06:27:02 +00002991
2992std::string Scop::getNameStr() const {
2993 std::string ExitName, EntryName;
2994 raw_string_ostream ExitStr(ExitName);
2995 raw_string_ostream EntryStr(EntryName);
2996
Tobias Grosserf240b482014-01-09 10:42:15 +00002997 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002998 EntryStr.str();
2999
3000 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003001 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003002 ExitStr.str();
3003 } else
3004 ExitName = "FunctionExit";
3005
3006 return EntryName + "---" + ExitName;
3007}
3008
Tobias Grosser74394f02013-01-14 22:40:23 +00003009__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003010__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003011 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003012}
3013
Tobias Grossere86109f2013-10-29 21:05:49 +00003014__isl_give isl_set *Scop::getAssumedContext() const {
3015 return isl_set_copy(AssumedContext);
3016}
3017
Johannes Doerfert43788c52015-08-20 05:58:56 +00003018__isl_give isl_set *Scop::getRuntimeCheckContext() const {
3019 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003020 RuntimeCheckContext =
3021 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
3022 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00003023 return RuntimeCheckContext;
3024}
3025
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003026bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003027 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003028 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00003029 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
3030 isl_set_free(RuntimeCheckContext);
3031 return IsFeasible;
3032}
3033
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003034static std::string toString(AssumptionKind Kind) {
3035 switch (Kind) {
3036 case ALIASING:
3037 return "No-aliasing";
3038 case INBOUNDS:
3039 return "Inbounds";
3040 case WRAPPING:
3041 return "No-overflows";
Johannes Doerferta4b77c02015-11-12 20:15:32 +00003042 case ALIGNMENT:
3043 return "Alignment";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003044 case ERRORBLOCK:
3045 return "No-error";
3046 case INFINITELOOP:
3047 return "Finite loop";
3048 case INVARIANTLOAD:
3049 return "Invariant load";
3050 case DELINEARIZATION:
3051 return "Delinearization";
3052 }
3053 llvm_unreachable("Unknown AssumptionKind!");
3054}
3055
3056void Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3057 DebugLoc Loc) {
3058 if (isl_set_is_subset(Context, Set))
3059 return;
3060
3061 if (isl_set_is_subset(AssumedContext, Set))
3062 return;
3063
3064 auto &F = *getRegion().getEntry()->getParent();
3065 std::string Msg = toString(Kind) + " assumption:\t" + stringFromIslObj(Set);
3066 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
3067}
3068
3069void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
3070 DebugLoc Loc) {
3071 trackAssumption(Kind, Set, Loc);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003072 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003073
Johannes Doerfert9d7899e2015-11-11 20:01:31 +00003074 int NSets = isl_set_n_basic_set(AssumedContext);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003075 if (NSets >= MaxDisjunctsAssumed) {
3076 isl_space *Space = isl_set_get_space(AssumedContext);
3077 isl_set_free(AssumedContext);
Tobias Grossere19fca42015-11-11 20:21:39 +00003078 AssumedContext = isl_set_empty(Space);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003079 }
3080
Tobias Grosser7b50bee2014-11-25 10:51:12 +00003081 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003082}
3083
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003084void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
3085 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc);
3086}
3087
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003088__isl_give isl_set *Scop::getBoundaryContext() const {
3089 return isl_set_copy(BoundaryContext);
3090}
3091
Tobias Grosser75805372011-04-29 06:27:02 +00003092void Scop::printContext(raw_ostream &OS) const {
3093 OS << "Context:\n";
3094
3095 if (!Context) {
3096 OS.indent(4) << "n/a\n\n";
3097 return;
3098 }
3099
3100 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003101
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003102 OS.indent(4) << "Assumed Context:\n";
3103 if (!AssumedContext) {
3104 OS.indent(4) << "n/a\n\n";
3105 return;
3106 }
3107
3108 OS.indent(4) << getAssumedContextStr() << "\n";
3109
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003110 OS.indent(4) << "Boundary Context:\n";
3111 if (!BoundaryContext) {
3112 OS.indent(4) << "n/a\n\n";
3113 return;
3114 }
3115
3116 OS.indent(4) << getBoundaryContextStr() << "\n";
3117
Tobias Grosser083d3d32014-06-28 08:59:45 +00003118 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00003119 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00003120 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
3121 }
Tobias Grosser75805372011-04-29 06:27:02 +00003122}
3123
Johannes Doerfertb164c792014-09-18 11:17:17 +00003124void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003125 int noOfGroups = 0;
3126 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003127 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003128 noOfGroups += 1;
3129 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003130 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003131 }
3132
Tobias Grosserbb853c22015-07-25 12:31:03 +00003133 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003134 if (MinMaxAliasGroups.empty()) {
3135 OS.indent(8) << "n/a\n";
3136 return;
3137 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003138
Tobias Grosserbb853c22015-07-25 12:31:03 +00003139 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003140
3141 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003142 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003143 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003144 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003145 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3146 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003147 }
3148 OS << " ]]\n";
3149 }
3150
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003151 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003152 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003153 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003154 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003155 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3156 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003157 }
3158 OS << " ]]\n";
3159 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003160 }
3161}
3162
Tobias Grosser75805372011-04-29 06:27:02 +00003163void Scop::printStatements(raw_ostream &OS) const {
3164 OS << "Statements {\n";
3165
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003166 for (const ScopStmt &Stmt : *this)
3167 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003168
3169 OS.indent(4) << "}\n";
3170}
3171
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003172void Scop::printArrayInfo(raw_ostream &OS) const {
3173 OS << "Arrays {\n";
3174
Tobias Grosserab671442015-05-23 05:58:27 +00003175 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003176 Array.second->print(OS);
3177
3178 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003179
3180 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3181
3182 for (auto &Array : arrays())
3183 Array.second->print(OS, /* SizeAsPwAff */ true);
3184
3185 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003186}
3187
Tobias Grosser75805372011-04-29 06:27:02 +00003188void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00003189 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
3190 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003191 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003192 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003193 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003194 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003195 const auto &MAs = std::get<1>(IAClass);
3196 if (MAs.empty()) {
3197 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003198 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003199 MAs.front()->print(OS);
3200 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003201 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003202 }
3203 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003204 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003205 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003206 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003207 printStatements(OS.indent(4));
3208}
3209
3210void Scop::dump() const { print(dbgs()); }
3211
Tobias Grosser9a38ab82011-11-08 15:41:03 +00003212isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00003213
Johannes Doerfertcef616f2015-09-15 22:49:04 +00003214__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
3215 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003216}
3217
Tobias Grosser808cd692015-07-14 09:33:13 +00003218__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003219 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003220
Tobias Grosser808cd692015-07-14 09:33:13 +00003221 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003222 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003223
3224 return Domain;
3225}
3226
Tobias Grossere5a35142015-11-12 14:07:09 +00003227__isl_give isl_union_map *
3228Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3229 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003230
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003231 for (ScopStmt &Stmt : *this) {
3232 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003233 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003234 continue;
3235
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003236 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003237 isl_map *AccessDomain = MA->getAccessRelation();
3238 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003239 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003240 }
3241 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003242 return isl_union_map_coalesce(Accesses);
3243}
3244
3245__isl_give isl_union_map *Scop::getMustWrites() {
3246 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003247}
3248
3249__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003250 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003251}
3252
Tobias Grosser37eb4222014-02-20 21:43:54 +00003253__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003254 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003255}
3256
3257__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003258 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003259}
3260
Tobias Grosser2ac23382015-11-12 14:07:13 +00003261__isl_give isl_union_map *Scop::getAccesses() {
3262 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3263}
3264
Tobias Grosser808cd692015-07-14 09:33:13 +00003265__isl_give isl_union_map *Scop::getSchedule() const {
3266 auto Tree = getScheduleTree();
3267 auto S = isl_schedule_get_map(Tree);
3268 isl_schedule_free(Tree);
3269 return S;
3270}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003271
Tobias Grosser808cd692015-07-14 09:33:13 +00003272__isl_give isl_schedule *Scop::getScheduleTree() const {
3273 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3274 getDomains());
3275}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003276
Tobias Grosser808cd692015-07-14 09:33:13 +00003277void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3278 auto *S = isl_schedule_from_domain(getDomains());
3279 S = isl_schedule_insert_partial_schedule(
3280 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3281 isl_schedule_free(Schedule);
3282 Schedule = S;
3283}
3284
3285void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3286 isl_schedule_free(Schedule);
3287 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003288}
3289
3290bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3291 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003292 for (ScopStmt &Stmt : *this) {
3293 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003294 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3295 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3296
3297 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3298 isl_union_set_free(StmtDomain);
3299 isl_union_set_free(NewStmtDomain);
3300 continue;
3301 }
3302
3303 Changed = true;
3304
3305 isl_union_set_free(StmtDomain);
3306 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3307
3308 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003309 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003310 isl_union_set_free(NewStmtDomain);
3311 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003312 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003313 }
3314 isl_union_set_free(Domain);
3315 return Changed;
3316}
3317
Tobias Grosser75805372011-04-29 06:27:02 +00003318ScalarEvolution *Scop::getSE() const { return SE; }
3319
Johannes Doerfertf5673802015-10-01 23:48:18 +00003320bool Scop::isIgnored(RegionNode *RN) {
3321 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Michael Krusea902ba62015-12-13 19:21:45 +00003322 ScopStmt *Stmt = getStmtForRegionNode(RN);
3323
3324 // If there is no stmt, then it already has been removed.
3325 if (!Stmt)
3326 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00003327
Johannes Doerfertf5673802015-10-01 23:48:18 +00003328 // Check if there are accesses contained.
Michael Krusea902ba62015-12-13 19:21:45 +00003329 if (Stmt->isEmpty())
Johannes Doerfertf5673802015-10-01 23:48:18 +00003330 return true;
3331
3332 // Check for reachability via non-error blocks.
3333 if (!DomainMap.count(BB))
3334 return true;
3335
3336 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003337 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003338 return true;
3339
3340 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003341}
3342
Tobias Grosser808cd692015-07-14 09:33:13 +00003343struct MapToDimensionDataTy {
3344 int N;
3345 isl_union_pw_multi_aff *Res;
3346};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003347
Tobias Grosser808cd692015-07-14 09:33:13 +00003348// @brief Create a function that maps the elements of 'Set' to its N-th
3349// dimension.
3350//
3351// The result is added to 'User->Res'.
3352//
3353// @param Set The input set.
3354// @param N The dimension to map to.
3355//
3356// @returns Zero if no error occurred, non-zero otherwise.
3357static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3358 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3359 int Dim;
3360 isl_space *Space;
3361 isl_pw_multi_aff *PMA;
3362
3363 Dim = isl_set_dim(Set, isl_dim_set);
3364 Space = isl_set_get_space(Set);
3365 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3366 Dim - Data->N);
3367 if (Data->N > 1)
3368 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3369 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3370
3371 isl_set_free(Set);
3372
3373 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003374}
3375
Tobias Grosser808cd692015-07-14 09:33:13 +00003376// @brief Create a function that maps the elements of Domain to their Nth
3377// dimension.
3378//
3379// @param Domain The set of elements to map.
3380// @param N The dimension to map to.
3381static __isl_give isl_multi_union_pw_aff *
3382mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003383 if (N <= 0 || isl_union_set_is_empty(Domain)) {
3384 isl_union_set_free(Domain);
3385 return nullptr;
3386 }
3387
Tobias Grosser808cd692015-07-14 09:33:13 +00003388 struct MapToDimensionDataTy Data;
3389 isl_space *Space;
3390
3391 Space = isl_union_set_get_space(Domain);
3392 Data.N = N;
3393 Data.Res = isl_union_pw_multi_aff_empty(Space);
3394 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
3395 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
3396
3397 isl_union_set_free(Domain);
3398 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3399}
3400
Tobias Grosser316b5b22015-11-11 19:28:14 +00003401void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003402 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003403 Stmts.emplace_back(*this, *BB);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003404 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003405 StmtMap[BB] = Stmt;
3406 } else {
3407 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003408 Stmts.emplace_back(*this, *R);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003409 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003410 for (BasicBlock *BB : R->blocks())
3411 StmtMap[BB] = Stmt;
3412 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003413}
3414
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003415void Scop::buildSchedule(
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003416 Region *R,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003417 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00003418
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003419 if (SD.isNonAffineSubRegion(R, &getRegion())) {
Johannes Doerfertc6987c12015-09-26 13:41:43 +00003420 Loop *L = getLoopSurroundingRegion(*R, LI);
3421 auto &LSchedulePair = LoopSchedules[L];
Michael Krusecac948e2015-10-02 13:53:07 +00003422 ScopStmt *Stmt = getStmtForBasicBlock(R->getEntry());
Michael Kruseafe06702015-10-02 16:33:27 +00003423 isl_set *Domain = Stmt->getDomain();
Michael Krusecac948e2015-10-02 13:53:07 +00003424 auto *UDomain = isl_union_set_from_set(Domain);
3425 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003426 LSchedulePair.first = StmtSchedule;
3427 return;
3428 }
3429
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003430 ReversePostOrderTraversal<Region *> RTraversal(R);
3431 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00003432
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003433 if (RN->isSubRegion()) {
3434 Region *SubRegion = RN->getNodeAs<Region>();
3435 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003436 buildSchedule(SubRegion, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003437 continue;
3438 }
Tobias Grosser75805372011-04-29 06:27:02 +00003439 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003440
3441 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert30c22652015-10-18 21:17:11 +00003442 if (!getRegion().contains(L))
3443 L = getLoopSurroundingRegion(getRegion(), LI);
3444
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003445 int LD = getRelativeLoopDepth(L);
3446 auto &LSchedulePair = LoopSchedules[L];
3447 LSchedulePair.second += getNumBlocksInRegionNode(RN);
3448
Michael Krusecac948e2015-10-02 13:53:07 +00003449 BasicBlock *BB = getRegionNodeBasicBlock(RN);
3450 ScopStmt *Stmt = getStmtForBasicBlock(BB);
3451 if (Stmt) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003452 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3453 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
3454 LSchedulePair.first =
3455 combineInSequence(LSchedulePair.first, StmtSchedule);
3456 }
3457
3458 unsigned NumVisited = LSchedulePair.second;
3459 while (L && NumVisited == L->getNumBlocks()) {
3460 auto *LDomain = isl_schedule_get_domain(LSchedulePair.first);
3461 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
3462 LSchedulePair.first =
3463 isl_schedule_insert_partial_schedule(LSchedulePair.first, MUPA);
3464
3465 auto *PL = L->getParentLoop();
Johannes Doerfertdca28372015-11-03 00:28:07 +00003466
3467 // Either we have a proper loop and we also build a schedule for the
3468 // parent loop or we have a infinite loop that does not have a proper
3469 // parent loop. In the former case this conditional will be skipped, in
3470 // the latter case however we will break here as we do not build a domain
3471 // nor a schedule for a infinite loop.
3472 assert(LoopSchedules.count(PL) || LSchedulePair.first == nullptr);
3473 if (!LoopSchedules.count(PL))
3474 break;
3475
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003476 auto &PSchedulePair = LoopSchedules[PL];
3477 PSchedulePair.first =
3478 combineInSequence(PSchedulePair.first, LSchedulePair.first);
3479 PSchedulePair.second += NumVisited;
3480
3481 L = PL;
3482 NumVisited = PSchedulePair.second;
3483 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003484 }
Tobias Grosser75805372011-04-29 06:27:02 +00003485}
3486
Johannes Doerfert7c494212014-10-31 23:13:39 +00003487ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003488 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003489 if (StmtMapIt == StmtMap.end())
3490 return nullptr;
3491 return StmtMapIt->second;
3492}
3493
Michael Krusea902ba62015-12-13 19:21:45 +00003494ScopStmt *Scop::getStmtForRegionNode(RegionNode *RN) const {
3495 return getStmtForBasicBlock(getRegionNodeBasicBlock(RN));
3496}
3497
Johannes Doerfert96425c22015-08-30 21:13:53 +00003498int Scop::getRelativeLoopDepth(const Loop *L) const {
3499 Loop *OuterLoop =
3500 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3501 if (!OuterLoop)
3502 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003503 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3504}
3505
Michael Krused868b5d2015-09-10 15:25:24 +00003506void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003507 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003508
3509 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3510 // true, are not modeled as ordinary PHI nodes as they are not part of the
3511 // region. However, we model the operands in the predecessor blocks that are
3512 // part of the region as regular scalar accesses.
3513
3514 // If we can synthesize a PHI we can skip it, however only if it is in
3515 // the region. If it is not it can only be in the exit block of the region.
3516 // In this case we model the operands but not the PHI itself.
3517 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3518 return;
3519
3520 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3521 // detection. Hence, the PHI is a load of a new memory location in which the
3522 // incoming value was written at the end of the incoming basic block.
3523 bool OnlyNonAffineSubRegionOperands = true;
3524 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3525 Value *Op = PHI->getIncomingValue(u);
3526 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3527
3528 // Do not build scalar dependences inside a non-affine subregion.
3529 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3530 continue;
3531
3532 OnlyNonAffineSubRegionOperands = false;
3533
3534 if (!R.contains(OpBB))
3535 continue;
3536
3537 Instruction *OpI = dyn_cast<Instruction>(Op);
3538 if (OpI) {
3539 BasicBlock *OpIBB = OpI->getParent();
3540 // As we pretend there is a use (or more precise a write) of OpI in OpBB
3541 // we have to insert a scalar dependence from the definition of OpI to
3542 // OpBB if the definition is not in OpBB.
Michael Kruse668af712015-10-15 14:45:48 +00003543 if (scop->getStmtForBasicBlock(OpIBB) !=
3544 scop->getStmtForBasicBlock(OpBB)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003545 addScalarReadAccess(OpI, PHI, OpBB);
3546 addScalarWriteAccess(OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003547 }
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003548 } else if (ModelReadOnlyScalars && !isa<Constant>(Op)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003549 addScalarReadAccess(Op, PHI, OpBB);
Michael Kruse7bf39442015-09-10 12:46:52 +00003550 }
3551
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003552 addPHIWriteAccess(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003553 }
3554
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003555 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3556 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003557 }
3558}
3559
Michael Krused868b5d2015-09-10 15:25:24 +00003560bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
3561 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003562 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
3563 if (isIgnoredIntrinsic(Inst))
3564 return false;
3565
3566 bool AnyCrossStmtUse = false;
3567 BasicBlock *ParentBB = Inst->getParent();
3568
3569 for (User *U : Inst->users()) {
3570 Instruction *UI = dyn_cast<Instruction>(U);
3571
3572 // Ignore the strange user
3573 if (UI == 0)
3574 continue;
3575
3576 BasicBlock *UseParent = UI->getParent();
3577
Tobias Grosserbaffa092015-10-24 20:55:27 +00003578 // Ignore basic block local uses. A value that is defined in a scop, but
3579 // used in a PHI node in the same basic block does not count as basic block
3580 // local, as for such cases a control flow edge is passed between definition
3581 // and use.
3582 if (UseParent == ParentBB && !isa<PHINode>(UI))
Michael Kruse7bf39442015-09-10 12:46:52 +00003583 continue;
3584
Michael Krusef714d472015-11-05 13:18:43 +00003585 // Uses by PHI nodes in the entry node count as external uses in case the
3586 // use is through an incoming block that is itself not contained in the
3587 // region.
3588 if (R->getEntry() == UseParent) {
3589 if (auto *PHI = dyn_cast<PHINode>(UI)) {
3590 bool ExternalUse = false;
3591 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
3592 if (PHI->getIncomingValue(i) == Inst &&
3593 !R->contains(PHI->getIncomingBlock(i))) {
3594 ExternalUse = true;
3595 break;
3596 }
3597 }
3598
3599 if (ExternalUse) {
3600 AnyCrossStmtUse = true;
3601 continue;
3602 }
3603 }
3604 }
3605
Michael Kruse7bf39442015-09-10 12:46:52 +00003606 // Do not build scalar dependences inside a non-affine subregion.
3607 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
3608 continue;
3609
Michael Kruse01cb3792015-10-17 21:07:08 +00003610 // Check for PHI nodes in the region exit and skip them, if they will be
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003611 // modeled as PHI nodes.
Michael Kruse01cb3792015-10-17 21:07:08 +00003612 //
3613 // PHI nodes in the region exit that have more than two incoming edges need
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003614 // to be modeled as PHI-Nodes to correctly model the fact that depending on
3615 // the control flow a different value will be assigned to the PHI node. In
3616 // case this is the case, there is no need to create an additional normal
3617 // scalar dependence. Hence, bail out before we register an "out-of-region"
3618 // use for this definition.
Michael Kruse01cb3792015-10-17 21:07:08 +00003619 if (isa<PHINode>(UI) && UI->getParent() == R->getExit() &&
3620 !R->getExitingBlock())
3621 continue;
3622
Michael Kruse7bf39442015-09-10 12:46:52 +00003623 // Check whether or not the use is in the SCoP.
Tobias Grosserc73d8b02015-10-23 22:36:22 +00003624 if (!R->contains(UseParent)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003625 AnyCrossStmtUse = true;
3626 continue;
3627 }
3628
3629 // If the instruction can be synthesized and the user is in the region
3630 // we do not need to add scalar dependences.
3631 if (canSynthesizeInst)
3632 continue;
3633
3634 // No need to translate these scalar dependences into polyhedral form,
3635 // because synthesizable scalars can be generated by the code generator.
3636 if (canSynthesize(UI, LI, SE, R))
3637 continue;
3638
3639 // Skip PHI nodes in the region as they handle their operands on their own.
3640 if (isa<PHINode>(UI))
3641 continue;
3642
3643 // Now U is used in another statement.
3644 AnyCrossStmtUse = true;
3645
3646 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00003647 // Use the def instruction as base address of the MemoryAccess, so that it
3648 // will become the name of the scalar access in the polyhedral form.
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003649 addScalarReadAccess(Inst, UI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003650 }
3651
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003652 if (ModelReadOnlyScalars && !isa<PHINode>(Inst)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003653 for (Value *Op : Inst->operands()) {
3654 if (canSynthesize(Op, LI, SE, R))
3655 continue;
3656
3657 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
3658 if (R->contains(OpInst))
3659 continue;
3660
3661 if (isa<Constant>(Op))
3662 continue;
3663
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003664 addScalarReadAccess(Op, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003665 }
3666 }
3667
3668 return AnyCrossStmtUse;
3669}
3670
3671extern MapInsnToMemAcc InsnToMemAcc;
3672
Michael Krusee2bccbb2015-09-18 19:59:43 +00003673void ScopInfo::buildMemoryAccess(
3674 Instruction *Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003675 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3676 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003677 unsigned Size;
3678 Type *SizeType;
3679 Value *Val;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003680 enum MemoryAccess::AccessType Type;
Michael Kruse7bf39442015-09-10 12:46:52 +00003681
3682 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
3683 SizeType = Load->getType();
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003684 Size = TD->getTypeAllocSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003685 Type = MemoryAccess::READ;
Michael Kruse7bf39442015-09-10 12:46:52 +00003686 Val = Load;
3687 } else {
3688 StoreInst *Store = cast<StoreInst>(Inst);
3689 SizeType = Store->getValueOperand()->getType();
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003690 Size = TD->getTypeAllocSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003691 Type = MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003692 Val = Store->getValueOperand();
3693 }
3694
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003695 auto Address = getPointerOperand(*Inst);
3696
3697 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003698 const SCEVUnknown *BasePointer =
3699 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3700
3701 assert(BasePointer && "Could not find base pointer");
3702 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
3703
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003704 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3705 auto NewAddress = Address;
3706 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3707 auto Src = BitCast->getOperand(0);
3708 auto SrcTy = Src->getType();
3709 auto DstTy = BitCast->getType();
3710 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3711 NewAddress = Src;
3712 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003713
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003714 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3715 std::vector<const SCEV *> Subscripts;
3716 std::vector<int> Sizes;
3717 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3718 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003719
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003720 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003721
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003722 bool AllAffineSubcripts = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003723 for (auto Subscript : Subscripts) {
3724 InvariantLoadsSetTy AccessILS;
3725 AllAffineSubcripts =
3726 isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS);
3727
3728 for (LoadInst *LInst : AccessILS)
3729 if (!ScopRIL.count(LInst))
3730 AllAffineSubcripts = false;
3731
3732 if (!AllAffineSubcripts)
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003733 break;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003734 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003735
3736 if (AllAffineSubcripts && Sizes.size() > 0) {
3737 for (auto V : Sizes)
3738 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3739 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003740 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003741 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003742
Tobias Grossera535dff2015-12-13 19:59:01 +00003743 addArrayAccess(Inst, Type, BasePointer->getValue(), Size, true,
3744 Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00003745 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003746 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003747 }
3748 }
3749
Michael Kruse7bf39442015-09-10 12:46:52 +00003750 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003751 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003752 addArrayAccess(Inst, Type, BasePointer->getValue(), Size, true,
3753 AccItr->second.DelinearizedSubscripts,
3754 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003755 return;
3756 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003757
3758 // Check if the access depends on a loop contained in a non-affine subregion.
3759 bool isVariantInNonAffineLoop = false;
3760 if (BoxedLoops) {
3761 SetVector<const Loop *> Loops;
3762 findLoops(AccessFunction, Loops);
3763 for (const Loop *L : Loops)
3764 if (BoxedLoops->count(L))
3765 isVariantInNonAffineLoop = true;
3766 }
3767
Johannes Doerfert09e36972015-10-07 20:17:36 +00003768 InvariantLoadsSetTy AccessILS;
3769 bool IsAffine =
3770 !isVariantInNonAffineLoop &&
3771 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3772
3773 for (LoadInst *LInst : AccessILS)
3774 if (!ScopRIL.count(LInst))
3775 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003776
Michael Krusecaac2b62015-09-26 15:51:44 +00003777 // FIXME: Size of the number of bytes of an array element, not the number of
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003778 // elements as probably intended here.
Tobias Grossera43b6e92015-09-27 17:54:50 +00003779 const SCEV *SizeSCEV =
3780 SE->getConstant(TD->getIntPtrType(Inst->getContext()), Size);
Michael Kruse7bf39442015-09-10 12:46:52 +00003781
Michael Krusee2bccbb2015-09-18 19:59:43 +00003782 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3783 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003784
Tobias Grossera535dff2015-12-13 19:59:01 +00003785 addArrayAccess(Inst, Type, BasePointer->getValue(), Size, IsAffine,
3786 ArrayRef<const SCEV *>(AccessFunction),
3787 ArrayRef<const SCEV *>(SizeSCEV), Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003788}
3789
Michael Krused868b5d2015-09-10 15:25:24 +00003790void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003791
3792 if (SD->isNonAffineSubRegion(&SR, &R)) {
3793 for (BasicBlock *BB : SR.blocks())
3794 buildAccessFunctions(R, *BB, &SR);
3795 return;
3796 }
3797
3798 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3799 if (I->isSubRegion())
3800 buildAccessFunctions(R, *I->getNodeAs<Region>());
3801 else
3802 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
3803}
3804
Michael Krusecac948e2015-10-02 13:53:07 +00003805void ScopInfo::buildStmts(Region &SR) {
3806 Region *R = getRegion();
3807
3808 if (SD->isNonAffineSubRegion(&SR, R)) {
3809 scop->addScopStmt(nullptr, &SR);
3810 return;
3811 }
3812
3813 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3814 if (I->isSubRegion())
3815 buildStmts(*I->getNodeAs<Region>());
3816 else
3817 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
3818}
3819
Michael Krused868b5d2015-09-10 15:25:24 +00003820void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
3821 Region *NonAffineSubRegion,
3822 bool IsExitBlock) {
Tobias Grosser910cf262015-11-11 20:15:49 +00003823 // We do not build access functions for error blocks, as they may contain
3824 // instructions we can not model.
3825 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3826 if (isErrorBlock(BB, R, *LI, DT) && !IsExitBlock)
3827 return;
3828
Michael Kruse7bf39442015-09-10 12:46:52 +00003829 Loop *L = LI->getLoopFor(&BB);
3830
3831 // The set of loops contained in non-affine subregions that are part of R.
3832 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3833
Johannes Doerfert09e36972015-10-07 20:17:36 +00003834 // The set of loads that are required to be invariant.
3835 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
3836
Michael Kruse7bf39442015-09-10 12:46:52 +00003837 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00003838 Instruction *Inst = &*I;
Michael Kruse7bf39442015-09-10 12:46:52 +00003839
3840 PHINode *PHI = dyn_cast<PHINode>(Inst);
3841 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003842 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003843
3844 // For the exit block we stop modeling after the last PHI node.
3845 if (!PHI && IsExitBlock)
3846 break;
3847
Johannes Doerfert09e36972015-10-07 20:17:36 +00003848 // TODO: At this point we only know that elements of ScopRIL have to be
3849 // invariant and will be hoisted for the SCoP to be processed. Though,
3850 // there might be other invariant accesses that will be hoisted and
3851 // that would allow to make a non-affine access affine.
Michael Kruse7bf39442015-09-10 12:46:52 +00003852 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
Johannes Doerfert09e36972015-10-07 20:17:36 +00003853 buildMemoryAccess(Inst, L, &R, BoxedLoops, ScopRIL);
Michael Kruse7bf39442015-09-10 12:46:52 +00003854
3855 if (isIgnoredIntrinsic(Inst))
3856 continue;
3857
Johannes Doerfert09e36972015-10-07 20:17:36 +00003858 // Do not build scalar dependences for required invariant loads as we will
3859 // hoist them later on anyway or drop the SCoP if we cannot.
3860 if (ScopRIL.count(dyn_cast<LoadInst>(Inst)))
3861 continue;
3862
Michael Kruse7bf39442015-09-10 12:46:52 +00003863 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00003864 if (!isa<StoreInst>(Inst))
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003865 addScalarWriteAccess(Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003866 }
3867 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003868}
Michael Kruse7bf39442015-09-10 12:46:52 +00003869
Michael Kruse2d0ece92015-09-24 11:41:21 +00003870void ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3871 MemoryAccess::AccessType Type,
3872 Value *BaseAddress, unsigned ElemBytes,
3873 bool Affine, Value *AccessValue,
3874 ArrayRef<const SCEV *> Subscripts,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003875 ArrayRef<const SCEV *> Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00003876 ScopArrayInfo::MemoryKind Kind) {
Michael Krusecac948e2015-10-02 13:53:07 +00003877 ScopStmt *Stmt = scop->getStmtForBasicBlock(BB);
3878
3879 // Do not create a memory access for anything not in the SCoP. It would be
3880 // ignored anyway.
3881 if (!Stmt)
3882 return;
3883
Michael Krusee2bccbb2015-09-18 19:59:43 +00003884 AccFuncSetType &AccList = AccFuncMap[BB];
Michael Krusee2bccbb2015-09-18 19:59:43 +00003885 Value *BaseAddr = BaseAddress;
3886 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3887
Michael Kruseb06e3022015-12-13 22:10:32 +00003888 // The execution of a store is not guaranteed if not in the entry block of a
3889 // subregion. However, scalar writes (llvm::Value definitions or one of a
3890 // PHI's incoming values) must occur in well-formed IR code.
3891 bool isApproximated = (Kind == ScopArrayInfo::MK_Array) &&
3892 Stmt->isRegionStmt() &&
3893 (Stmt->getRegion()->getEntry() != BB);
Michael Krusecac948e2015-10-02 13:53:07 +00003894 if (isApproximated && Type == MemoryAccess::MUST_WRITE)
3895 Type = MemoryAccess::MAY_WRITE;
3896
Tobias Grosserf1bfd752015-11-05 20:15:37 +00003897 AccList.emplace_back(Stmt, Inst, Type, BaseAddress, ElemBytes, Affine,
Tobias Grossera535dff2015-12-13 19:59:01 +00003898 Subscripts, Sizes, AccessValue, Kind, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00003899 Stmt->addAccess(&AccList.back());
Michael Kruse7bf39442015-09-10 12:46:52 +00003900}
3901
Tobias Grossera535dff2015-12-13 19:59:01 +00003902void ScopInfo::addArrayAccess(Instruction *MemAccInst,
3903 MemoryAccess::AccessType Type, Value *BaseAddress,
3904 unsigned ElemBytes, bool IsAffine,
3905 ArrayRef<const SCEV *> Subscripts,
3906 ArrayRef<const SCEV *> Sizes,
3907 Value *AccessValue) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003908 assert(isa<LoadInst>(MemAccInst) || isa<StoreInst>(MemAccInst));
3909 assert(isa<LoadInst>(MemAccInst) == (Type == MemoryAccess::READ));
3910 addMemoryAccess(MemAccInst->getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003911 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00003912 ScopArrayInfo::MK_Array);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003913}
3914void ScopInfo::addScalarWriteAccess(Instruction *Value) {
3915 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
3916 true, Value, ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00003917 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003918}
3919void ScopInfo::addScalarReadAccess(Value *Value, Instruction *User) {
3920 assert(!isa<PHINode>(User));
3921 addMemoryAccess(User->getParent(), User, MemoryAccess::READ, Value, 1, true,
3922 Value, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00003923 ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003924}
3925void ScopInfo::addScalarReadAccess(Value *Value, PHINode *User,
3926 BasicBlock *UserBB) {
3927 addMemoryAccess(UserBB, User, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003928 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00003929 ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003930}
3931void ScopInfo::addPHIWriteAccess(PHINode *PHI, BasicBlock *IncomingBlock,
3932 Value *IncomingValue, bool IsExitBlock) {
3933 addMemoryAccess(IncomingBlock, IncomingBlock->getTerminator(),
3934 MemoryAccess::MUST_WRITE, PHI, 1, true, IncomingValue,
3935 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00003936 IsExitBlock ? ScopArrayInfo::MK_ExitPHI
3937 : ScopArrayInfo::MK_PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003938}
3939void ScopInfo::addPHIReadAccess(PHINode *PHI) {
3940 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003941 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00003942 ScopArrayInfo::MK_PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003943}
3944
Michael Krusedaf66942015-12-13 22:10:37 +00003945void ScopInfo::buildScop(Region &R, AssumptionCache &AC) {
Michael Kruse9d080092015-09-11 21:41:48 +00003946 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Michael Krusedaf66942015-12-13 22:10:37 +00003947 scop = new Scop(R, AccFuncMap, *SD, *SE, *DT, *LI, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00003948
Michael Krusecac948e2015-10-02 13:53:07 +00003949 buildStmts(R);
Michael Kruse7bf39442015-09-10 12:46:52 +00003950 buildAccessFunctions(R, R);
3951
3952 // In case the region does not have an exiting block we will later (during
3953 // code generation) split the exit block. This will move potential PHI nodes
3954 // from the current exit block into the new region exiting block. Hence, PHI
3955 // nodes that are at this point not part of the region will be.
3956 // To handle these PHI nodes later we will now model their operands as scalar
3957 // accesses. Note that we do not model anything in the exit block if we have
3958 // an exiting block in the region, as there will not be any splitting later.
3959 if (!R.getExitingBlock())
3960 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
3961
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003962 scop->init(*AA, AC);
Michael Kruse7bf39442015-09-10 12:46:52 +00003963}
3964
Michael Krused868b5d2015-09-10 15:25:24 +00003965void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00003966 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00003967 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00003968 return;
3969 }
3970
Michael Kruse9d080092015-09-11 21:41:48 +00003971 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00003972}
3973
Michael Krused868b5d2015-09-10 15:25:24 +00003974void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00003975 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00003976 if (scop) {
3977 delete scop;
3978 scop = 0;
3979 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003980}
3981
3982//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00003983ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00003984 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00003985 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00003986}
3987
3988ScopInfo::~ScopInfo() {
3989 clear();
3990 isl_ctx_free(ctx);
3991}
3992
Tobias Grosser75805372011-04-29 06:27:02 +00003993void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00003994 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00003995 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00003996 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00003997 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
3998 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003999 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004000 AU.addRequired<AssumptionCacheTracker>();
Tobias Grosser75805372011-04-29 06:27:02 +00004001 AU.setPreservesAll();
4002}
4003
4004bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00004005 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00004006
Michael Krused868b5d2015-09-10 15:25:24 +00004007 if (!SD->isMaxRegionInScop(*R))
4008 return false;
4009
4010 Function *F = R->getEntry()->getParent();
4011 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4012 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4013 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
4014 TD = &F->getParent()->getDataLayout();
Michael Krusedaf66942015-12-13 22:10:37 +00004015 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004016 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krused868b5d2015-09-10 15:25:24 +00004017
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004018 DebugLoc Beg, End;
4019 getDebugLocations(R, Beg, End);
4020 std::string Msg = "SCoP begins here.";
4021 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg);
4022
Michael Krusedaf66942015-12-13 22:10:37 +00004023 buildScop(*R, AC);
Tobias Grosser75805372011-04-29 06:27:02 +00004024
Tobias Grosserd6a50b32015-05-30 06:26:21 +00004025 DEBUG(scop->print(dbgs()));
4026
Michael Kruseafe06702015-10-02 16:33:27 +00004027 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004028 Msg = "SCoP ends here but was dismissed.";
Johannes Doerfert43788c52015-08-20 05:58:56 +00004029 delete scop;
4030 scop = nullptr;
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004031 } else {
4032 Msg = "SCoP ends here.";
4033 ++ScopFound;
4034 if (scop->getMaxLoopDepth() > 0)
4035 ++RichScopFound;
Johannes Doerfert43788c52015-08-20 05:58:56 +00004036 }
4037
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004038 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg);
4039
Tobias Grosser75805372011-04-29 06:27:02 +00004040 return false;
4041}
4042
4043char ScopInfo::ID = 0;
4044
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004045Pass *polly::createScopInfoPass() { return new ScopInfo(); }
4046
Tobias Grosser73600b82011-10-08 00:30:40 +00004047INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
4048 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004049 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004050INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004051INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004052INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004053INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004054INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004055INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004056INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00004057INITIALIZE_PASS_END(ScopInfo, "polly-scops",
4058 "Polly - Create polyhedral description of Scops", false,
4059 false)