blob: 8f98aa5dde6e7e081c38950671ff27ffc0e534fb [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 Grosser5624d3c2015-12-21 12:38:56 +000020#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000021#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000022#include "polly/Options.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
Tobias Grosser75dc40c2015-12-20 13:31:48 +000065// The maximal number of basic sets we allow during domain construction to
66// be created. More complex scops will result in very high compile time and
67// are also unlikely to result in good code
68static int const MaxConjunctsInDomain = 20;
69
Michael Kruse7bf39442015-09-10 12:46:52 +000070static cl::opt<bool> ModelReadOnlyScalars(
71 "polly-analyze-read-only-scalars",
72 cl::desc("Model read-only scalar values in the scop description"),
73 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
74
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000075// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000076// operations can overflow easily. Additive reductions and bit operations
77// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000078static cl::opt<bool> DisableMultiplicativeReductions(
79 "polly-disable-multiplicative-reductions",
80 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
81 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000082
Johannes Doerfert9143d672014-09-27 11:02:39 +000083static cl::opt<unsigned> RunTimeChecksMaxParameters(
84 "polly-rtc-max-parameters",
85 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
86 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
87
Tobias Grosser71500722015-03-28 15:11:14 +000088static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
89 "polly-rtc-max-arrays-per-group",
90 cl::desc("The maximal number of arrays to compare in each alias group."),
91 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000092static cl::opt<std::string> UserContextStr(
93 "polly-context", cl::value_desc("isl parameter set"),
94 cl::desc("Provide additional constraints on the context parameters"),
95 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000096
Tobias Grosserd83b8a82015-08-20 19:08:11 +000097static cl::opt<bool> DetectReductions("polly-detect-reductions",
98 cl::desc("Detect and exploit reductions"),
99 cl::Hidden, cl::ZeroOrMore,
100 cl::init(true), cl::cat(PollyCategory));
101
Tobias Grosser20a4c0c2015-11-11 16:22:36 +0000102static cl::opt<int> MaxDisjunctsAssumed(
103 "polly-max-disjuncts-assumed",
104 cl::desc("The maximal number of disjuncts we allow in the assumption "
105 "context (this bounds compile time)"),
106 cl::Hidden, cl::ZeroOrMore, cl::init(150), cl::cat(PollyCategory));
107
Tobias Grosser4927c8e2015-11-24 12:50:02 +0000108static cl::opt<bool> IgnoreIntegerWrapping(
109 "polly-ignore-integer-wrapping",
110 cl::desc("Do not build run-time checks to proof absence of integer "
111 "wrapping"),
112 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
113
Michael Kruse7bf39442015-09-10 12:46:52 +0000114//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000115
Michael Kruse046dde42015-08-10 13:01:57 +0000116// Create a sequence of two schedules. Either argument may be null and is
117// interpreted as the empty schedule. Can also return null if both schedules are
118// empty.
119static __isl_give isl_schedule *
120combineInSequence(__isl_take isl_schedule *Prev,
121 __isl_take isl_schedule *Succ) {
122 if (!Prev)
123 return Succ;
124 if (!Succ)
125 return Prev;
126
127 return isl_schedule_sequence(Prev, Succ);
128}
129
Johannes Doerferte7044942015-02-24 11:58:30 +0000130static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
131 const ConstantRange &Range,
132 int dim,
133 enum isl_dim_type type) {
134 isl_val *V;
135 isl_ctx *ctx = isl_set_get_ctx(S);
136
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000137 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
138 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000139 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000140 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
141
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000142 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000143 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000144 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000145 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000146 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
147
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000148 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000149 return isl_set_union(SLB, SUB);
150 else
151 return isl_set_intersect(SLB, SUB);
152}
153
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000154static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
155 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
156 if (!BasePtrLI)
157 return nullptr;
158
159 if (!S->getRegion().contains(BasePtrLI))
160 return nullptr;
161
162 ScalarEvolution &SE = *S->getSE();
163
164 auto *OriginBaseSCEV =
165 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
166 if (!OriginBaseSCEV)
167 return nullptr;
168
169 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
170 if (!OriginBaseSCEVUnknown)
171 return nullptr;
172
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000173 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grossera535dff2015-12-13 19:59:01 +0000174 ScopArrayInfo::MK_Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000175}
176
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000177ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grossera535dff2015-12-13 19:59:01 +0000178 ArrayRef<const SCEV *> Sizes, enum MemoryKind Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000179 const DataLayout &DL, Scop *S)
180 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000181 std::string BasePtrName =
Tobias Grossera535dff2015-12-13 19:59:01 +0000182 getIslCompatibleName("MemRef_", BasePtr, Kind == MK_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000183 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000184
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000185 updateSizes(Sizes);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000186 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
187 if (BasePtrOriginSAI)
188 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000189}
190
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000191__isl_give isl_space *ScopArrayInfo::getSpace() const {
192 auto Space =
193 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
194 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
195 return Space;
196}
197
Tobias Grosser8286b832015-11-02 11:29:32 +0000198bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000199 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
200 int ExtraDimsNew = NewSizes.size() - SharedDims;
201 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Tobias Grosser8286b832015-11-02 11:29:32 +0000202 for (int i = 0; i < SharedDims; i++)
203 if (NewSizes[i + ExtraDimsNew] != DimensionSizes[i + ExtraDimsOld])
204 return false;
205
206 if (DimensionSizes.size() >= NewSizes.size())
207 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000208
209 DimensionSizes.clear();
210 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
211 NewSizes.end());
212 for (isl_pw_aff *Size : DimensionSizesPw)
213 isl_pw_aff_free(Size);
214 DimensionSizesPw.clear();
215 for (const SCEV *Expr : DimensionSizes) {
216 isl_pw_aff *Size = S.getPwAff(Expr);
217 DimensionSizesPw.push_back(Size);
218 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000219 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000220}
221
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000222ScopArrayInfo::~ScopArrayInfo() {
223 isl_id_free(Id);
224 for (isl_pw_aff *Size : DimensionSizesPw)
225 isl_pw_aff_free(Size);
226}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000227
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000228std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
229
230int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000231 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000232}
233
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000234isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
235
236void ScopArrayInfo::dump() const { print(errs()); }
237
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000238void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000239 OS.indent(8) << *getElementType() << " " << getName();
240 if (getNumberOfDimensions() > 0)
241 OS << "[*]";
Tobias Grosser26253842015-11-10 14:24:21 +0000242 for (unsigned u = 1; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000243 OS << "[";
244
Tobias Grosser26253842015-11-10 14:24:21 +0000245 if (SizeAsPwAff) {
246 auto Size = getDimensionSizePw(u);
247 OS << " " << Size << " ";
248 isl_pw_aff_free(Size);
249 } else {
250 OS << *getDimensionSize(u);
251 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000252
253 OS << "]";
254 }
255
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000256 OS << ";";
257
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000258 if (BasePtrOriginSAI)
259 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
260
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000261 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000262}
263
264const ScopArrayInfo *
265ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
266 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
267 assert(Id && "Output dimension didn't have an ID");
268 return getFromId(Id);
269}
270
271const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
272 void *User = isl_id_get_user(Id);
273 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
274 isl_id_free(Id);
275 return SAI;
276}
277
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000278void MemoryAccess::updateDimensionality() {
279 auto ArraySpace = getScopArrayInfo()->getSpace();
280 auto AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
281
282 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
283 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
284 auto DimsMissing = DimsArray - DimsAccess;
285
286 auto Map = isl_map_from_domain_and_range(isl_set_universe(AccessSpace),
287 isl_set_universe(ArraySpace));
288
289 for (unsigned i = 0; i < DimsMissing; i++)
290 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
291
292 for (unsigned i = DimsMissing; i < DimsArray; i++)
293 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
294
295 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000296
297 assumeNoOutOfBound();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000298}
299
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000300const std::string
301MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
302 switch (RT) {
303 case MemoryAccess::RT_NONE:
304 llvm_unreachable("Requested a reduction operator string for a memory "
305 "access which isn't a reduction");
306 case MemoryAccess::RT_ADD:
307 return "+";
308 case MemoryAccess::RT_MUL:
309 return "*";
310 case MemoryAccess::RT_BOR:
311 return "|";
312 case MemoryAccess::RT_BXOR:
313 return "^";
314 case MemoryAccess::RT_BAND:
315 return "&";
316 }
317 llvm_unreachable("Unknown reduction type");
318 return "";
319}
320
Johannes Doerfertf6183392014-07-01 20:52:51 +0000321/// @brief Return the reduction type for a given binary operator
322static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
323 const Instruction *Load) {
324 if (!BinOp)
325 return MemoryAccess::RT_NONE;
326 switch (BinOp->getOpcode()) {
327 case Instruction::FAdd:
328 if (!BinOp->hasUnsafeAlgebra())
329 return MemoryAccess::RT_NONE;
330 // Fall through
331 case Instruction::Add:
332 return MemoryAccess::RT_ADD;
333 case Instruction::Or:
334 return MemoryAccess::RT_BOR;
335 case Instruction::Xor:
336 return MemoryAccess::RT_BXOR;
337 case Instruction::And:
338 return MemoryAccess::RT_BAND;
339 case Instruction::FMul:
340 if (!BinOp->hasUnsafeAlgebra())
341 return MemoryAccess::RT_NONE;
342 // Fall through
343 case Instruction::Mul:
344 if (DisableMultiplicativeReductions)
345 return MemoryAccess::RT_NONE;
346 return MemoryAccess::RT_MUL;
347 default:
348 return MemoryAccess::RT_NONE;
349 }
350}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000351
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000352/// @brief Derive the individual index expressions from a GEP instruction
353///
354/// This function optimistically assumes the GEP references into a fixed size
355/// array. If this is actually true, this function returns a list of array
356/// subscript expressions as SCEV as well as a list of integers describing
357/// the size of the individual array dimensions. Both lists have either equal
358/// length of the size list is one element shorter in case there is no known
359/// size available for the outermost array dimension.
360///
361/// @param GEP The GetElementPtr instruction to analyze.
362///
363/// @return A tuple with the subscript expressions and the dimension sizes.
364static std::tuple<std::vector<const SCEV *>, std::vector<int>>
365getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
366 std::vector<const SCEV *> Subscripts;
367 std::vector<int> Sizes;
368
369 Type *Ty = GEP->getPointerOperandType();
370
371 bool DroppedFirstDim = false;
372
Michael Kruse26ed65e2015-09-24 17:32:49 +0000373 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000374
375 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
376
377 if (i == 1) {
378 if (auto PtrTy = dyn_cast<PointerType>(Ty)) {
379 Ty = PtrTy->getElementType();
380 } else if (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
381 Ty = ArrayTy->getElementType();
382 } else {
383 Subscripts.clear();
384 Sizes.clear();
385 break;
386 }
387 if (auto Const = dyn_cast<SCEVConstant>(Expr))
388 if (Const->getValue()->isZero()) {
389 DroppedFirstDim = true;
390 continue;
391 }
392 Subscripts.push_back(Expr);
393 continue;
394 }
395
396 auto ArrayTy = dyn_cast<ArrayType>(Ty);
397 if (!ArrayTy) {
398 Subscripts.clear();
399 Sizes.clear();
400 break;
401 }
402
403 Subscripts.push_back(Expr);
404 if (!(DroppedFirstDim && i == 2))
405 Sizes.push_back(ArrayTy->getNumElements());
406
407 Ty = ArrayTy->getElementType();
408 }
409
410 return std::make_tuple(Subscripts, Sizes);
411}
412
Tobias Grosser75805372011-04-29 06:27:02 +0000413MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000414 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000415 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000416 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000417}
418
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000419const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
420 isl_id *ArrayId = getArrayId();
421 void *User = isl_id_get_user(ArrayId);
422 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
423 isl_id_free(ArrayId);
424 return SAI;
425}
426
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000427__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000428 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
429}
430
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000431__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
432 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000433 isl_map *Schedule, *ScheduledAccRel;
434 isl_union_set *UDomain;
435
436 UDomain = isl_union_set_from_set(getStatement()->getDomain());
437 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
438 Schedule = isl_map_from_union_map(USchedule);
439 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
440 return isl_pw_multi_aff_from_map(ScheduledAccRel);
441}
442
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000443__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000444 return isl_map_copy(AccessRelation);
445}
446
Johannes Doerferta99130f2014-10-13 12:58:03 +0000447std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000448 return stringFromIslObj(AccessRelation);
449}
450
Johannes Doerferta99130f2014-10-13 12:58:03 +0000451__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000452 return isl_map_get_space(AccessRelation);
453}
454
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000455__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000456 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000457}
458
Tobias Grosser6f730082015-09-05 07:46:47 +0000459std::string MemoryAccess::getNewAccessRelationStr() const {
460 return stringFromIslObj(NewAccessRelation);
461}
462
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000463__isl_give isl_basic_map *
464MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000465 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000466 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000467
Tobias Grosser084d8f72012-05-29 09:29:44 +0000468 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000469 isl_basic_set_universe(Statement->getDomainSpace()),
470 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000471}
472
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000473// Formalize no out-of-bound access assumption
474//
475// When delinearizing array accesses we optimistically assume that the
476// delinearized accesses do not access out of bound locations (the subscript
477// expression of each array evaluates for each statement instance that is
478// executed to a value that is larger than zero and strictly smaller than the
479// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000480// dimension for which we do not need to assume any upper bound. At this point
481// we formalize this assumption to ensure that at code generation time the
482// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000483//
484// To find the set of constraints necessary to avoid out of bound accesses, we
485// first build the set of data locations that are not within array bounds. We
486// then apply the reverse access relation to obtain the set of iterations that
487// may contain invalid accesses and reduce this set of iterations to the ones
488// that are actually executed by intersecting them with the domain of the
489// statement. If we now project out all loop dimensions, we obtain a set of
490// parameters that may cause statement instances to be executed that may
491// possibly yield out of bound memory accesses. The complement of these
492// constraints is the set of constraints that needs to be assumed to ensure such
493// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000494void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000495 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000496 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000497 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000498 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
499 isl_pw_aff *Var =
500 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
501 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
502
503 isl_set *DimOutside;
504
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000505 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Roman Gareev10595a12016-01-08 14:01:59 +0000506 isl_pw_aff *SizeE = getScopArrayInfo()->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000507 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
508 isl_space_dim(Space, isl_dim_set));
509 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
510 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000511
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000512 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000513
514 Outside = isl_set_union(Outside, DimOutside);
515 }
516
517 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
518 Outside = isl_set_intersect(Outside, Statement->getDomain());
519 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000520
521 // Remove divs to avoid the construction of overly complicated assumptions.
522 // Doing so increases the set of parameter combinations that are assumed to
523 // not appear. This is always save, but may make the resulting run-time check
524 // bail out more often than strictly necessary.
525 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000526 Outside = isl_set_complement(Outside);
Michael Krusead28e5a2016-01-26 13:33:15 +0000527 Statement->getParent()->addAssumption(
528 INBOUNDS, Outside,
529 getAccessInstruction() ? getAccessInstruction()->getDebugLoc() : nullptr);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000530 isl_space_free(Space);
531}
532
Johannes Doerferte7044942015-02-24 11:58:30 +0000533void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
534 ScalarEvolution *SE = Statement->getParent()->getSE();
535
Michael Kruse70131d32016-01-27 17:09:17 +0000536 Value *Ptr = MemAccInst(getAccessInstruction()).getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000537 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
538 return;
539
540 auto *PtrSCEV = SE->getSCEV(Ptr);
541 if (isa<SCEVCouldNotCompute>(PtrSCEV))
542 return;
543
544 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
545 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
546 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
547
548 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
549 if (Range.isFullSet())
550 return;
551
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000552 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000553 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000554 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
555 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
556
557 auto Min = LB.sdiv(APInt(BW, ElementSize));
558 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000559
560 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
561 AccessRange =
562 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
563 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
564}
565
Michael Krusee2bccbb2015-09-18 19:59:43 +0000566__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000567 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000568 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000569
570 for (int i = Size - 2; i >= 0; --i) {
571 isl_space *Space;
572 isl_map *MapOne, *MapTwo;
Michael Krusee2bccbb2015-09-18 19:59:43 +0000573 isl_pw_aff *DimSize = Statement->getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000574
575 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
576 isl_pw_aff_free(DimSize);
577 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
578
579 Space = isl_map_get_space(AccessRelation);
580 Space = isl_space_map_from_set(isl_space_range(Space));
581 Space = isl_space_align_params(Space, SpaceSize);
582
583 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
584 isl_id_free(ParamId);
585
586 MapOne = isl_map_universe(isl_space_copy(Space));
587 for (int j = 0; j < Size; ++j)
588 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
589 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
590
591 MapTwo = isl_map_universe(isl_space_copy(Space));
592 for (int j = 0; j < Size; ++j)
593 if (j < i || j > i + 1)
594 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
595
596 isl_local_space *LS = isl_local_space_from_space(Space);
597 isl_constraint *C;
598 C = isl_equality_alloc(isl_local_space_copy(LS));
599 C = isl_constraint_set_constant_si(C, -1);
600 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
601 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
602 MapTwo = isl_map_add_constraint(MapTwo, C);
603 C = isl_equality_alloc(LS);
604 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
605 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
606 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
607 MapTwo = isl_map_add_constraint(MapTwo, C);
608 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
609
610 MapOne = isl_map_union(MapOne, MapTwo);
611 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
612 }
613 return AccessRelation;
614}
615
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000616/// @brief Check if @p Expr is divisible by @p Size.
617static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
618
619 // Only one factor needs to be divisible.
620 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
621 for (auto *FactorExpr : MulExpr->operands())
622 if (isDivisible(FactorExpr, Size, SE))
623 return true;
624 return false;
625 }
626
627 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
628 // to be divisble.
629 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
630 for (auto *OpExpr : NAryExpr->operands())
631 if (!isDivisible(OpExpr, Size, SE))
632 return false;
633 return true;
634 }
635
636 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
637 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
638 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
639 return MulSCEV == Expr;
640}
641
Michael Krusee2bccbb2015-09-18 19:59:43 +0000642void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
643 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000644
Michael Krusee2bccbb2015-09-18 19:59:43 +0000645 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000646 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000647
Michael Krusee2bccbb2015-09-18 19:59:43 +0000648 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000649 // We overapproximate non-affine accesses with a possible access to the
650 // whole array. For read accesses it does not make a difference, if an
651 // access must or may happen. However, for write accesses it is important to
652 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000653 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000654 AccessRelation =
655 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000656
Michael Krusee2bccbb2015-09-18 19:59:43 +0000657 computeBoundsOnAccessRelation(getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000658 return;
659 }
660
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000661 Scop &S = *getStatement()->getParent();
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000662 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000663 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000664
Michael Krusee2bccbb2015-09-18 19:59:43 +0000665 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
666 isl_pw_aff *Affine = Statement->getPwAff(Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000667
Sebastian Pop422e33f2014-06-03 18:16:31 +0000668 if (Size == 1) {
669 // For the non delinearized arrays, divide the access function of the last
670 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000671 //
672 // A stride one array access in C expressed as A[i] is expressed in
673 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
674 // two subsequent values of 'i' index two values that are stored next to
675 // each other in memory. By this division we make this characteristic
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000676 // obvious again. However, if the index is not divisible by the element
677 // size we will bail out.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000678 isl_val *v = isl_val_int_from_si(Ctx, getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000679 Affine = isl_pw_aff_scale_down_val(Affine, v);
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000680
681 if (!isDivisible(Subscripts[0], getElemSizeInBytes(), *S.getSE()))
Tobias Grosser8d4f6262015-12-12 09:52:26 +0000682 S.invalidate(ALIGNMENT, AccessInstruction->getDebugLoc());
Sebastian Pop18016682014-04-08 21:20:44 +0000683 }
684
685 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
686
Tobias Grosser79baa212014-04-10 08:38:02 +0000687 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000688 }
689
Michael Krusee2bccbb2015-09-18 19:59:43 +0000690 if (Sizes.size() > 1 && !isa<SCEVConstant>(Sizes[0]))
691 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000692
Tobias Grosser79baa212014-04-10 08:38:02 +0000693 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000694 AccessRelation = isl_map_set_tuple_id(
695 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000696 AccessRelation =
697 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
698
Tobias Grosseraa660a92015-03-30 00:07:50 +0000699 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000700 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000701}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000702
Michael Krusecac948e2015-10-02 13:53:07 +0000703MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000704 AccessType Type, Value *BaseAddress,
705 unsigned ElemBytes, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000706 ArrayRef<const SCEV *> Subscripts,
707 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000708 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
709 : Kind(Kind), AccType(Type), RedType(RT_NONE), Statement(Stmt),
Michael Krusecac948e2015-10-02 13:53:07 +0000710 BaseAddr(BaseAddress), BaseName(BaseName), ElemBytes(ElemBytes),
711 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
712 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000713 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000714 NewAccessRelation(nullptr) {
715
716 std::string IdName = "__polly_array_ref";
717 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
718}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000719
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000720void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000721 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000722 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000723}
724
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000725const std::string MemoryAccess::getReductionOperatorStr() const {
726 return MemoryAccess::getReductionOperatorStr(getReductionType());
727}
728
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000729__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
730
Johannes Doerfertf6183392014-07-01 20:52:51 +0000731raw_ostream &polly::operator<<(raw_ostream &OS,
732 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000733 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000734 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000735 else
736 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000737 return OS;
738}
739
Tobias Grosser75805372011-04-29 06:27:02 +0000740void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000741 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000742 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000743 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000744 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000745 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000746 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000747 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000748 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000749 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000750 break;
751 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000752 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000753 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000754 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000755 if (hasNewAccessRelation())
756 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000757}
758
Tobias Grosser74394f02013-01-14 22:40:23 +0000759void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000760
761// Create a map in the size of the provided set domain, that maps from the
762// one element of the provided set domain to another element of the provided
763// set domain.
764// The mapping is limited to all points that are equal in all but the last
765// dimension and for which the last dimension of the input is strict smaller
766// than the last dimension of the output.
767//
768// getEqualAndLarger(set[i0, i1, ..., iX]):
769//
770// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
771// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
772//
Tobias Grosserf5338802011-10-06 00:03:35 +0000773static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000774 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000775 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000776 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000777
778 // Set all but the last dimension to be equal for the input and output
779 //
780 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
781 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000782 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000783 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000784
785 // Set the last dimension of the input to be strict smaller than the
786 // last dimension of the output.
787 //
788 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000789 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
790 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000791 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000792}
793
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000794__isl_give isl_set *
795MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000796 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000797 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000798 isl_space *Space = isl_space_range(isl_map_get_space(S));
799 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000800
Sebastian Popa00a0292012-12-18 07:46:06 +0000801 S = isl_map_reverse(S);
802 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000803
Sebastian Popa00a0292012-12-18 07:46:06 +0000804 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
805 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
806 NextScatt = isl_map_apply_domain(NextScatt, S);
807 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000808
Sebastian Popa00a0292012-12-18 07:46:06 +0000809 isl_set *Deltas = isl_map_deltas(NextScatt);
810 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000811}
812
Sebastian Popa00a0292012-12-18 07:46:06 +0000813bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000814 int StrideWidth) const {
815 isl_set *Stride, *StrideX;
816 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000817
Sebastian Popa00a0292012-12-18 07:46:06 +0000818 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000819 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000820 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
821 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
822 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
823 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000824 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000825
Tobias Grosser28dd4862012-01-24 16:42:16 +0000826 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000827 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000828
Tobias Grosser28dd4862012-01-24 16:42:16 +0000829 return IsStrideX;
830}
831
Sebastian Popa00a0292012-12-18 07:46:06 +0000832bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
833 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000834}
835
Sebastian Popa00a0292012-12-18 07:46:06 +0000836bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
837 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000838}
839
Tobias Grosser166c4222015-09-05 07:46:40 +0000840void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
841 isl_map_free(NewAccessRelation);
842 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000843}
Tobias Grosser75805372011-04-29 06:27:02 +0000844
845//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000846
Tobias Grosser808cd692015-07-14 09:33:13 +0000847isl_map *ScopStmt::getSchedule() const {
848 isl_set *Domain = getDomain();
849 if (isl_set_is_empty(Domain)) {
850 isl_set_free(Domain);
851 return isl_map_from_aff(
852 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
853 }
854 auto *Schedule = getParent()->getSchedule();
855 Schedule = isl_union_map_intersect_domain(
856 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
857 if (isl_union_map_is_empty(Schedule)) {
858 isl_set_free(Domain);
859 isl_union_map_free(Schedule);
860 return isl_map_from_aff(
861 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
862 }
863 auto *M = isl_map_from_union_map(Schedule);
864 M = isl_map_coalesce(M);
865 M = isl_map_gist_domain(M, Domain);
866 M = isl_map_coalesce(M);
867 return M;
868}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000869
Johannes Doerfert574182d2015-08-12 10:19:50 +0000870__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000871 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
872 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000873}
874
Tobias Grosser37eb4222014-02-20 21:43:54 +0000875void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
876 assert(isl_set_is_subset(NewDomain, Domain) &&
877 "New domain is not a subset of old domain!");
878 isl_set_free(Domain);
879 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000880}
881
Michael Krusecac948e2015-10-02 13:53:07 +0000882void ScopStmt::buildAccessRelations() {
883 for (MemoryAccess *Access : MemAccs) {
884 Type *ElementType = Access->getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000885
Tobias Grossera535dff2015-12-13 19:59:01 +0000886 ScopArrayInfo::MemoryKind Ty;
887 if (Access->isPHIKind())
888 Ty = ScopArrayInfo::MK_PHI;
889 else if (Access->isExitPHIKind())
890 Ty = ScopArrayInfo::MK_ExitPHI;
891 else if (Access->isValueKind())
892 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000893 else
Tobias Grossera535dff2015-12-13 19:59:01 +0000894 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000895
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000896 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000897 Access->getBaseAddr(), ElementType, Access->Sizes, Ty);
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000898
Michael Krusecac948e2015-10-02 13:53:07 +0000899 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +0000900 }
901}
902
Michael Krusecac948e2015-10-02 13:53:07 +0000903void ScopStmt::addAccess(MemoryAccess *Access) {
904 Instruction *AccessInst = Access->getAccessInstruction();
905
Michael Kruse58fa3bb2015-12-22 23:25:11 +0000906 if (Access->isArrayKind()) {
907 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
908 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +0000909 } else if (Access->isValueKind() && Access->isWrite()) {
910 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
911 assert(Parent.getStmtForBasicBlock(AccessVal->getParent()) == this);
912 assert(!ValueWrites.lookup(AccessVal));
913
914 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +0000915 } else if (Access->isValueKind() && Access->isRead()) {
916 Value *AccessVal = Access->getAccessValue();
917 assert(!ValueReads.lookup(AccessVal));
918
919 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +0000920 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
921 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
922 assert(!PHIWrites.lookup(PHI));
923
924 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +0000925 }
926
927 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +0000928}
929
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000930void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000931 for (MemoryAccess *MA : *this)
932 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000933
934 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000935}
936
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000937/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
938static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
939 void *User) {
940 isl_set **BoundedParts = static_cast<isl_set **>(User);
941 if (isl_basic_set_is_bounded(BSet))
942 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
943 else
944 isl_basic_set_free(BSet);
945 return isl_stat_ok;
946}
947
948/// @brief Return the bounded parts of @p S.
949static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
950 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
951 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
952 isl_set_free(S);
953 return BoundedParts;
954}
955
956/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
957///
958/// @returns A separation of @p S into first an unbounded then a bounded subset,
959/// both with regards to the dimension @p Dim.
960static std::pair<__isl_give isl_set *, __isl_give isl_set *>
961partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
962
963 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000964 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000965
966 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000967 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000968
969 // Remove dimensions that are greater than Dim as they are not interesting.
970 assert(NumDimsS >= Dim + 1);
971 OnlyDimS =
972 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
973
974 // Create artificial parametric upper bounds for dimensions smaller than Dim
975 // as we are not interested in them.
976 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
977 for (unsigned u = 0; u < Dim; u++) {
978 isl_constraint *C = isl_inequality_alloc(
979 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
980 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
981 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
982 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
983 }
984
985 // Collect all bounded parts of OnlyDimS.
986 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
987
988 // Create the dimensions greater than Dim again.
989 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
990 NumDimsS - Dim - 1);
991
992 // Remove the artificial upper bound parameters again.
993 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
994
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000995 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000996 return std::make_pair(UnboundedParts, BoundedParts);
997}
998
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000999/// @brief Set the dimension Ids from @p From in @p To.
1000static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1001 __isl_take isl_set *To) {
1002 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1003 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1004 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1005 }
1006 return To;
1007}
1008
1009/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001010static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001011 __isl_take isl_pw_aff *L,
1012 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001013 switch (Pred) {
1014 case ICmpInst::ICMP_EQ:
1015 return isl_pw_aff_eq_set(L, R);
1016 case ICmpInst::ICMP_NE:
1017 return isl_pw_aff_ne_set(L, R);
1018 case ICmpInst::ICMP_SLT:
1019 return isl_pw_aff_lt_set(L, R);
1020 case ICmpInst::ICMP_SLE:
1021 return isl_pw_aff_le_set(L, R);
1022 case ICmpInst::ICMP_SGT:
1023 return isl_pw_aff_gt_set(L, R);
1024 case ICmpInst::ICMP_SGE:
1025 return isl_pw_aff_ge_set(L, R);
1026 case ICmpInst::ICMP_ULT:
1027 return isl_pw_aff_lt_set(L, R);
1028 case ICmpInst::ICMP_UGT:
1029 return isl_pw_aff_gt_set(L, R);
1030 case ICmpInst::ICMP_ULE:
1031 return isl_pw_aff_le_set(L, R);
1032 case ICmpInst::ICMP_UGE:
1033 return isl_pw_aff_ge_set(L, R);
1034 default:
1035 llvm_unreachable("Non integer predicate not supported");
1036 }
1037}
1038
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001039/// @brief Create the conditions under which @p L @p Pred @p R is true.
1040///
1041/// Helper function that will make sure the dimensions of the result have the
1042/// same isl_id's as the @p Domain.
1043static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1044 __isl_take isl_pw_aff *L,
1045 __isl_take isl_pw_aff *R,
1046 __isl_keep isl_set *Domain) {
1047 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1048 return setDimensionIds(Domain, ConsequenceCondSet);
1049}
1050
1051/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001052///
1053/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001054/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1055/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001056static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001057buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001058 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1059
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001060 Value *Condition = getConditionFromTerminator(SI);
1061 assert(Condition && "No condition for switch");
1062
1063 ScalarEvolution &SE = *S.getSE();
1064 BasicBlock *BB = SI->getParent();
1065 isl_pw_aff *LHS, *RHS;
1066 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
1067
1068 unsigned NumSuccessors = SI->getNumSuccessors();
1069 ConditionSets.resize(NumSuccessors);
1070 for (auto &Case : SI->cases()) {
1071 unsigned Idx = Case.getSuccessorIndex();
1072 ConstantInt *CaseValue = Case.getCaseValue();
1073
1074 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
1075 isl_set *CaseConditionSet =
1076 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1077 ConditionSets[Idx] = isl_set_coalesce(
1078 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1079 }
1080
1081 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1082 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1083 for (unsigned u = 2; u < NumSuccessors; u++)
1084 ConditionSetUnion =
1085 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1086 ConditionSets[0] = setDimensionIds(
1087 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1088
1089 S.markAsOptimized();
1090 isl_pw_aff_free(LHS);
1091}
1092
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001093/// @brief Build the conditions sets for the branch condition @p Condition in
1094/// the @p Domain.
1095///
1096/// This will fill @p ConditionSets with the conditions under which control
1097/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001098/// have as many elements as @p TI has successors. If @p TI is nullptr the
1099/// context under which @p Condition is true/false will be returned as the
1100/// new elements of @p ConditionSets.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001101static void
1102buildConditionSets(Scop &S, Value *Condition, TerminatorInst *TI, Loop *L,
1103 __isl_keep isl_set *Domain,
1104 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1105
1106 isl_set *ConsequenceCondSet = nullptr;
1107 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1108 if (CCond->isZero())
1109 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1110 else
1111 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1112 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1113 auto Opcode = BinOp->getOpcode();
1114 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1115
1116 buildConditionSets(S, BinOp->getOperand(0), TI, L, Domain, ConditionSets);
1117 buildConditionSets(S, BinOp->getOperand(1), TI, L, Domain, ConditionSets);
1118
1119 isl_set_free(ConditionSets.pop_back_val());
1120 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1121 isl_set_free(ConditionSets.pop_back_val());
1122 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1123
1124 if (Opcode == Instruction::And)
1125 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1126 else
1127 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1128 } else {
1129 auto *ICond = dyn_cast<ICmpInst>(Condition);
1130 assert(ICond &&
1131 "Condition of exiting branch was neither constant nor ICmp!");
1132
1133 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001134 BasicBlock *BB = TI ? TI->getParent() : nullptr;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001135 isl_pw_aff *LHS, *RHS;
1136 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1137 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
1138 ConsequenceCondSet =
1139 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1140 }
1141
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001142 // If no terminator was given we are only looking for parameter constraints
1143 // under which @p Condition is true/false.
1144 if (!TI)
1145 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
1146
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001147 assert(ConsequenceCondSet);
1148 isl_set *AlternativeCondSet =
1149 isl_set_complement(isl_set_copy(ConsequenceCondSet));
1150
1151 ConditionSets.push_back(isl_set_coalesce(
1152 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
1153 ConditionSets.push_back(isl_set_coalesce(
1154 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
1155}
1156
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001157/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1158///
1159/// This will fill @p ConditionSets with the conditions under which control
1160/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1161/// have as many elements as @p TI has successors.
1162static void
1163buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1164 __isl_keep isl_set *Domain,
1165 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1166
1167 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1168 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1169
1170 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1171
1172 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001173 ConditionSets.push_back(isl_set_copy(Domain));
1174 return;
1175 }
1176
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001177 Value *Condition = getConditionFromTerminator(TI);
1178 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001179
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001180 return buildConditionSets(S, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001181}
1182
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001183void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +00001184 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +00001185
Tobias Grosser084d8f72012-05-29 09:29:44 +00001186 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1187
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001188 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001189 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001190}
1191
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001192void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001193 isl_ctx *Ctx = Parent.getIslCtx();
1194 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1195 Type *Ty = GEP->getPointerOperandType();
1196 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001197 ScopDetection &SD = Parent.getSD();
1198
1199 // The set of loads that are required to be invariant.
1200 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001201
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001202 std::vector<const SCEV *> Subscripts;
1203 std::vector<int> Sizes;
1204
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001205 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001206
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001207 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001208 Ty = PtrTy->getElementType();
1209 }
1210
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001211 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001212
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001213 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001214
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001215 for (size_t i = 0; i < Sizes.size(); i++) {
1216 auto Expr = Subscripts[i + IndexOffset];
1217 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001218
Johannes Doerfert09e36972015-10-07 20:17:36 +00001219 InvariantLoadsSetTy AccessILS;
1220 if (!isAffineExpr(&Parent.getRegion(), Expr, SE, nullptr, &AccessILS))
1221 continue;
1222
1223 bool NonAffine = false;
1224 for (LoadInst *LInst : AccessILS)
1225 if (!ScopRIL.count(LInst))
1226 NonAffine = true;
1227
1228 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001229 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001230
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001231 isl_pw_aff *AccessOffset = getPwAff(Expr);
1232 AccessOffset =
1233 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001234
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001235 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1236 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001237
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001238 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1239 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1240 OutOfBound = isl_set_params(OutOfBound);
1241 isl_set *InBound = isl_set_complement(OutOfBound);
1242 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001243
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001244 // A => B == !A or B
1245 isl_set *InBoundIfExecuted =
1246 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001247
Roman Gareev10595a12016-01-08 14:01:59 +00001248 InBoundIfExecuted = isl_set_coalesce(InBoundIfExecuted);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001249 Parent.addAssumption(INBOUNDS, InBoundIfExecuted, GEP->getDebugLoc());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001250 }
1251
1252 isl_local_space_free(LSpace);
1253}
1254
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001255void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1256 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001257 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1258 deriveAssumptionsFromGEP(GEP);
1259}
1260
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001261void ScopStmt::collectSurroundingLoops() {
1262 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1263 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1264 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1265 isl_id_free(DimId);
1266 }
1267}
1268
Michael Kruse9d080092015-09-11 21:41:48 +00001269ScopStmt::ScopStmt(Scop &parent, Region &R)
Michael Krusecac948e2015-10-02 13:53:07 +00001270 : Parent(parent), Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001271
Tobias Grosser16c44032015-07-09 07:31:45 +00001272 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001273}
1274
Michael Kruse9d080092015-09-11 21:41:48 +00001275ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Michael Krusecac948e2015-10-02 13:53:07 +00001276 : Parent(parent), Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001277
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001278 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001279}
1280
1281void ScopStmt::init() {
1282 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001283
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001284 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001285 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001286 buildAccessRelations();
1287
1288 if (BB) {
1289 deriveAssumptions(BB);
1290 } else {
1291 for (BasicBlock *Block : R->blocks()) {
1292 deriveAssumptions(Block);
1293 }
1294 }
1295
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001296 if (DetectReductions)
1297 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001298}
1299
Johannes Doerferte58a0122014-06-27 20:31:28 +00001300/// @brief Collect loads which might form a reduction chain with @p StoreMA
1301///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001302/// Check if the stored value for @p StoreMA is a binary operator with one or
1303/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001304/// used only once (by @p StoreMA) and its load operands are also used only
1305/// once, we have found a possible reduction chain. It starts at an operand
1306/// load and includes the binary operator and @p StoreMA.
1307///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001308/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001309/// escape this block or into any other store except @p StoreMA.
1310void ScopStmt::collectCandiateReductionLoads(
1311 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1312 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1313 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001314 return;
1315
1316 // Skip if there is not one binary operator between the load and the store
1317 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001318 if (!BinOp)
1319 return;
1320
1321 // Skip if the binary operators has multiple uses
1322 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001323 return;
1324
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001325 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001326 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1327 return;
1328
Johannes Doerfert9890a052014-07-01 00:32:29 +00001329 // Skip if the binary operator is outside the current SCoP
1330 if (BinOp->getParent() != Store->getParent())
1331 return;
1332
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001333 // Skip if it is a multiplicative reduction and we disabled them
1334 if (DisableMultiplicativeReductions &&
1335 (BinOp->getOpcode() == Instruction::Mul ||
1336 BinOp->getOpcode() == Instruction::FMul))
1337 return;
1338
Johannes Doerferte58a0122014-06-27 20:31:28 +00001339 // Check the binary operator operands for a candidate load
1340 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1341 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1342 if (!PossibleLoad0 && !PossibleLoad1)
1343 return;
1344
1345 // A load is only a candidate if it cannot escape (thus has only this use)
1346 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001347 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001348 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001349 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001350 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001351 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001352}
1353
1354/// @brief Check for reductions in this ScopStmt
1355///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001356/// Iterate over all store memory accesses and check for valid binary reduction
1357/// like chains. For all candidates we check if they have the same base address
1358/// and there are no other accesses which overlap with them. The base address
1359/// check rules out impossible reductions candidates early. The overlap check,
1360/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001361/// guarantees that none of the intermediate results will escape during
1362/// execution of the loop nest. We basically check here that no other memory
1363/// access can access the same memory as the potential reduction.
1364void ScopStmt::checkForReductions() {
1365 SmallVector<MemoryAccess *, 2> Loads;
1366 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1367
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001368 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001369 // stores and collecting possible reduction loads.
1370 for (MemoryAccess *StoreMA : MemAccs) {
1371 if (StoreMA->isRead())
1372 continue;
1373
1374 Loads.clear();
1375 collectCandiateReductionLoads(StoreMA, Loads);
1376 for (MemoryAccess *LoadMA : Loads)
1377 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1378 }
1379
1380 // Then check each possible candidate pair.
1381 for (const auto &CandidatePair : Candidates) {
1382 bool Valid = true;
1383 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1384 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1385
1386 // Skip those with obviously unequal base addresses.
1387 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1388 isl_map_free(LoadAccs);
1389 isl_map_free(StoreAccs);
1390 continue;
1391 }
1392
1393 // And check if the remaining for overlap with other memory accesses.
1394 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1395 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1396 isl_set *AllAccs = isl_map_range(AllAccsRel);
1397
1398 for (MemoryAccess *MA : MemAccs) {
1399 if (MA == CandidatePair.first || MA == CandidatePair.second)
1400 continue;
1401
1402 isl_map *AccRel =
1403 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1404 isl_set *Accs = isl_map_range(AccRel);
1405
1406 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1407 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1408 Valid = Valid && isl_set_is_empty(OverlapAccs);
1409 isl_set_free(OverlapAccs);
1410 }
1411 }
1412
1413 isl_set_free(AllAccs);
1414 if (!Valid)
1415 continue;
1416
Johannes Doerfertf6183392014-07-01 20:52:51 +00001417 const LoadInst *Load =
1418 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1419 MemoryAccess::ReductionType RT =
1420 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1421
Johannes Doerferte58a0122014-06-27 20:31:28 +00001422 // If no overlapping access was found we mark the load and store as
1423 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001424 CandidatePair.first->markAsReductionLike(RT);
1425 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001426 }
Tobias Grosser75805372011-04-29 06:27:02 +00001427}
1428
Tobias Grosser74394f02013-01-14 22:40:23 +00001429std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001430
Tobias Grosser54839312015-04-21 11:37:25 +00001431std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001432 auto *S = getSchedule();
1433 auto Str = stringFromIslObj(S);
1434 isl_map_free(S);
1435 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001436}
1437
Tobias Grosser74394f02013-01-14 22:40:23 +00001438unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001439
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001440unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001441
Tobias Grosser75805372011-04-29 06:27:02 +00001442const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1443
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001444const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001445 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001446}
1447
Tobias Grosser74394f02013-01-14 22:40:23 +00001448isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001449
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001450__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001451
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001452__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001453 return isl_set_get_space(Domain);
1454}
1455
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001456__isl_give isl_id *ScopStmt::getDomainId() const {
1457 return isl_set_get_tuple_id(Domain);
1458}
Tobias Grossercd95b772012-08-30 11:49:38 +00001459
Tobias Grosser10120182015-12-16 16:14:03 +00001460ScopStmt::~ScopStmt() { isl_set_free(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001461
1462void ScopStmt::print(raw_ostream &OS) const {
1463 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001464 OS.indent(12) << "Domain :=\n";
1465
1466 if (Domain) {
1467 OS.indent(16) << getDomainStr() << ";\n";
1468 } else
1469 OS.indent(16) << "n/a\n";
1470
Tobias Grosser54839312015-04-21 11:37:25 +00001471 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001472
1473 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001474 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001475 } else
1476 OS.indent(16) << "n/a\n";
1477
Tobias Grosser083d3d32014-06-28 08:59:45 +00001478 for (MemoryAccess *Access : MemAccs)
1479 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001480}
1481
1482void ScopStmt::dump() const { print(dbgs()); }
1483
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001484void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001485 // Remove all memory accesses in @p InvMAs from this statement
1486 // together with all scalar accesses that were caused by them.
Michael Krusead28e5a2016-01-26 13:33:15 +00001487 // MK_Value READs have no access instruction, hence would not be removed by
1488 // this function. However, it is only used for invariant LoadInst accesses,
1489 // its arguments are always affine, hence synthesizable, and therefore there
1490 // are no MK_Value READ accesses to be removed.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001491 for (MemoryAccess *MA : InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001492 auto Predicate = [&](MemoryAccess *Acc) {
Tobias Grosser3a6ac9f2015-11-30 21:13:43 +00001493 return Acc->getAccessInstruction() == MA->getAccessInstruction();
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001494 };
1495 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1496 MemAccs.end());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001497 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001498 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001499}
1500
Tobias Grosser75805372011-04-29 06:27:02 +00001501//===----------------------------------------------------------------------===//
1502/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001503
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001504void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001505 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1506 isl_set_free(Context);
1507 Context = NewContext;
1508}
1509
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001510/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1511struct SCEVSensitiveParameterRewriter
1512 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1513 ValueToValueMap &VMap;
1514 ScalarEvolution &SE;
1515
1516public:
1517 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1518 : VMap(VMap), SE(SE) {}
1519
1520 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1521 ValueToValueMap &VMap) {
1522 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1523 return SSPR.visit(E);
1524 }
1525
1526 const SCEV *visit(const SCEV *E) {
1527 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1528 }
1529
1530 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1531
1532 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1533 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1534 }
1535
1536 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1537 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1538 }
1539
1540 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1541 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1542 }
1543
1544 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1545 SmallVector<const SCEV *, 4> Operands;
1546 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1547 Operands.push_back(visit(E->getOperand(i)));
1548 return SE.getAddExpr(Operands);
1549 }
1550
1551 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1552 SmallVector<const SCEV *, 4> Operands;
1553 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1554 Operands.push_back(visit(E->getOperand(i)));
1555 return SE.getMulExpr(Operands);
1556 }
1557
1558 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1559 SmallVector<const SCEV *, 4> Operands;
1560 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1561 Operands.push_back(visit(E->getOperand(i)));
1562 return SE.getSMaxExpr(Operands);
1563 }
1564
1565 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1566 SmallVector<const SCEV *, 4> Operands;
1567 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1568 Operands.push_back(visit(E->getOperand(i)));
1569 return SE.getUMaxExpr(Operands);
1570 }
1571
1572 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1573 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1574 }
1575
1576 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1577 auto *Start = visit(E->getStart());
1578 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1579 visit(E->getStepRecurrence(SE)),
1580 E->getLoop(), SCEV::FlagAnyWrap);
1581 return SE.getAddExpr(Start, AddRec);
1582 }
1583
1584 const SCEV *visitUnknown(const SCEVUnknown *E) {
1585 if (auto *NewValue = VMap.lookup(E->getValue()))
1586 return SE.getUnknown(NewValue);
1587 return E;
1588 }
1589};
1590
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001591const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001592 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001593}
1594
Tobias Grosserabfbe632013-02-05 12:09:06 +00001595void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001596 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001597 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001598
1599 // Normalize the SCEV to get the representing element for an invariant load.
1600 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1601
Tobias Grosser60b54f12011-11-08 15:41:28 +00001602 if (ParameterIds.find(Parameter) != ParameterIds.end())
1603 continue;
1604
1605 int dimension = Parameters.size();
1606
1607 Parameters.push_back(Parameter);
1608 ParameterIds[Parameter] = dimension;
1609 }
1610}
1611
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001612__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001613 // Normalize the SCEV to get the representing element for an invariant load.
1614 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1615
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001616 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001617
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001618 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001619 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001620
Tobias Grosser8f99c162011-11-15 11:38:55 +00001621 std::string ParameterName;
1622
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001623 ParameterName = "p_" + utostr_32(IdIter->second);
1624
Tobias Grosser8f99c162011-11-15 11:38:55 +00001625 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1626 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001627
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001628 // If this parameter references a specific Value and this value has a name
1629 // we use this name as it is likely to be unique and more useful than just
1630 // a number.
1631 if (Val->hasName())
1632 ParameterName = Val->getName();
1633 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
1634 auto LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
1635 if (LoadOrigin->hasName()) {
1636 ParameterName += "_loaded_from_";
1637 ParameterName +=
1638 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1639 }
1640 }
1641 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001642
Tobias Grosser20532b82014-04-11 17:56:49 +00001643 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1644 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001645}
Tobias Grosser75805372011-04-29 06:27:02 +00001646
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001647isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1648 isl_set *DomainContext = isl_union_set_params(getDomains());
1649 return isl_set_intersect_params(C, DomainContext);
1650}
1651
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001652void Scop::buildBoundaryContext() {
Tobias Grosser4927c8e2015-11-24 12:50:02 +00001653 if (IgnoreIntegerWrapping) {
1654 BoundaryContext = isl_set_universe(getParamSpace());
1655 return;
1656 }
1657
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001658 BoundaryContext = Affinator.getWrappingContext();
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001659
1660 // The isl_set_complement operation used to create the boundary context
1661 // can possibly become very expensive. We bound the compile time of
1662 // this operation by setting a compute out.
1663 //
1664 // TODO: We can probably get around using isl_set_complement and directly
1665 // AST generate BoundaryContext.
1666 long MaxOpsOld = isl_ctx_get_max_operations(getIslCtx());
Tobias Grosserf920fb12015-11-13 16:56:13 +00001667 isl_ctx_reset_operations(getIslCtx());
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001668 isl_ctx_set_max_operations(getIslCtx(), 300000);
1669 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_CONTINUE);
1670
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001671 BoundaryContext = isl_set_complement(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001672
Tobias Grossera52b4da2015-11-11 17:59:53 +00001673 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
1674 isl_set_free(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001675 BoundaryContext = isl_set_empty(getParamSpace());
Tobias Grossera52b4da2015-11-11 17:59:53 +00001676 }
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001677
1678 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
1679 isl_ctx_reset_operations(getIslCtx());
1680 isl_ctx_set_max_operations(getIslCtx(), MaxOpsOld);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001681 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001682 trackAssumption(WRAPPING, BoundaryContext, DebugLoc());
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001683}
1684
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001685void Scop::addUserAssumptions(AssumptionCache &AC) {
1686 auto *R = &getRegion();
1687 auto &F = *R->getEntry()->getParent();
1688 for (auto &Assumption : AC.assumptions()) {
1689 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1690 if (!CI || CI->getNumArgOperands() != 1)
1691 continue;
1692 if (!DT.dominates(CI->getParent(), R->getEntry()))
1693 continue;
1694
1695 auto *Val = CI->getArgOperand(0);
1696 std::vector<const SCEV *> Params;
1697 if (!isAffineParamConstraint(Val, R, *SE, Params)) {
1698 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1699 CI->getDebugLoc(),
1700 "Non-affine user assumption ignored.");
1701 continue;
1702 }
1703
1704 addParams(Params);
1705
1706 auto *L = LI.getLoopFor(CI->getParent());
1707 SmallVector<isl_set *, 2> ConditionSets;
1708 buildConditionSets(*this, Val, nullptr, L, Context, ConditionSets);
1709 assert(ConditionSets.size() == 2);
1710 isl_set_free(ConditionSets[1]);
1711
1712 auto *AssumptionCtx = ConditionSets[0];
1713 emitOptimizationRemarkAnalysis(
1714 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1715 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1716 Context = isl_set_intersect(Context, AssumptionCtx);
1717 }
1718}
1719
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001720void Scop::addUserContext() {
1721 if (UserContextStr.empty())
1722 return;
1723
1724 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1725 isl_space *Space = getParamSpace();
1726 if (isl_space_dim(Space, isl_dim_param) !=
1727 isl_set_dim(UserContext, isl_dim_param)) {
1728 auto SpaceStr = isl_space_to_str(Space);
1729 errs() << "Error: the context provided in -polly-context has not the same "
1730 << "number of dimensions than the computed context. Due to this "
1731 << "mismatch, the -polly-context option is ignored. Please provide "
1732 << "the context in the parameter space: " << SpaceStr << ".\n";
1733 free(SpaceStr);
1734 isl_set_free(UserContext);
1735 isl_space_free(Space);
1736 return;
1737 }
1738
1739 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1740 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1741 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1742
1743 if (strcmp(NameContext, NameUserContext) != 0) {
1744 auto SpaceStr = isl_space_to_str(Space);
1745 errs() << "Error: the name of dimension " << i
1746 << " provided in -polly-context "
1747 << "is '" << NameUserContext << "', but the name in the computed "
1748 << "context is '" << NameContext
1749 << "'. Due to this name mismatch, "
1750 << "the -polly-context option is ignored. Please provide "
1751 << "the context in the parameter space: " << SpaceStr << ".\n";
1752 free(SpaceStr);
1753 isl_set_free(UserContext);
1754 isl_space_free(Space);
1755 return;
1756 }
1757
1758 UserContext =
1759 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1760 isl_space_get_dim_id(Space, isl_dim_param, i));
1761 }
1762
1763 Context = isl_set_intersect(Context, UserContext);
1764 isl_space_free(Space);
1765}
1766
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001767void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001768 DenseMap<const SCEV *, LoadInst *> EquivClasses;
1769
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001770 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001771 for (LoadInst *LInst : RIL) {
1772 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1773
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001774 LoadInst *&ClassRep = EquivClasses[PointerSCEV];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001775 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001776 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001777 continue;
1778 }
1779
1780 ClassRep = LInst;
1781 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(),
1782 nullptr);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001783 }
1784}
1785
Tobias Grosser6be480c2011-11-08 15:41:13 +00001786void Scop::buildContext() {
1787 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001788 Context = isl_set_universe(isl_space_copy(Space));
1789 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001790}
1791
Tobias Grosser18daaca2012-05-22 10:47:27 +00001792void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001793 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001794 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001795
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001796 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001797
Johannes Doerferte7044942015-02-24 11:58:30 +00001798 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001799 }
1800}
1801
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001802void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001803 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001804 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001805
Tobias Grosser083d3d32014-06-28 08:59:45 +00001806 for (const auto &ParamID : ParameterIds) {
1807 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001808 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001809 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001810 }
1811
1812 // Align the parameters of all data structures to the model.
1813 Context = isl_set_align_params(Context, Space);
1814
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001815 for (ScopStmt &Stmt : *this)
1816 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001817}
1818
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001819static __isl_give isl_set *
1820simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1821 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001822 // If we modelt all blocks in the SCoP that have side effects we can simplify
1823 // the context with the constraints that are needed for anything to be
1824 // executed at all. However, if we have error blocks in the SCoP we already
1825 // assumed some parameter combinations cannot occure and removed them from the
1826 // domains, thus we cannot use the remaining domain to simplify the
1827 // assumptions.
1828 if (!S.hasErrorBlock()) {
1829 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1830 AssumptionContext =
1831 isl_set_gist_params(AssumptionContext, DomainParameters);
1832 }
1833
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001834 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1835 return AssumptionContext;
1836}
1837
1838void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001839 // The parameter constraints of the iteration domains give us a set of
1840 // constraints that need to hold for all cases where at least a single
1841 // statement iteration is executed in the whole scop. We now simplify the
1842 // assumed context under the assumption that such constraints hold and at
1843 // least a single statement iteration is executed. For cases where no
1844 // statement instances are executed, the assumptions we have taken about
1845 // the executed code do not matter and can be changed.
1846 //
1847 // WARNING: This only holds if the assumptions we have taken do not reduce
1848 // the set of statement instances that are executed. Otherwise we
1849 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001850 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001851 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001852 // performed. In such a case, modifying the run-time conditions and
1853 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001854 // to not be executed.
1855 //
1856 // Example:
1857 //
1858 // When delinearizing the following code:
1859 //
1860 // for (long i = 0; i < 100; i++)
1861 // for (long j = 0; j < m; j++)
1862 // A[i+p][j] = 1.0;
1863 //
1864 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001865 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001866 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001867 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1868 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001869}
1870
Johannes Doerfertb164c792014-09-18 11:17:17 +00001871/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001872static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001873 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1874 isl_pw_multi_aff *MinPMA, *MaxPMA;
1875 isl_pw_aff *LastDimAff;
1876 isl_aff *OneAff;
1877 unsigned Pos;
1878
Johannes Doerfert9143d672014-09-27 11:02:39 +00001879 // Restrict the number of parameters involved in the access as the lexmin/
1880 // lexmax computation will take too long if this number is high.
1881 //
1882 // Experiments with a simple test case using an i7 4800MQ:
1883 //
1884 // #Parameters involved | Time (in sec)
1885 // 6 | 0.01
1886 // 7 | 0.04
1887 // 8 | 0.12
1888 // 9 | 0.40
1889 // 10 | 1.54
1890 // 11 | 6.78
1891 // 12 | 30.38
1892 //
1893 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1894 unsigned InvolvedParams = 0;
1895 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1896 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1897 InvolvedParams++;
1898
1899 if (InvolvedParams > RunTimeChecksMaxParameters) {
1900 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001901 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001902 }
1903 }
1904
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001905 Set = isl_set_remove_divs(Set);
1906
Johannes Doerfertb164c792014-09-18 11:17:17 +00001907 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1908 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1909
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001910 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1911 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1912
Johannes Doerfertb164c792014-09-18 11:17:17 +00001913 // Adjust the last dimension of the maximal access by one as we want to
1914 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1915 // we test during code generation might now point after the end of the
1916 // allocated array but we will never dereference it anyway.
1917 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1918 "Assumed at least one output dimension");
1919 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1920 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1921 OneAff = isl_aff_zero_on_domain(
1922 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1923 OneAff = isl_aff_add_constant_si(OneAff, 1);
1924 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1925 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1926
1927 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1928
1929 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001930 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001931}
1932
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001933static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1934 isl_set *Domain = MA->getStatement()->getDomain();
1935 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1936 return isl_set_reset_tuple_id(Domain);
1937}
1938
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001939/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1940static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001941 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001942 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001943
1944 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1945 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001946 Locations = isl_union_set_coalesce(Locations);
1947 Locations = isl_union_set_detect_equalities(Locations);
1948 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001949 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001950 isl_union_set_free(Locations);
1951 return Valid;
1952}
1953
Johannes Doerfert96425c22015-08-30 21:13:53 +00001954/// @brief Helper to treat non-affine regions and basic blocks the same.
1955///
1956///{
1957
1958/// @brief Return the block that is the representing block for @p RN.
1959static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1960 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1961 : RN->getNodeAs<BasicBlock>();
1962}
1963
1964/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001965static inline BasicBlock *
1966getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001967 if (RN->isSubRegion()) {
1968 assert(idx == 0);
1969 return RN->getNodeAs<Region>()->getExit();
1970 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001971 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001972}
1973
1974/// @brief Return the smallest loop surrounding @p RN.
1975static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1976 if (!RN->isSubRegion())
1977 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1978
1979 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1980 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1981 while (L && NonAffineSubRegion->contains(L))
1982 L = L->getParentLoop();
1983 return L;
1984}
1985
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001986static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1987 if (!RN->isSubRegion())
1988 return 1;
1989
1990 unsigned NumBlocks = 0;
1991 Region *R = RN->getNodeAs<Region>();
1992 for (auto BB : R->blocks()) {
1993 (void)BB;
1994 NumBlocks++;
1995 }
1996 return NumBlocks;
1997}
1998
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001999static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2000 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002001 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002002 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002003 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002004 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002005 return true;
2006 return false;
2007}
2008
Johannes Doerfert96425c22015-08-30 21:13:53 +00002009///}
2010
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002011static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2012 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002013 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002014 isl_id *DimId =
2015 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2016 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2017}
2018
Johannes Doerfert96425c22015-08-30 21:13:53 +00002019isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
2020 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
2021 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002022 return getDomainConditions(BB);
2023}
2024
2025isl_set *Scop::getDomainConditions(BasicBlock *BB) {
2026 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002027 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002028}
2029
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002030void Scop::removeErrorBlockDomains() {
2031 auto removeDomains = [this](BasicBlock *Start) {
2032 auto BBNode = DT.getNode(Start);
2033 for (auto ErrorChild : depth_first(BBNode)) {
2034 auto ErrorChildBlock = ErrorChild->getBlock();
2035 auto CurrentDomain = DomainMap[ErrorChildBlock];
2036 auto Empty = isl_set_empty(isl_set_get_space(CurrentDomain));
2037 DomainMap[ErrorChildBlock] = Empty;
2038 isl_set_free(CurrentDomain);
2039 }
2040 };
2041
Tobias Grosser5ef2bc32015-11-23 10:18:23 +00002042 SmallVector<Region *, 4> Todo = {&R};
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002043
2044 while (!Todo.empty()) {
2045 auto SubRegion = Todo.back();
2046 Todo.pop_back();
2047
2048 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
2049 for (auto &Child : *SubRegion)
2050 Todo.push_back(Child.get());
2051 continue;
2052 }
2053 if (containsErrorBlock(SubRegion->getNode(), getRegion(), LI, DT))
2054 removeDomains(SubRegion->getEntry());
2055 }
2056
2057 for (auto BB : R.blocks())
2058 if (isErrorBlock(*BB, R, LI, DT))
2059 removeDomains(BB);
2060}
2061
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002062void Scop::buildDomains(Region *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002063
Johannes Doerfert432658d2016-01-26 11:01:41 +00002064 bool IsOnlyNonAffineRegion = SD.isNonAffineSubRegion(R, R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002065 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002066 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2067 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002068 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002069
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002070 while (LD-- >= 0) {
2071 S = addDomainDimId(S, LD + 1, L);
2072 L = L->getParentLoop();
2073 }
2074
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002075 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002076
Johannes Doerfert432658d2016-01-26 11:01:41 +00002077 if (IsOnlyNonAffineRegion)
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002078 return;
2079
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002080 buildDomainsWithBranchConstraints(R);
2081 propagateDomainConstraints(R);
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002082
2083 // Error blocks and blocks dominated by them have been assumed to never be
2084 // executed. Representing them in the Scop does not add any value. In fact,
2085 // it is likely to cause issues during construction of the ScopStmts. The
2086 // contents of error blocks have not been verfied to be expressible and
2087 // will cause problems when building up a ScopStmt for them.
2088 // Furthermore, basic blocks dominated by error blocks may reference
2089 // instructions in the error block which, if the error block is not modeled,
2090 // can themselves not be constructed properly.
2091 removeErrorBlockDomains();
Johannes Doerfert96425c22015-08-30 21:13:53 +00002092}
2093
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002094void Scop::buildDomainsWithBranchConstraints(Region *R) {
Johannes Doerfert6f50c292016-01-26 11:03:25 +00002095 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002096
2097 // To create the domain for each block in R we iterate over all blocks and
2098 // subregions in R and propagate the conditions under which the current region
2099 // element is executed. To this end we iterate in reverse post order over R as
2100 // it ensures that we first visit all predecessors of a region node (either a
2101 // basic block or a subregion) before we visit the region node itself.
2102 // Initially, only the domain for the SCoP region entry block is set and from
2103 // there we propagate the current domain to all successors, however we add the
2104 // condition that the successor is actually executed next.
2105 // As we are only interested in non-loop carried constraints here we can
2106 // simply skip loop back edges.
2107
2108 ReversePostOrderTraversal<Region *> RTraversal(R);
2109 for (auto *RN : RTraversal) {
2110
2111 // Recurse for affine subregions but go on for basic blocks and non-affine
2112 // subregions.
2113 if (RN->isSubRegion()) {
2114 Region *SubRegion = RN->getNodeAs<Region>();
2115 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002116 buildDomainsWithBranchConstraints(SubRegion);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002117 continue;
2118 }
2119 }
2120
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002121 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002122 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002123
Johannes Doerfert96425c22015-08-30 21:13:53 +00002124 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002125 TerminatorInst *TI = BB->getTerminator();
2126
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002127 if (isa<UnreachableInst>(TI))
2128 continue;
2129
Johannes Doerfertf5673802015-10-01 23:48:18 +00002130 isl_set *Domain = DomainMap.lookup(BB);
2131 if (!Domain) {
2132 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2133 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002134 continue;
2135 }
2136
Johannes Doerfert96425c22015-08-30 21:13:53 +00002137 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002138
2139 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2140 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2141
2142 // Build the condition sets for the successor nodes of the current region
2143 // node. If it is a non-affine subregion we will always execute the single
2144 // exit node, hence the single entry node domain is the condition set. For
2145 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002146 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002147 if (RN->isSubRegion())
2148 ConditionSets.push_back(isl_set_copy(Domain));
2149 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002150 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002151
2152 // Now iterate over the successors and set their initial domain based on
2153 // their condition set. We skip back edges here and have to be careful when
2154 // we leave a loop not to keep constraints over a dimension that doesn't
2155 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002156 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002157 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002158 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002159 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002160
2161 // Skip back edges.
2162 if (DT.dominates(SuccBB, BB)) {
2163 isl_set_free(CondSet);
2164 continue;
2165 }
2166
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002167 // Do not adjust the number of dimensions if we enter a boxed loop or are
2168 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002169 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfert6f50c292016-01-26 11:03:25 +00002170 while (BoxedLoops.count(SuccBBLoop))
2171 SuccBBLoop = SuccBBLoop->getParentLoop();
Johannes Doerfert634909c2015-10-04 14:57:41 +00002172
2173 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002174
2175 // Check if the edge to SuccBB is a loop entry or exit edge. If so
2176 // adjust the dimensionality accordingly. Lastly, if we leave a loop
2177 // and enter a new one we need to drop the old constraints.
2178 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002179 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002180 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002181 CondSet = isl_set_project_out(CondSet, isl_dim_set,
2182 isl_set_n_dim(CondSet) - LoopDepthDiff,
2183 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002184 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002185 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002186 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002187 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002188 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002189 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002190 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
2191 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002192 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002193 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002194 }
2195
2196 // Set the domain for the successor or merge it with an existing domain in
2197 // case there are multiple paths (without loop back edges) to the
2198 // successor block.
2199 isl_set *&SuccDomain = DomainMap[SuccBB];
2200 if (!SuccDomain)
2201 SuccDomain = CondSet;
2202 else
2203 SuccDomain = isl_set_union(SuccDomain, CondSet);
2204
2205 SuccDomain = isl_set_coalesce(SuccDomain);
Tobias Grosser75dc40c2015-12-20 13:31:48 +00002206 if (isl_set_n_basic_set(SuccDomain) > MaxConjunctsInDomain) {
2207 auto *Empty = isl_set_empty(isl_set_get_space(SuccDomain));
2208 isl_set_free(SuccDomain);
2209 SuccDomain = Empty;
2210 invalidate(ERROR_DOMAINCONJUNCTS, DebugLoc());
2211 }
Johannes Doerfert634909c2015-10-04 14:57:41 +00002212 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
2213 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002214 }
2215 }
2216}
2217
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002218/// @brief Return the domain for @p BB wrt @p DomainMap.
2219///
2220/// This helper function will lookup @p BB in @p DomainMap but also handle the
2221/// case where @p BB is contained in a non-affine subregion using the region
2222/// tree obtained by @p RI.
2223static __isl_give isl_set *
2224getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
2225 RegionInfo &RI) {
2226 auto DIt = DomainMap.find(BB);
2227 if (DIt != DomainMap.end())
2228 return isl_set_copy(DIt->getSecond());
2229
2230 Region *R = RI.getRegionFor(BB);
2231 while (R->getEntry() == BB)
2232 R = R->getParent();
2233 return getDomainForBlock(R->getEntry(), DomainMap, RI);
2234}
2235
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002236void Scop::propagateDomainConstraints(Region *R) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002237 // Iterate over the region R and propagate the domain constrains from the
2238 // predecessors to the current node. In contrast to the
2239 // buildDomainsWithBranchConstraints function, this one will pull the domain
2240 // information from the predecessors instead of pushing it to the successors.
2241 // Additionally, we assume the domains to be already present in the domain
2242 // map here. However, we iterate again in reverse post order so we know all
2243 // predecessors have been visited before a block or non-affine subregion is
2244 // visited.
2245
2246 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2247 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2248
2249 ReversePostOrderTraversal<Region *> RTraversal(R);
2250 for (auto *RN : RTraversal) {
2251
2252 // Recurse for affine subregions but go on for basic blocks and non-affine
2253 // subregions.
2254 if (RN->isSubRegion()) {
2255 Region *SubRegion = RN->getNodeAs<Region>();
2256 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002257 propagateDomainConstraints(SubRegion);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002258 continue;
2259 }
2260 }
2261
Johannes Doerfertf5673802015-10-01 23:48:18 +00002262 // Get the domain for the current block and check if it was initialized or
2263 // not. The only way it was not is if this block is only reachable via error
2264 // blocks, thus will not be executed under the assumptions we make. Such
2265 // blocks have to be skipped as their predecessors might not have domains
2266 // either. It would not benefit us to compute the domain anyway, only the
2267 // domains of the error blocks that are reachable from non-error blocks
2268 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002269 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002270 isl_set *&Domain = DomainMap[BB];
2271 if (!Domain) {
2272 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2273 << ", it is only reachable from error blocks.\n");
2274 DomainMap.erase(BB);
2275 continue;
2276 }
2277 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
2278
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002279 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2280 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2281
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002282 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2283 for (auto *PredBB : predecessors(BB)) {
2284
2285 // Skip backedges
2286 if (DT.dominates(BB, PredBB))
2287 continue;
2288
2289 isl_set *PredBBDom = nullptr;
2290
2291 // Handle the SCoP entry block with its outside predecessors.
2292 if (!getRegion().contains(PredBB))
2293 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
2294
2295 if (!PredBBDom) {
2296 // Determine the loop depth of the predecessor and adjust its domain to
2297 // the domain of the current block. This can mean we have to:
2298 // o) Drop a dimension if this block is the exit of a loop, not the
2299 // header of a new loop and the predecessor was part of the loop.
2300 // o) Add an unconstrainted new dimension if this block is the header
2301 // of a loop and the predecessor is not part of it.
2302 // o) Drop the information about the innermost loop dimension when the
2303 // predecessor and the current block are surrounded by different
2304 // loops in the same depth.
2305 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2306 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2307 while (BoxedLoops.count(PredBBLoop))
2308 PredBBLoop = PredBBLoop->getParentLoop();
2309
2310 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002311 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002312 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002313 PredBBDom = isl_set_project_out(
2314 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2315 LoopDepthDiff);
2316 else if (PredBBLoopDepth < BBLoopDepth) {
2317 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002318 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002319 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2320 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002321 PredBBDom = isl_set_drop_constraints_involving_dims(
2322 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002323 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002324 }
2325
2326 PredDom = isl_set_union(PredDom, PredBBDom);
2327 }
2328
2329 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002330 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002331
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002332 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002333 addLoopBoundsToHeaderDomain(BBLoop);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002334
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002335 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002336 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002337 IsOptimized = true;
2338 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002339 addAssumption(ERRORBLOCK, isl_set_complement(DomPar),
2340 BB->getTerminator()->getDebugLoc());
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002341 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002342 }
2343}
2344
2345/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2346/// is incremented by one and all other dimensions are equal, e.g.,
2347/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2348/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2349static __isl_give isl_map *
2350createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2351 auto *MapSpace = isl_space_map_from_set(SetSpace);
2352 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2353 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2354 if (u != Dim)
2355 NextIterationMap =
2356 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2357 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2358 C = isl_constraint_set_constant_si(C, 1);
2359 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2360 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2361 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2362 return NextIterationMap;
2363}
2364
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002365void Scop::addLoopBoundsToHeaderDomain(Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002366 int LoopDepth = getRelativeLoopDepth(L);
2367 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002368
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002369 BasicBlock *HeaderBB = L->getHeader();
2370 assert(DomainMap.count(HeaderBB));
2371 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002372
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002373 isl_map *NextIterationMap =
2374 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002375
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002376 isl_set *UnionBackedgeCondition =
2377 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002378
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002379 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2380 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002381
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002382 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002383
2384 // If the latch is only reachable via error statements we skip it.
2385 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2386 if (!LatchBBDom)
2387 continue;
2388
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002389 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002390
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002391 TerminatorInst *TI = LatchBB->getTerminator();
2392 BranchInst *BI = dyn_cast<BranchInst>(TI);
2393 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002394 BackedgeCondition = isl_set_copy(LatchBBDom);
2395 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002396 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002397 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002398 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002399
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002400 // Free the non back edge condition set as we do not need it.
2401 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002402
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002403 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002404 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002405
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002406 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2407 assert(LatchLoopDepth >= LoopDepth);
2408 BackedgeCondition =
2409 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2410 LatchLoopDepth - LoopDepth);
2411 UnionBackedgeCondition =
2412 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002413 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002414
2415 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2416 for (int i = 0; i < LoopDepth; i++)
2417 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2418
2419 isl_set *UnionBackedgeConditionComplement =
2420 isl_set_complement(UnionBackedgeCondition);
2421 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2422 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2423 UnionBackedgeConditionComplement =
2424 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2425 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2426 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2427
2428 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2429 HeaderBBDom = Parts.second;
2430
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002431 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2432 // the bounded assumptions to the context as they are already implied by the
2433 // <nsw> tag.
2434 if (Affinator.hasNSWAddRecForLoop(L)) {
2435 isl_set_free(Parts.first);
2436 return;
2437 }
2438
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002439 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2440 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002441 addAssumption(INFINITELOOP, BoundedCtx,
2442 HeaderBB->getTerminator()->getDebugLoc());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002443}
2444
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002445void Scop::buildAliasChecks(AliasAnalysis &AA) {
2446 if (!PollyUseRuntimeAliasChecks)
2447 return;
2448
2449 if (buildAliasGroups(AA))
2450 return;
2451
2452 // If a problem occurs while building the alias groups we need to delete
2453 // this SCoP and pretend it wasn't valid in the first place. To this end
2454 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002455 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002456
2457 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2458 << " could not be created as the number of parameters involved "
2459 "is too high. The SCoP will be "
2460 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2461 "the maximal number of parameters but be advised that the "
2462 "compile time might increase exponentially.\n\n");
2463}
2464
Johannes Doerfert9143d672014-09-27 11:02:39 +00002465bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002466 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002467 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002468 // for all memory accesses inside the SCoP.
2469 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002470 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002471 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002472 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002473 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002474 // if their access domains intersect, otherwise they are in different
2475 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002476 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002477 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002478 // and maximal accesses to each array of a group in read only and non
2479 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002480 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2481
2482 AliasSetTracker AST(AA);
2483
2484 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002485 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002486 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002487
2488 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002489 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002490 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2491 isl_set_free(StmtDomain);
2492 if (StmtDomainEmpty)
2493 continue;
2494
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002495 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002496 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002497 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002498 if (!MA->isRead())
2499 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002500 MemAccInst Acc(MA->getAccessInstruction());
2501 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002502 AST.add(Acc);
2503 }
2504 }
2505
2506 SmallVector<AliasGroupTy, 4> AliasGroups;
2507 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002508 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002509 continue;
2510 AliasGroupTy AG;
2511 for (auto PR : AS)
2512 AG.push_back(PtrToAcc[PR.getValue()]);
2513 assert(AG.size() > 1 &&
2514 "Alias groups should contain at least two accesses");
2515 AliasGroups.push_back(std::move(AG));
2516 }
2517
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002518 // Split the alias groups based on their domain.
2519 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2520 AliasGroupTy NewAG;
2521 AliasGroupTy &AG = AliasGroups[u];
2522 AliasGroupTy::iterator AGI = AG.begin();
2523 isl_set *AGDomain = getAccessDomain(*AGI);
2524 while (AGI != AG.end()) {
2525 MemoryAccess *MA = *AGI;
2526 isl_set *MADomain = getAccessDomain(MA);
2527 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2528 NewAG.push_back(MA);
2529 AGI = AG.erase(AGI);
2530 isl_set_free(MADomain);
2531 } else {
2532 AGDomain = isl_set_union(AGDomain, MADomain);
2533 AGI++;
2534 }
2535 }
2536 if (NewAG.size() > 1)
2537 AliasGroups.push_back(std::move(NewAG));
2538 isl_set_free(AGDomain);
2539 }
2540
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002541 auto &F = *getRegion().getEntry()->getParent();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002542 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002543 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2544 for (AliasGroupTy &AG : AliasGroups) {
2545 NonReadOnlyBaseValues.clear();
2546 ReadOnlyPairs.clear();
2547
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002548 if (AG.size() < 2) {
2549 AG.clear();
2550 continue;
2551 }
2552
Johannes Doerfert13771732014-10-01 12:40:46 +00002553 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002554 emitOptimizationRemarkAnalysis(
2555 F.getContext(), DEBUG_TYPE, F,
2556 (*II)->getAccessInstruction()->getDebugLoc(),
2557 "Possibly aliasing pointer, use restrict keyword.");
2558
Johannes Doerfert13771732014-10-01 12:40:46 +00002559 Value *BaseAddr = (*II)->getBaseAddr();
2560 if (HasWriteAccess.count(BaseAddr)) {
2561 NonReadOnlyBaseValues.insert(BaseAddr);
2562 II++;
2563 } else {
2564 ReadOnlyPairs[BaseAddr].insert(*II);
2565 II = AG.erase(II);
2566 }
2567 }
2568
2569 // If we don't have read only pointers check if there are at least two
2570 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002571 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002572 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002573 continue;
2574 }
2575
2576 // If we don't have non read only pointers clear the alias group.
2577 if (NonReadOnlyBaseValues.empty()) {
2578 AG.clear();
2579 continue;
2580 }
2581
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002582 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002583 MinMaxAliasGroups.emplace_back();
2584 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2585 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2586 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2587 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002588
2589 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002590
2591 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002592 for (MemoryAccess *MA : AG)
2593 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002594
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002595 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2596 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002597
2598 // Bail out if the number of values we need to compare is too large.
2599 // This is important as the number of comparisions grows quadratically with
2600 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002601 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2602 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002603 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002604
2605 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002606 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002607 Accesses = isl_union_map_empty(getParamSpace());
2608
2609 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2610 for (MemoryAccess *MA : ReadOnlyPair.second)
2611 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2612
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002613 Valid =
2614 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002615
2616 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002617 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002618 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002619
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002620 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002621}
2622
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002623/// @brief Get the smallest loop that contains @p R but is not in @p R.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002624static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002625 // Start with the smallest loop containing the entry and expand that
2626 // loop until it contains all blocks in the region. If there is a loop
2627 // containing all blocks in the region check if it is itself contained
2628 // and if so take the parent loop as it will be the smallest containing
2629 // the region but not contained by it.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002630 Loop *L = LI.getLoopFor(R.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002631 while (L) {
2632 bool AllContained = true;
2633 for (auto *BB : R.blocks())
2634 AllContained &= L->contains(BB);
2635 if (AllContained)
2636 break;
2637 L = L->getParentLoop();
2638 }
2639
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002640 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2641}
2642
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002643static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2644 ScopDetection &SD) {
2645
2646 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2647
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002648 unsigned MinLD = INT_MAX, MaxLD = 0;
2649 for (BasicBlock *BB : R.blocks()) {
2650 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002651 if (!R.contains(L))
2652 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002653 if (BoxedLoops && BoxedLoops->count(L))
2654 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002655 unsigned LD = L->getLoopDepth();
2656 MinLD = std::min(MinLD, LD);
2657 MaxLD = std::max(MaxLD, LD);
2658 }
2659 }
2660
2661 // Handle the case that there is no loop in the SCoP first.
2662 if (MaxLD == 0)
2663 return 1;
2664
2665 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2666 assert(MaxLD >= MinLD &&
2667 "Maximal loop depth was smaller than mininaml loop depth?");
2668 return MaxLD - MinLD + 1;
2669}
2670
Johannes Doerfert478a7de2015-10-02 13:09:31 +00002671Scop::Scop(Region &R, AccFuncMapType &AccFuncMap, ScopDetection &SD,
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002672 ScalarEvolution &ScalarEvolution, DominatorTree &DT, LoopInfo &LI,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002673 isl_ctx *Context, unsigned MaxLoopDepth)
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002674 : LI(LI), DT(DT), SE(&ScalarEvolution), SD(SD), R(R),
2675 AccFuncMap(AccFuncMap), IsOptimized(false),
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002676 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
2677 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Context(nullptr),
2678 Affinator(this), AssumedContext(nullptr), BoundaryContext(nullptr),
2679 Schedule(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002680
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002681void Scop::init(AliasAnalysis &AA, AssumptionCache &AC) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002682 buildContext();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002683 addUserAssumptions(AC);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002684 buildInvariantEquivalenceClasses();
2685
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002686 buildDomains(&R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002687
Michael Krusecac948e2015-10-02 13:53:07 +00002688 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002689 // Exit early in case there are no executable statements left in this scop.
Michael Krusecac948e2015-10-02 13:53:07 +00002690 simplifySCoP(true);
Michael Kruseafe06702015-10-02 16:33:27 +00002691 if (Stmts.empty())
2692 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002693
Michael Krusecac948e2015-10-02 13:53:07 +00002694 // The ScopStmts now have enough information to initialize themselves.
2695 for (ScopStmt &Stmt : Stmts)
2696 Stmt.init();
2697
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00002698 buildSchedule();
Tobias Grosser75805372011-04-29 06:27:02 +00002699
Tobias Grosser8286b832015-11-02 11:29:32 +00002700 if (isl_set_is_empty(AssumedContext))
2701 return;
2702
2703 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002704 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002705 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002706 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002707 buildBoundaryContext();
2708 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002709 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002710
2711 hoistInvariantLoads();
Michael Krusecac948e2015-10-02 13:53:07 +00002712 simplifySCoP(false);
Tobias Grosser75805372011-04-29 06:27:02 +00002713}
2714
2715Scop::~Scop() {
2716 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002717 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002718 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002719 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002720
Johannes Doerfert96425c22015-08-30 21:13:53 +00002721 for (auto It : DomainMap)
2722 isl_set_free(It.second);
2723
Johannes Doerfertb164c792014-09-18 11:17:17 +00002724 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002725 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002726 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002727 isl_pw_multi_aff_free(MMA.first);
2728 isl_pw_multi_aff_free(MMA.second);
2729 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002730 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002731 isl_pw_multi_aff_free(MMA.first);
2732 isl_pw_multi_aff_free(MMA.second);
2733 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002734 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002735
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002736 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002737 isl_set_free(std::get<2>(IAClass));
Tobias Grosser75805372011-04-29 06:27:02 +00002738}
2739
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002740void Scop::updateAccessDimensionality() {
2741 for (auto &Stmt : *this)
2742 for (auto &Access : Stmt)
2743 Access->updateDimensionality();
2744}
2745
Michael Krusecac948e2015-10-02 13:53:07 +00002746void Scop::simplifySCoP(bool RemoveIgnoredStmts) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002747 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2748 ScopStmt &Stmt = *StmtIt;
Michael Krusecac948e2015-10-02 13:53:07 +00002749 RegionNode *RN = Stmt.isRegionStmt()
2750 ? Stmt.getRegion()->getNode()
2751 : getRegion().getBBNode(Stmt.getBasicBlock());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002752
Johannes Doerferteca9e892015-11-03 16:54:49 +00002753 bool RemoveStmt = StmtIt->isEmpty();
2754 if (!RemoveStmt)
2755 RemoveStmt = isl_set_is_empty(DomainMap[getRegionNodeBasicBlock(RN)]);
2756 if (!RemoveStmt)
2757 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002758
Johannes Doerferteca9e892015-11-03 16:54:49 +00002759 // Remove read only statements only after invariant loop hoisting.
2760 if (!RemoveStmt && !RemoveIgnoredStmts) {
2761 bool OnlyRead = true;
2762 for (MemoryAccess *MA : Stmt) {
2763 if (MA->isRead())
2764 continue;
2765
2766 OnlyRead = false;
2767 break;
2768 }
2769
2770 RemoveStmt = OnlyRead;
2771 }
2772
2773 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00002774 // Remove the statement because it is unnecessary.
2775 if (Stmt.isRegionStmt())
2776 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2777 StmtMap.erase(BB);
2778 else
2779 StmtMap.erase(Stmt.getBasicBlock());
2780
2781 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002782 continue;
2783 }
2784
Michael Krusecac948e2015-10-02 13:53:07 +00002785 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002786 }
2787}
2788
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002789const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2790 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2791 if (!LInst)
2792 return nullptr;
2793
2794 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2795 LInst = cast<LoadInst>(Rep);
2796
2797 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2798 for (auto &IAClass : InvariantEquivClasses)
2799 if (PointerSCEV == std::get<0>(IAClass))
2800 return &IAClass;
2801
2802 return nullptr;
2803}
2804
2805void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2806
2807 // Get the context under which the statement is executed.
2808 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2809 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2810 DomainCtx = isl_set_detect_equalities(DomainCtx);
2811 DomainCtx = isl_set_coalesce(DomainCtx);
2812
2813 // Project out all parameters that relate to loads in the statement. Otherwise
2814 // we could have cyclic dependences on the constraints under which the
2815 // hoisted loads are executed and we could not determine an order in which to
2816 // pre-load them. This happens because not only lower bounds are part of the
2817 // domain but also upper bounds.
2818 for (MemoryAccess *MA : InvMAs) {
2819 Instruction *AccInst = MA->getAccessInstruction();
2820 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00002821 SetVector<Value *> Values;
2822 for (const SCEV *Parameter : Parameters) {
2823 Values.clear();
2824 findValues(Parameter, Values);
2825 if (!Values.count(AccInst))
2826 continue;
2827
2828 if (isl_id *ParamId = getIdForParam(Parameter)) {
2829 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2830 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2831 isl_id_free(ParamId);
2832 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002833 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002834 }
2835 }
2836
2837 for (MemoryAccess *MA : InvMAs) {
2838 // Check for another invariant access that accesses the same location as
2839 // MA and if found consolidate them. Otherwise create a new equivalence
2840 // class at the end of InvariantEquivClasses.
2841 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
2842 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2843
2844 bool Consolidated = false;
2845 for (auto &IAClass : InvariantEquivClasses) {
2846 if (PointerSCEV != std::get<0>(IAClass))
2847 continue;
2848
2849 Consolidated = true;
2850
2851 // Add MA to the list of accesses that are in this class.
2852 auto &MAs = std::get<1>(IAClass);
2853 MAs.push_front(MA);
2854
2855 // Unify the execution context of the class and this statement.
2856 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002857 if (IAClassDomainCtx)
2858 IAClassDomainCtx = isl_set_coalesce(
2859 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
2860 else
2861 IAClassDomainCtx = isl_set_copy(DomainCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002862 break;
2863 }
2864
2865 if (Consolidated)
2866 continue;
2867
2868 // If we did not consolidate MA, thus did not find an equivalence class
2869 // for it, we create a new one.
2870 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
2871 isl_set_copy(DomainCtx));
2872 }
2873
2874 isl_set_free(DomainCtx);
2875}
2876
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002877bool Scop::isHoistableAccess(MemoryAccess *Access,
2878 __isl_keep isl_union_map *Writes) {
2879 // TODO: Loads that are not loop carried, hence are in a statement with
2880 // zero iterators, are by construction invariant, though we
2881 // currently "hoist" them anyway. This is necessary because we allow
2882 // them to be treated as parameters (e.g., in conditions) and our code
2883 // generation would otherwise use the old value.
2884
2885 auto &Stmt = *Access->getStatement();
2886 BasicBlock *BB =
2887 Stmt.isBlockStmt() ? Stmt.getBasicBlock() : Stmt.getRegion()->getEntry();
2888
2889 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
2890 return false;
2891
2892 // Skip accesses that have an invariant base pointer which is defined but
2893 // not loaded inside the SCoP. This can happened e.g., if a readnone call
2894 // returns a pointer that is used as a base address. However, as we want
2895 // to hoist indirect pointers, we allow the base pointer to be defined in
2896 // the region if it is also a memory access. Each ScopArrayInfo object
2897 // that has a base pointer origin has a base pointer that is loaded and
2898 // that it is invariant, thus it will be hoisted too. However, if there is
2899 // no base pointer origin we check that the base pointer is defined
2900 // outside the region.
2901 const ScopArrayInfo *SAI = Access->getScopArrayInfo();
2902 while (auto *BasePtrOriginSAI = SAI->getBasePtrOriginSAI())
2903 SAI = BasePtrOriginSAI;
2904
2905 if (auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr()))
2906 if (R.contains(BasePtrInst))
2907 return false;
2908
2909 // Skip accesses in non-affine subregions as they might not be executed
2910 // under the same condition as the entry of the non-affine subregion.
2911 if (BB != Access->getAccessInstruction()->getParent())
2912 return false;
2913
2914 isl_map *AccessRelation = Access->getAccessRelation();
2915
2916 // Skip accesses that have an empty access relation. These can be caused
2917 // by multiple offsets with a type cast in-between that cause the overall
2918 // byte offset to be not divisible by the new types sizes.
2919 if (isl_map_is_empty(AccessRelation)) {
2920 isl_map_free(AccessRelation);
2921 return false;
2922 }
2923
2924 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
2925 Stmt.getNumIterators())) {
2926 isl_map_free(AccessRelation);
2927 return false;
2928 }
2929
2930 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
2931 isl_set *AccessRange = isl_map_range(AccessRelation);
2932
2933 isl_union_map *Written = isl_union_map_intersect_range(
2934 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
2935 bool IsWritten = !isl_union_map_is_empty(Written);
2936 isl_union_map_free(Written);
2937
2938 if (IsWritten)
2939 return false;
2940
2941 return true;
2942}
2943
2944void Scop::verifyInvariantLoads() {
2945 auto &RIL = *SD.getRequiredInvariantLoads(&getRegion());
2946 for (LoadInst *LI : RIL) {
2947 assert(LI && getRegion().contains(LI));
2948 ScopStmt *Stmt = getStmtForBasicBlock(LI->getParent());
Tobias Grosser949e8c62015-12-21 07:10:39 +00002949 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002950 invalidate(INVARIANTLOAD, LI->getDebugLoc());
2951 return;
2952 }
2953 }
2954}
2955
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002956void Scop::hoistInvariantLoads() {
2957 isl_union_map *Writes = getWrites();
2958 for (ScopStmt &Stmt : *this) {
2959
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002960 MemoryAccessList InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002961
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002962 for (MemoryAccess *Access : Stmt)
2963 if (isHoistableAccess(Access, Writes))
2964 InvariantAccesses.push_front(Access);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002965
2966 // We inserted invariant accesses always in the front but need them to be
2967 // sorted in a "natural order". The statements are already sorted in reverse
2968 // post order and that suffices for the accesses too. The reason we require
2969 // an order in the first place is the dependences between invariant loads
2970 // that can be caused by indirect loads.
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002971 InvariantAccesses.reverse();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002972
2973 // Transfer the memory access from the statement to the SCoP.
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002974 Stmt.removeMemoryAccesses(InvariantAccesses);
2975 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002976 }
2977 isl_union_map_free(Writes);
2978
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002979 verifyInvariantLoads();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002980}
2981
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002982const ScopArrayInfo *
2983Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002984 ArrayRef<const SCEV *> Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00002985 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002986 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002987 if (!SAI) {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00002988 auto &DL = getRegion().getEntry()->getModule()->getDataLayout();
2989 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, Kind,
2990 DL, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002991 } else {
Tobias Grosser8286b832015-11-02 11:29:32 +00002992 // In case of mismatching array sizes, we bail out by setting the run-time
2993 // context to false.
2994 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002995 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002996 }
Tobias Grosserab671442015-05-23 05:58:27 +00002997 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002998}
2999
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003000const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00003001 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003002 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003003 assert(SAI && "No ScopArrayInfo available for this base pointer");
3004 return SAI;
3005}
3006
Tobias Grosser74394f02013-01-14 22:40:23 +00003007std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003008std::string Scop::getAssumedContextStr() const {
3009 return stringFromIslObj(AssumedContext);
3010}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003011std::string Scop::getBoundaryContextStr() const {
3012 return stringFromIslObj(BoundaryContext);
3013}
Tobias Grosser75805372011-04-29 06:27:02 +00003014
3015std::string Scop::getNameStr() const {
3016 std::string ExitName, EntryName;
3017 raw_string_ostream ExitStr(ExitName);
3018 raw_string_ostream EntryStr(EntryName);
3019
Tobias Grosserf240b482014-01-09 10:42:15 +00003020 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003021 EntryStr.str();
3022
3023 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003024 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003025 ExitStr.str();
3026 } else
3027 ExitName = "FunctionExit";
3028
3029 return EntryName + "---" + ExitName;
3030}
3031
Tobias Grosser74394f02013-01-14 22:40:23 +00003032__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003033__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003034 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003035}
3036
Tobias Grossere86109f2013-10-29 21:05:49 +00003037__isl_give isl_set *Scop::getAssumedContext() const {
3038 return isl_set_copy(AssumedContext);
3039}
3040
Johannes Doerfert43788c52015-08-20 05:58:56 +00003041__isl_give isl_set *Scop::getRuntimeCheckContext() const {
3042 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003043 RuntimeCheckContext =
3044 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
3045 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00003046 return RuntimeCheckContext;
3047}
3048
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003049bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003050 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003051 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00003052 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
3053 isl_set_free(RuntimeCheckContext);
3054 return IsFeasible;
3055}
3056
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003057static std::string toString(AssumptionKind Kind) {
3058 switch (Kind) {
3059 case ALIASING:
3060 return "No-aliasing";
3061 case INBOUNDS:
3062 return "Inbounds";
3063 case WRAPPING:
3064 return "No-overflows";
Johannes Doerferta4b77c02015-11-12 20:15:32 +00003065 case ALIGNMENT:
3066 return "Alignment";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003067 case ERRORBLOCK:
3068 return "No-error";
3069 case INFINITELOOP:
3070 return "Finite loop";
3071 case INVARIANTLOAD:
3072 return "Invariant load";
3073 case DELINEARIZATION:
3074 return "Delinearization";
Tobias Grosser75dc40c2015-12-20 13:31:48 +00003075 case ERROR_DOMAINCONJUNCTS:
3076 return "Low number of domain conjuncts";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003077 }
3078 llvm_unreachable("Unknown AssumptionKind!");
3079}
3080
3081void Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3082 DebugLoc Loc) {
3083 if (isl_set_is_subset(Context, Set))
3084 return;
3085
3086 if (isl_set_is_subset(AssumedContext, Set))
3087 return;
3088
3089 auto &F = *getRegion().getEntry()->getParent();
3090 std::string Msg = toString(Kind) + " assumption:\t" + stringFromIslObj(Set);
3091 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
3092}
3093
3094void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
3095 DebugLoc Loc) {
3096 trackAssumption(Kind, Set, Loc);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003097 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003098
Johannes Doerfert9d7899e2015-11-11 20:01:31 +00003099 int NSets = isl_set_n_basic_set(AssumedContext);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003100 if (NSets >= MaxDisjunctsAssumed) {
3101 isl_space *Space = isl_set_get_space(AssumedContext);
3102 isl_set_free(AssumedContext);
Tobias Grossere19fca42015-11-11 20:21:39 +00003103 AssumedContext = isl_set_empty(Space);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003104 }
3105
Tobias Grosser7b50bee2014-11-25 10:51:12 +00003106 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003107}
3108
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003109void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
3110 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc);
3111}
3112
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003113__isl_give isl_set *Scop::getBoundaryContext() const {
3114 return isl_set_copy(BoundaryContext);
3115}
3116
Tobias Grosser75805372011-04-29 06:27:02 +00003117void Scop::printContext(raw_ostream &OS) const {
3118 OS << "Context:\n";
3119
3120 if (!Context) {
3121 OS.indent(4) << "n/a\n\n";
3122 return;
3123 }
3124
3125 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003126
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003127 OS.indent(4) << "Assumed Context:\n";
3128 if (!AssumedContext) {
3129 OS.indent(4) << "n/a\n\n";
3130 return;
3131 }
3132
3133 OS.indent(4) << getAssumedContextStr() << "\n";
3134
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003135 OS.indent(4) << "Boundary Context:\n";
3136 if (!BoundaryContext) {
3137 OS.indent(4) << "n/a\n\n";
3138 return;
3139 }
3140
3141 OS.indent(4) << getBoundaryContextStr() << "\n";
3142
Tobias Grosser083d3d32014-06-28 08:59:45 +00003143 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00003144 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00003145 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
3146 }
Tobias Grosser75805372011-04-29 06:27:02 +00003147}
3148
Johannes Doerfertb164c792014-09-18 11:17:17 +00003149void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003150 int noOfGroups = 0;
3151 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003152 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003153 noOfGroups += 1;
3154 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003155 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003156 }
3157
Tobias Grosserbb853c22015-07-25 12:31:03 +00003158 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003159 if (MinMaxAliasGroups.empty()) {
3160 OS.indent(8) << "n/a\n";
3161 return;
3162 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003163
Tobias Grosserbb853c22015-07-25 12:31:03 +00003164 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003165
3166 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003167 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003168 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003169 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003170 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3171 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003172 }
3173 OS << " ]]\n";
3174 }
3175
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003176 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003177 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003178 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003179 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003180 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3181 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003182 }
3183 OS << " ]]\n";
3184 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003185 }
3186}
3187
Tobias Grosser75805372011-04-29 06:27:02 +00003188void Scop::printStatements(raw_ostream &OS) const {
3189 OS << "Statements {\n";
3190
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003191 for (const ScopStmt &Stmt : *this)
3192 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003193
3194 OS.indent(4) << "}\n";
3195}
3196
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003197void Scop::printArrayInfo(raw_ostream &OS) const {
3198 OS << "Arrays {\n";
3199
Tobias Grosserab671442015-05-23 05:58:27 +00003200 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003201 Array.second->print(OS);
3202
3203 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003204
3205 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3206
3207 for (auto &Array : arrays())
3208 Array.second->print(OS, /* SizeAsPwAff */ true);
3209
3210 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003211}
3212
Tobias Grosser75805372011-04-29 06:27:02 +00003213void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00003214 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
3215 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003216 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003217 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003218 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003219 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003220 const auto &MAs = std::get<1>(IAClass);
3221 if (MAs.empty()) {
3222 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003223 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003224 MAs.front()->print(OS);
3225 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003226 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003227 }
3228 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003229 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003230 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003231 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003232 printStatements(OS.indent(4));
3233}
3234
3235void Scop::dump() const { print(dbgs()); }
3236
Tobias Grosser9a38ab82011-11-08 15:41:03 +00003237isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00003238
Johannes Doerfertcef616f2015-09-15 22:49:04 +00003239__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
3240 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003241}
3242
Tobias Grosser808cd692015-07-14 09:33:13 +00003243__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003244 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003245
Tobias Grosser808cd692015-07-14 09:33:13 +00003246 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003247 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003248
3249 return Domain;
3250}
3251
Tobias Grossere5a35142015-11-12 14:07:09 +00003252__isl_give isl_union_map *
3253Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3254 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003255
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003256 for (ScopStmt &Stmt : *this) {
3257 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003258 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003259 continue;
3260
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003261 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003262 isl_map *AccessDomain = MA->getAccessRelation();
3263 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003264 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003265 }
3266 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003267 return isl_union_map_coalesce(Accesses);
3268}
3269
3270__isl_give isl_union_map *Scop::getMustWrites() {
3271 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003272}
3273
3274__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003275 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003276}
3277
Tobias Grosser37eb4222014-02-20 21:43:54 +00003278__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003279 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003280}
3281
3282__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003283 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003284}
3285
Tobias Grosser2ac23382015-11-12 14:07:13 +00003286__isl_give isl_union_map *Scop::getAccesses() {
3287 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3288}
3289
Tobias Grosser808cd692015-07-14 09:33:13 +00003290__isl_give isl_union_map *Scop::getSchedule() const {
3291 auto Tree = getScheduleTree();
3292 auto S = isl_schedule_get_map(Tree);
3293 isl_schedule_free(Tree);
3294 return S;
3295}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003296
Tobias Grosser808cd692015-07-14 09:33:13 +00003297__isl_give isl_schedule *Scop::getScheduleTree() const {
3298 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3299 getDomains());
3300}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003301
Tobias Grosser808cd692015-07-14 09:33:13 +00003302void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3303 auto *S = isl_schedule_from_domain(getDomains());
3304 S = isl_schedule_insert_partial_schedule(
3305 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3306 isl_schedule_free(Schedule);
3307 Schedule = S;
3308}
3309
3310void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3311 isl_schedule_free(Schedule);
3312 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003313}
3314
3315bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3316 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003317 for (ScopStmt &Stmt : *this) {
3318 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003319 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3320 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3321
3322 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3323 isl_union_set_free(StmtDomain);
3324 isl_union_set_free(NewStmtDomain);
3325 continue;
3326 }
3327
3328 Changed = true;
3329
3330 isl_union_set_free(StmtDomain);
3331 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3332
3333 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003334 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003335 isl_union_set_free(NewStmtDomain);
3336 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003337 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003338 }
3339 isl_union_set_free(Domain);
3340 return Changed;
3341}
3342
Tobias Grosser75805372011-04-29 06:27:02 +00003343ScalarEvolution *Scop::getSE() const { return SE; }
3344
Johannes Doerfertf5673802015-10-01 23:48:18 +00003345bool Scop::isIgnored(RegionNode *RN) {
3346 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Michael Krusea902ba62015-12-13 19:21:45 +00003347 ScopStmt *Stmt = getStmtForRegionNode(RN);
3348
3349 // If there is no stmt, then it already has been removed.
3350 if (!Stmt)
3351 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00003352
Johannes Doerfertf5673802015-10-01 23:48:18 +00003353 // Check if there are accesses contained.
Michael Krusea902ba62015-12-13 19:21:45 +00003354 if (Stmt->isEmpty())
Johannes Doerfertf5673802015-10-01 23:48:18 +00003355 return true;
3356
3357 // Check for reachability via non-error blocks.
3358 if (!DomainMap.count(BB))
3359 return true;
3360
3361 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003362 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003363 return true;
3364
3365 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003366}
3367
Tobias Grosser808cd692015-07-14 09:33:13 +00003368struct MapToDimensionDataTy {
3369 int N;
3370 isl_union_pw_multi_aff *Res;
3371};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003372
Tobias Grosser808cd692015-07-14 09:33:13 +00003373// @brief Create a function that maps the elements of 'Set' to its N-th
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003374// dimension and add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00003375//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003376// @param Set The input set.
3377// @param User->N The dimension to map to.
3378// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00003379//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003380// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00003381static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3382 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3383 int Dim;
3384 isl_space *Space;
3385 isl_pw_multi_aff *PMA;
3386
3387 Dim = isl_set_dim(Set, isl_dim_set);
3388 Space = isl_set_get_space(Set);
3389 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3390 Dim - Data->N);
3391 if (Data->N > 1)
3392 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3393 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3394
3395 isl_set_free(Set);
3396
3397 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003398}
3399
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003400// @brief Create an isl_multi_union_aff that defines an identity mapping
3401// from the elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003402//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003403// # Example:
3404//
3405// Domain: { A[i,j]; B[i,j,k] }
3406// N: 1
3407//
3408// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
3409//
3410// @param USet A union set describing the elements for which to generate a
3411// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00003412// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003413// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003414static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003415mapToDimension(__isl_take isl_union_set *USet, int N) {
3416 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00003417 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003418 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003419
Tobias Grosser808cd692015-07-14 09:33:13 +00003420 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00003421
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003422 auto *Space = isl_union_set_get_space(USet);
3423 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00003424
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003425 Data = {N, PwAff};
3426
3427 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
3428
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00003429 (void)Res;
3430
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003431 assert(Res == isl_stat_ok);
3432
3433 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00003434 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3435}
3436
Tobias Grosser316b5b22015-11-11 19:28:14 +00003437void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003438 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003439 Stmts.emplace_back(*this, *BB);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003440 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003441 StmtMap[BB] = Stmt;
3442 } else {
3443 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003444 Stmts.emplace_back(*this, *R);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003445 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003446 for (BasicBlock *BB : R->blocks())
3447 StmtMap[BB] = Stmt;
3448 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003449}
3450
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003451void Scop::buildSchedule() {
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003452 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
3453 Loop *L = getLoopSurroundingRegion(getRegion(), LI);
3454 LoopSchedules[L];
Tobias Grosser8362c262016-01-06 15:30:06 +00003455 buildSchedule(getRegion().getNode(), LoopSchedules);
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003456 Schedule = LoopSchedules[L].first;
3457}
3458
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003459void Scop::buildSchedule(
Tobias Grosser8362c262016-01-06 15:30:06 +00003460 RegionNode *RN,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003461 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00003462
Tobias Grosser8362c262016-01-06 15:30:06 +00003463 if (RN->isSubRegion()) {
3464 auto *LocalRegion = RN->getNodeAs<Region>();
3465 if (!SD.isNonAffineSubRegion(LocalRegion, &getRegion())) {
3466 ReversePostOrderTraversal<Region *> RTraversal(LocalRegion);
3467 for (auto *Child : RTraversal)
3468 buildSchedule(Child, LoopSchedules);
3469 return;
3470 }
3471 }
Michael Kruse046dde42015-08-10 13:01:57 +00003472
Tobias Grosser8362c262016-01-06 15:30:06 +00003473 Loop *L = getRegionNodeLoop(RN, LI);
3474 if (!getRegion().contains(L))
3475 L = getLoopSurroundingRegion(getRegion(), LI);
3476
3477 int LD = getRelativeLoopDepth(L);
3478 auto &LSchedulePair = LoopSchedules[L];
3479 LSchedulePair.second += getNumBlocksInRegionNode(RN);
3480
Tobias Grosserc9abde82016-01-23 20:23:06 +00003481 if (auto *Stmt = getStmtForRegionNode(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00003482 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3483 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
3484 LSchedulePair.first = combineInSequence(LSchedulePair.first, StmtSchedule);
3485 }
3486
3487 isl_schedule *LSchedule = LSchedulePair.first;
3488 unsigned NumVisited = LSchedulePair.second;
3489 while (L && NumVisited == L->getNumBlocks()) {
3490 auto *PL = L->getParentLoop();
3491
3492 // Either we have a proper loop and we also build a schedule for the
3493 // parent loop or we have a infinite loop that does not have a proper
3494 // parent loop. In the former case this conditional will be skipped, in
3495 // the latter case however we will break here as we do not build a domain
3496 // nor a schedule for a infinite loop.
3497 assert(LoopSchedules.count(PL) || LSchedule == nullptr);
3498 if (!LoopSchedules.count(PL))
3499 break;
3500
3501 auto &PSchedulePair = LoopSchedules[PL];
3502
3503 if (LSchedule) {
3504 auto *LDomain = isl_schedule_get_domain(LSchedule);
3505 auto *MUPA = mapToDimension(LDomain, LD + 1);
3506 LSchedule = isl_schedule_insert_partial_schedule(LSchedule, MUPA);
3507 PSchedulePair.first = combineInSequence(PSchedulePair.first, LSchedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003508 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003509
Tobias Grosser8362c262016-01-06 15:30:06 +00003510 PSchedulePair.second += NumVisited;
Johannes Doerfert30c22652015-10-18 21:17:11 +00003511
Tobias Grosser8362c262016-01-06 15:30:06 +00003512 L = PL;
3513 LD--;
3514 NumVisited = PSchedulePair.second;
3515 LSchedule = PSchedulePair.first;
Tobias Grosser808cd692015-07-14 09:33:13 +00003516 }
Tobias Grosser75805372011-04-29 06:27:02 +00003517}
3518
Johannes Doerfert7c494212014-10-31 23:13:39 +00003519ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003520 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003521 if (StmtMapIt == StmtMap.end())
3522 return nullptr;
3523 return StmtMapIt->second;
3524}
3525
Michael Krusea902ba62015-12-13 19:21:45 +00003526ScopStmt *Scop::getStmtForRegionNode(RegionNode *RN) const {
3527 return getStmtForBasicBlock(getRegionNodeBasicBlock(RN));
3528}
3529
Johannes Doerfert96425c22015-08-30 21:13:53 +00003530int Scop::getRelativeLoopDepth(const Loop *L) const {
3531 Loop *OuterLoop =
3532 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3533 if (!OuterLoop)
3534 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003535 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3536}
3537
Michael Krused868b5d2015-09-10 15:25:24 +00003538void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003539 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003540
3541 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3542 // true, are not modeled as ordinary PHI nodes as they are not part of the
3543 // region. However, we model the operands in the predecessor blocks that are
3544 // part of the region as regular scalar accesses.
3545
3546 // If we can synthesize a PHI we can skip it, however only if it is in
3547 // the region. If it is not it can only be in the exit block of the region.
3548 // In this case we model the operands but not the PHI itself.
3549 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3550 return;
3551
3552 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3553 // detection. Hence, the PHI is a load of a new memory location in which the
3554 // incoming value was written at the end of the incoming basic block.
3555 bool OnlyNonAffineSubRegionOperands = true;
3556 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3557 Value *Op = PHI->getIncomingValue(u);
3558 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3559
3560 // Do not build scalar dependences inside a non-affine subregion.
3561 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3562 continue;
3563
3564 OnlyNonAffineSubRegionOperands = false;
3565
3566 if (!R.contains(OpBB))
3567 continue;
3568
3569 Instruction *OpI = dyn_cast<Instruction>(Op);
3570 if (OpI) {
3571 BasicBlock *OpIBB = OpI->getParent();
3572 // As we pretend there is a use (or more precise a write) of OpI in OpBB
3573 // we have to insert a scalar dependence from the definition of OpI to
3574 // OpBB if the definition is not in OpBB.
Michael Kruse668af712015-10-15 14:45:48 +00003575 if (scop->getStmtForBasicBlock(OpIBB) !=
3576 scop->getStmtForBasicBlock(OpBB)) {
Michael Krusead28e5a2016-01-26 13:33:15 +00003577 ensureValueRead(OpI, OpBB);
Michael Kruse436db622016-01-26 13:33:10 +00003578 ensureValueWrite(OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003579 }
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003580 } else if (ModelReadOnlyScalars && !isa<Constant>(Op)) {
Michael Krusead28e5a2016-01-26 13:33:15 +00003581 ensureValueRead(Op, OpBB);
Michael Kruse7bf39442015-09-10 12:46:52 +00003582 }
3583
Michael Kruseee6a4fc2016-01-26 13:33:27 +00003584 ensurePHIWrite(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003585 }
3586
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003587 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3588 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003589 }
3590}
3591
Michael Krused868b5d2015-09-10 15:25:24 +00003592bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
3593 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003594 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
3595 if (isIgnoredIntrinsic(Inst))
3596 return false;
3597
3598 bool AnyCrossStmtUse = false;
3599 BasicBlock *ParentBB = Inst->getParent();
3600
3601 for (User *U : Inst->users()) {
3602 Instruction *UI = dyn_cast<Instruction>(U);
3603
3604 // Ignore the strange user
3605 if (UI == 0)
3606 continue;
3607
3608 BasicBlock *UseParent = UI->getParent();
3609
Tobias Grosserbaffa092015-10-24 20:55:27 +00003610 // Ignore basic block local uses. A value that is defined in a scop, but
3611 // used in a PHI node in the same basic block does not count as basic block
3612 // local, as for such cases a control flow edge is passed between definition
3613 // and use.
3614 if (UseParent == ParentBB && !isa<PHINode>(UI))
Michael Kruse7bf39442015-09-10 12:46:52 +00003615 continue;
3616
Michael Krusef714d472015-11-05 13:18:43 +00003617 // Uses by PHI nodes in the entry node count as external uses in case the
3618 // use is through an incoming block that is itself not contained in the
3619 // region.
3620 if (R->getEntry() == UseParent) {
3621 if (auto *PHI = dyn_cast<PHINode>(UI)) {
3622 bool ExternalUse = false;
3623 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
3624 if (PHI->getIncomingValue(i) == Inst &&
3625 !R->contains(PHI->getIncomingBlock(i))) {
3626 ExternalUse = true;
3627 break;
3628 }
3629 }
3630
3631 if (ExternalUse) {
3632 AnyCrossStmtUse = true;
3633 continue;
3634 }
3635 }
3636 }
3637
Michael Kruse7bf39442015-09-10 12:46:52 +00003638 // Do not build scalar dependences inside a non-affine subregion.
3639 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
3640 continue;
3641
Michael Kruse01cb3792015-10-17 21:07:08 +00003642 // Check for PHI nodes in the region exit and skip them, if they will be
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003643 // modeled as PHI nodes.
Michael Kruse01cb3792015-10-17 21:07:08 +00003644 //
3645 // PHI nodes in the region exit that have more than two incoming edges need
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003646 // to be modeled as PHI-Nodes to correctly model the fact that depending on
3647 // the control flow a different value will be assigned to the PHI node. In
3648 // case this is the case, there is no need to create an additional normal
3649 // scalar dependence. Hence, bail out before we register an "out-of-region"
3650 // use for this definition.
Michael Kruse01cb3792015-10-17 21:07:08 +00003651 if (isa<PHINode>(UI) && UI->getParent() == R->getExit() &&
3652 !R->getExitingBlock())
3653 continue;
3654
Michael Kruse7bf39442015-09-10 12:46:52 +00003655 // Check whether or not the use is in the SCoP.
Tobias Grosserc73d8b02015-10-23 22:36:22 +00003656 if (!R->contains(UseParent)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003657 AnyCrossStmtUse = true;
3658 continue;
3659 }
3660
3661 // If the instruction can be synthesized and the user is in the region
3662 // we do not need to add scalar dependences.
3663 if (canSynthesizeInst)
3664 continue;
3665
3666 // No need to translate these scalar dependences into polyhedral form,
3667 // because synthesizable scalars can be generated by the code generator.
3668 if (canSynthesize(UI, LI, SE, R))
3669 continue;
3670
3671 // Skip PHI nodes in the region as they handle their operands on their own.
3672 if (isa<PHINode>(UI))
3673 continue;
3674
3675 // Now U is used in another statement.
3676 AnyCrossStmtUse = true;
3677
3678 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00003679 // Use the def instruction as base address of the MemoryAccess, so that it
3680 // will become the name of the scalar access in the polyhedral form.
Michael Krusead28e5a2016-01-26 13:33:15 +00003681 ensureValueRead(Inst, UI->getParent());
Michael Kruse7bf39442015-09-10 12:46:52 +00003682 }
3683
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003684 if (ModelReadOnlyScalars && !isa<PHINode>(Inst)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003685 for (Value *Op : Inst->operands()) {
3686 if (canSynthesize(Op, LI, SE, R))
3687 continue;
3688
3689 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
3690 if (R->contains(OpInst))
3691 continue;
3692
3693 if (isa<Constant>(Op))
3694 continue;
3695
Michael Krusead28e5a2016-01-26 13:33:15 +00003696 ensureValueRead(Op, Inst->getParent());
Michael Kruse7bf39442015-09-10 12:46:52 +00003697 }
3698 }
3699
3700 return AnyCrossStmtUse;
3701}
3702
3703extern MapInsnToMemAcc InsnToMemAcc;
3704
Michael Krusee2bccbb2015-09-18 19:59:43 +00003705void ScopInfo::buildMemoryAccess(
Michael Kruse70131d32016-01-27 17:09:17 +00003706 MemAccInst Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003707 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3708 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003709
Michael Kruse70131d32016-01-27 17:09:17 +00003710 Value *Address = Inst.getPointerOperand();
3711 Value *Val = Inst.getValueOperand();
3712 Type *SizeType = Val->getType();
3713 unsigned Size = TD->getTypeAllocSize(SizeType);
3714 enum MemoryAccess::AccessType Type =
3715 Inst.isLoad() ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003716
3717 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003718 const SCEVUnknown *BasePointer =
3719 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3720
3721 assert(BasePointer && "Could not find base pointer");
3722 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
3723
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003724 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3725 auto NewAddress = Address;
3726 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3727 auto Src = BitCast->getOperand(0);
3728 auto SrcTy = Src->getType();
3729 auto DstTy = BitCast->getType();
3730 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3731 NewAddress = Src;
3732 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003733
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003734 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3735 std::vector<const SCEV *> Subscripts;
3736 std::vector<int> Sizes;
3737 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3738 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003739
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003740 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003741
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003742 bool AllAffineSubcripts = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003743 for (auto Subscript : Subscripts) {
3744 InvariantLoadsSetTy AccessILS;
3745 AllAffineSubcripts =
3746 isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS);
3747
3748 for (LoadInst *LInst : AccessILS)
3749 if (!ScopRIL.count(LInst))
3750 AllAffineSubcripts = false;
3751
3752 if (!AllAffineSubcripts)
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003753 break;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003754 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003755
3756 if (AllAffineSubcripts && Sizes.size() > 0) {
3757 for (auto V : Sizes)
3758 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3759 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003760 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003761 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003762
Tobias Grossera535dff2015-12-13 19:59:01 +00003763 addArrayAccess(Inst, Type, BasePointer->getValue(), Size, true,
3764 Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00003765 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003766 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003767 }
3768 }
3769
Michael Kruse7bf39442015-09-10 12:46:52 +00003770 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003771 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003772 addArrayAccess(Inst, Type, BasePointer->getValue(), Size, true,
3773 AccItr->second.DelinearizedSubscripts,
3774 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003775 return;
3776 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003777
3778 // Check if the access depends on a loop contained in a non-affine subregion.
3779 bool isVariantInNonAffineLoop = false;
3780 if (BoxedLoops) {
3781 SetVector<const Loop *> Loops;
3782 findLoops(AccessFunction, Loops);
3783 for (const Loop *L : Loops)
3784 if (BoxedLoops->count(L))
3785 isVariantInNonAffineLoop = true;
3786 }
3787
Johannes Doerfert09e36972015-10-07 20:17:36 +00003788 InvariantLoadsSetTy AccessILS;
3789 bool IsAffine =
3790 !isVariantInNonAffineLoop &&
3791 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3792
3793 for (LoadInst *LInst : AccessILS)
3794 if (!ScopRIL.count(LInst))
3795 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003796
Michael Krusecaac2b62015-09-26 15:51:44 +00003797 // FIXME: Size of the number of bytes of an array element, not the number of
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003798 // elements as probably intended here.
Tobias Grossera43b6e92015-09-27 17:54:50 +00003799 const SCEV *SizeSCEV =
Michael Kruse70131d32016-01-27 17:09:17 +00003800 SE->getConstant(TD->getIntPtrType(Inst.getContext()), Size);
Michael Kruse7bf39442015-09-10 12:46:52 +00003801
Michael Krusee2bccbb2015-09-18 19:59:43 +00003802 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3803 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003804
Tobias Grossera535dff2015-12-13 19:59:01 +00003805 addArrayAccess(Inst, Type, BasePointer->getValue(), Size, IsAffine,
3806 ArrayRef<const SCEV *>(AccessFunction),
3807 ArrayRef<const SCEV *>(SizeSCEV), Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003808}
3809
Michael Krused868b5d2015-09-10 15:25:24 +00003810void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003811
3812 if (SD->isNonAffineSubRegion(&SR, &R)) {
3813 for (BasicBlock *BB : SR.blocks())
3814 buildAccessFunctions(R, *BB, &SR);
3815 return;
3816 }
3817
3818 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3819 if (I->isSubRegion())
3820 buildAccessFunctions(R, *I->getNodeAs<Region>());
3821 else
3822 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
3823}
3824
Michael Krusecac948e2015-10-02 13:53:07 +00003825void ScopInfo::buildStmts(Region &SR) {
3826 Region *R = getRegion();
3827
3828 if (SD->isNonAffineSubRegion(&SR, R)) {
3829 scop->addScopStmt(nullptr, &SR);
3830 return;
3831 }
3832
3833 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3834 if (I->isSubRegion())
3835 buildStmts(*I->getNodeAs<Region>());
3836 else
3837 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
3838}
3839
Michael Krused868b5d2015-09-10 15:25:24 +00003840void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
3841 Region *NonAffineSubRegion,
3842 bool IsExitBlock) {
Tobias Grosser910cf262015-11-11 20:15:49 +00003843 // We do not build access functions for error blocks, as they may contain
3844 // instructions we can not model.
3845 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3846 if (isErrorBlock(BB, R, *LI, DT) && !IsExitBlock)
3847 return;
3848
Michael Kruse7bf39442015-09-10 12:46:52 +00003849 Loop *L = LI->getLoopFor(&BB);
3850
3851 // The set of loops contained in non-affine subregions that are part of R.
3852 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3853
Johannes Doerfert09e36972015-10-07 20:17:36 +00003854 // The set of loads that are required to be invariant.
3855 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
3856
Michael Kruse7bf39442015-09-10 12:46:52 +00003857 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00003858 Instruction *Inst = &*I;
Michael Kruse7bf39442015-09-10 12:46:52 +00003859
3860 PHINode *PHI = dyn_cast<PHINode>(Inst);
3861 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003862 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003863
3864 // For the exit block we stop modeling after the last PHI node.
3865 if (!PHI && IsExitBlock)
3866 break;
3867
Johannes Doerfert09e36972015-10-07 20:17:36 +00003868 // TODO: At this point we only know that elements of ScopRIL have to be
3869 // invariant and will be hoisted for the SCoP to be processed. Though,
3870 // there might be other invariant accesses that will be hoisted and
3871 // that would allow to make a non-affine access affine.
Michael Kruse70131d32016-01-27 17:09:17 +00003872 if (auto MemInst = MemAccInst::dyn_cast(Inst))
3873 buildMemoryAccess(MemInst, L, &R, BoxedLoops, ScopRIL);
Michael Kruse7bf39442015-09-10 12:46:52 +00003874
3875 if (isIgnoredIntrinsic(Inst))
3876 continue;
3877
Johannes Doerfert09e36972015-10-07 20:17:36 +00003878 // Do not build scalar dependences for required invariant loads as we will
3879 // hoist them later on anyway or drop the SCoP if we cannot.
3880 if (ScopRIL.count(dyn_cast<LoadInst>(Inst)))
3881 continue;
3882
Michael Kruse7bf39442015-09-10 12:46:52 +00003883 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00003884 if (!isa<StoreInst>(Inst))
Michael Kruse436db622016-01-26 13:33:10 +00003885 ensureValueWrite(Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003886 }
3887 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003888}
Michael Kruse7bf39442015-09-10 12:46:52 +00003889
Michael Kruseee6a4fc2016-01-26 13:33:27 +00003890MemoryAccess *ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3891 MemoryAccess::AccessType Type,
3892 Value *BaseAddress, unsigned ElemBytes,
3893 bool Affine, Value *AccessValue,
3894 ArrayRef<const SCEV *> Subscripts,
3895 ArrayRef<const SCEV *> Sizes,
3896 ScopArrayInfo::MemoryKind Kind) {
Michael Krusecac948e2015-10-02 13:53:07 +00003897 ScopStmt *Stmt = scop->getStmtForBasicBlock(BB);
3898
3899 // Do not create a memory access for anything not in the SCoP. It would be
3900 // ignored anyway.
3901 if (!Stmt)
Michael Kruseee6a4fc2016-01-26 13:33:27 +00003902 return nullptr;
Michael Krusecac948e2015-10-02 13:53:07 +00003903
Michael Krusee2bccbb2015-09-18 19:59:43 +00003904 AccFuncSetType &AccList = AccFuncMap[BB];
Michael Krusee2bccbb2015-09-18 19:59:43 +00003905 Value *BaseAddr = BaseAddress;
3906 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3907
Tobias Grosserf4f68702015-12-14 15:05:37 +00003908 bool isKnownMustAccess = false;
3909
3910 // Accesses in single-basic block statements are always excuted.
3911 if (Stmt->isBlockStmt())
3912 isKnownMustAccess = true;
3913
3914 if (Stmt->isRegionStmt()) {
3915 // Accesses that dominate the exit block of a non-affine region are always
3916 // executed. In non-affine regions there may exist MK_Values that do not
3917 // dominate the exit. MK_Values will always dominate the exit and MK_PHIs
3918 // only if there is at most one PHI_WRITE in the non-affine region.
3919 if (DT->dominates(BB, Stmt->getRegion()->getExit()))
3920 isKnownMustAccess = true;
3921 }
3922
Michael Kruseee6a4fc2016-01-26 13:33:27 +00003923 // Non-affine PHI writes do not "happen" at a particular instruction, but
3924 // after exiting the statement. Therefore they are guaranteed execute and
3925 // overwrite the old value.
3926 if (Kind == ScopArrayInfo::MK_PHI || Kind == ScopArrayInfo::MK_ExitPHI)
3927 isKnownMustAccess = true;
3928
Tobias Grosserf4f68702015-12-14 15:05:37 +00003929 if (!isKnownMustAccess && Type == MemoryAccess::MUST_WRITE)
Michael Krusecac948e2015-10-02 13:53:07 +00003930 Type = MemoryAccess::MAY_WRITE;
3931
Tobias Grosserf1bfd752015-11-05 20:15:37 +00003932 AccList.emplace_back(Stmt, Inst, Type, BaseAddress, ElemBytes, Affine,
Tobias Grossera535dff2015-12-13 19:59:01 +00003933 Subscripts, Sizes, AccessValue, Kind, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00003934 Stmt->addAccess(&AccList.back());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00003935 return &AccList.back();
Michael Kruse7bf39442015-09-10 12:46:52 +00003936}
3937
Michael Kruse70131d32016-01-27 17:09:17 +00003938void ScopInfo::addArrayAccess(MemAccInst MemAccInst,
Tobias Grossera535dff2015-12-13 19:59:01 +00003939 MemoryAccess::AccessType Type, Value *BaseAddress,
3940 unsigned ElemBytes, bool IsAffine,
3941 ArrayRef<const SCEV *> Subscripts,
3942 ArrayRef<const SCEV *> Sizes,
3943 Value *AccessValue) {
Michael Kruse70131d32016-01-27 17:09:17 +00003944 assert(MemAccInst.isLoad() == (Type == MemoryAccess::READ));
3945 addMemoryAccess(MemAccInst.getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003946 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00003947 ScopArrayInfo::MK_Array);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003948}
Michael Kruse436db622016-01-26 13:33:10 +00003949void ScopInfo::ensureValueWrite(Instruction *Value) {
3950 ScopStmt *Stmt = scop->getStmtForBasicBlock(Value->getParent());
3951
3952 // Value not defined within this SCoP.
3953 if (!Stmt)
3954 return;
3955
3956 // Do not process further if the value is already written.
3957 if (Stmt->lookupValueWriteOf(Value))
3958 return;
3959
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003960 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
3961 true, Value, ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00003962 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003963}
Michael Krusead28e5a2016-01-26 13:33:15 +00003964void ScopInfo::ensureValueRead(Value *Value, BasicBlock *UserBB) {
Michael Krusefd463082016-01-27 22:51:56 +00003965
3966 // If the instruction can be synthesized and the user is in the region we do
3967 // not need to add a value dependences.
3968 Region &ScopRegion = scop->getRegion();
3969 if (canSynthesize(Value, LI, SE, &ScopRegion))
3970 return;
3971
Michael Krusead28e5a2016-01-26 13:33:15 +00003972 ScopStmt *UserStmt = scop->getStmtForBasicBlock(UserBB);
3973
3974 // We do not model uses outside the scop.
3975 if (!UserStmt)
3976 return;
3977
3978 // Do not create another MemoryAccess for reloading the value if one already
3979 // exists.
3980 if (UserStmt->lookupValueReadOf(Value))
3981 return;
3982
3983 addMemoryAccess(UserBB, nullptr, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003984 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00003985 ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003986}
Michael Kruseee6a4fc2016-01-26 13:33:27 +00003987void ScopInfo::ensurePHIWrite(PHINode *PHI, BasicBlock *IncomingBlock,
3988 Value *IncomingValue, bool IsExitBlock) {
3989 ScopStmt *IncomingStmt = scop->getStmtForBasicBlock(IncomingBlock);
3990
3991 // Do not add more than one MemoryAccess per PHINode and ScopStmt.
3992 if (MemoryAccess *Acc = IncomingStmt->lookupPHIWriteOf(PHI)) {
3993 assert(Acc->getAccessInstruction() == PHI);
3994 Acc->addIncoming(IncomingBlock, IncomingValue);
3995 return;
3996 }
3997
3998 MemoryAccess *Acc = addMemoryAccess(
3999 IncomingStmt->isBlockStmt() ? IncomingBlock
4000 : IncomingStmt->getRegion()->getEntry(),
4001 PHI, MemoryAccess::MUST_WRITE, PHI, 1, true, PHI,
4002 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
4003 IsExitBlock ? ScopArrayInfo::MK_ExitPHI : ScopArrayInfo::MK_PHI);
4004 assert(Acc);
4005 Acc->addIncoming(IncomingBlock, IncomingValue);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004006}
4007void ScopInfo::addPHIReadAccess(PHINode *PHI) {
4008 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00004009 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004010 ScopArrayInfo::MK_PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004011}
4012
Michael Krusedaf66942015-12-13 22:10:37 +00004013void ScopInfo::buildScop(Region &R, AssumptionCache &AC) {
Michael Kruse9d080092015-09-11 21:41:48 +00004014 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Michael Krusedaf66942015-12-13 22:10:37 +00004015 scop = new Scop(R, AccFuncMap, *SD, *SE, *DT, *LI, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00004016
Michael Krusecac948e2015-10-02 13:53:07 +00004017 buildStmts(R);
Michael Kruse7bf39442015-09-10 12:46:52 +00004018 buildAccessFunctions(R, R);
4019
4020 // In case the region does not have an exiting block we will later (during
4021 // code generation) split the exit block. This will move potential PHI nodes
4022 // from the current exit block into the new region exiting block. Hence, PHI
4023 // nodes that are at this point not part of the region will be.
4024 // To handle these PHI nodes later we will now model their operands as scalar
4025 // accesses. Note that we do not model anything in the exit block if we have
4026 // an exiting block in the region, as there will not be any splitting later.
4027 if (!R.getExitingBlock())
4028 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
4029
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004030 scop->init(*AA, AC);
Michael Kruse7bf39442015-09-10 12:46:52 +00004031}
4032
Michael Krused868b5d2015-09-10 15:25:24 +00004033void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00004034 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00004035 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00004036 return;
4037 }
4038
Michael Kruse9d080092015-09-11 21:41:48 +00004039 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00004040}
4041
Michael Krused868b5d2015-09-10 15:25:24 +00004042void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00004043 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00004044 if (scop) {
4045 delete scop;
4046 scop = 0;
4047 }
Michael Kruse7bf39442015-09-10 12:46:52 +00004048}
4049
4050//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00004051ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00004052 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00004053 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00004054}
4055
4056ScopInfo::~ScopInfo() {
4057 clear();
4058 isl_ctx_free(ctx);
4059}
4060
Tobias Grosser75805372011-04-29 06:27:02 +00004061void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00004062 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00004063 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00004064 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00004065 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4066 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004067 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004068 AU.addRequired<AssumptionCacheTracker>();
Tobias Grosser75805372011-04-29 06:27:02 +00004069 AU.setPreservesAll();
4070}
4071
4072bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00004073 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00004074
Michael Krused868b5d2015-09-10 15:25:24 +00004075 if (!SD->isMaxRegionInScop(*R))
4076 return false;
4077
4078 Function *F = R->getEntry()->getParent();
4079 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4080 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4081 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
4082 TD = &F->getParent()->getDataLayout();
Michael Krusedaf66942015-12-13 22:10:37 +00004083 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004084 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krused868b5d2015-09-10 15:25:24 +00004085
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004086 DebugLoc Beg, End;
4087 getDebugLocations(R, Beg, End);
4088 std::string Msg = "SCoP begins here.";
4089 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg);
4090
Michael Krusedaf66942015-12-13 22:10:37 +00004091 buildScop(*R, AC);
Tobias Grosser75805372011-04-29 06:27:02 +00004092
Tobias Grosserd6a50b32015-05-30 06:26:21 +00004093 DEBUG(scop->print(dbgs()));
4094
Michael Kruseafe06702015-10-02 16:33:27 +00004095 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004096 Msg = "SCoP ends here but was dismissed.";
Johannes Doerfert43788c52015-08-20 05:58:56 +00004097 delete scop;
4098 scop = nullptr;
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004099 } else {
4100 Msg = "SCoP ends here.";
4101 ++ScopFound;
4102 if (scop->getMaxLoopDepth() > 0)
4103 ++RichScopFound;
Johannes Doerfert43788c52015-08-20 05:58:56 +00004104 }
4105
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004106 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg);
4107
Tobias Grosser75805372011-04-29 06:27:02 +00004108 return false;
4109}
4110
4111char ScopInfo::ID = 0;
4112
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004113Pass *polly::createScopInfoPass() { return new ScopInfo(); }
4114
Tobias Grosser73600b82011-10-08 00:30:40 +00004115INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
4116 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004117 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004118INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004119INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004120INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004121INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004122INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004123INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004124INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00004125INITIALIZE_PASS_END(ScopInfo, "polly-scops",
4126 "Polly - Create polyhedral description of Scops", false,
4127 false)