blob: 80d138074065567d1e1fa9518730d8ec68936f37 [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
Craig Topper7fb6e472016-01-31 20:36:20 +00001623 ParameterName = "p_" + utostr(IdIter->second);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001624
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
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001990 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00001991 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001992}
1993
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001994static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
1995 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00001996 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001997 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00001998 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001999 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002000 return true;
2001 return false;
2002}
2003
Johannes Doerfert96425c22015-08-30 21:13:53 +00002004///}
2005
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002006static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2007 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002008 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002009 isl_id *DimId =
2010 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2011 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2012}
2013
Johannes Doerfert96425c22015-08-30 21:13:53 +00002014isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
2015 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
2016 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002017 return getDomainConditions(BB);
2018}
2019
2020isl_set *Scop::getDomainConditions(BasicBlock *BB) {
2021 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002022 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002023}
2024
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002025void Scop::removeErrorBlockDomains() {
2026 auto removeDomains = [this](BasicBlock *Start) {
2027 auto BBNode = DT.getNode(Start);
2028 for (auto ErrorChild : depth_first(BBNode)) {
2029 auto ErrorChildBlock = ErrorChild->getBlock();
2030 auto CurrentDomain = DomainMap[ErrorChildBlock];
2031 auto Empty = isl_set_empty(isl_set_get_space(CurrentDomain));
2032 DomainMap[ErrorChildBlock] = Empty;
2033 isl_set_free(CurrentDomain);
2034 }
2035 };
2036
Tobias Grosser5ef2bc32015-11-23 10:18:23 +00002037 SmallVector<Region *, 4> Todo = {&R};
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002038
2039 while (!Todo.empty()) {
2040 auto SubRegion = Todo.back();
2041 Todo.pop_back();
2042
2043 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
2044 for (auto &Child : *SubRegion)
2045 Todo.push_back(Child.get());
2046 continue;
2047 }
2048 if (containsErrorBlock(SubRegion->getNode(), getRegion(), LI, DT))
2049 removeDomains(SubRegion->getEntry());
2050 }
2051
2052 for (auto BB : R.blocks())
2053 if (isErrorBlock(*BB, R, LI, DT))
2054 removeDomains(BB);
2055}
2056
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002057void Scop::buildDomains(Region *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002058
Johannes Doerfert432658d2016-01-26 11:01:41 +00002059 bool IsOnlyNonAffineRegion = SD.isNonAffineSubRegion(R, R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002060 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002061 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2062 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002063 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002064
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002065 while (LD-- >= 0) {
2066 S = addDomainDimId(S, LD + 1, L);
2067 L = L->getParentLoop();
2068 }
2069
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002070 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002071
Johannes Doerfert432658d2016-01-26 11:01:41 +00002072 if (IsOnlyNonAffineRegion)
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002073 return;
2074
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002075 buildDomainsWithBranchConstraints(R);
2076 propagateDomainConstraints(R);
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002077
2078 // Error blocks and blocks dominated by them have been assumed to never be
2079 // executed. Representing them in the Scop does not add any value. In fact,
2080 // it is likely to cause issues during construction of the ScopStmts. The
2081 // contents of error blocks have not been verfied to be expressible and
2082 // will cause problems when building up a ScopStmt for them.
2083 // Furthermore, basic blocks dominated by error blocks may reference
2084 // instructions in the error block which, if the error block is not modeled,
2085 // can themselves not be constructed properly.
2086 removeErrorBlockDomains();
Johannes Doerfert96425c22015-08-30 21:13:53 +00002087}
2088
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002089void Scop::buildDomainsWithBranchConstraints(Region *R) {
Johannes Doerfert6f50c292016-01-26 11:03:25 +00002090 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002091
2092 // To create the domain for each block in R we iterate over all blocks and
2093 // subregions in R and propagate the conditions under which the current region
2094 // element is executed. To this end we iterate in reverse post order over R as
2095 // it ensures that we first visit all predecessors of a region node (either a
2096 // basic block or a subregion) before we visit the region node itself.
2097 // Initially, only the domain for the SCoP region entry block is set and from
2098 // there we propagate the current domain to all successors, however we add the
2099 // condition that the successor is actually executed next.
2100 // As we are only interested in non-loop carried constraints here we can
2101 // simply skip loop back edges.
2102
2103 ReversePostOrderTraversal<Region *> RTraversal(R);
2104 for (auto *RN : RTraversal) {
2105
2106 // Recurse for affine subregions but go on for basic blocks and non-affine
2107 // subregions.
2108 if (RN->isSubRegion()) {
2109 Region *SubRegion = RN->getNodeAs<Region>();
2110 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002111 buildDomainsWithBranchConstraints(SubRegion);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002112 continue;
2113 }
2114 }
2115
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002116 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002117 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002118
Johannes Doerfert96425c22015-08-30 21:13:53 +00002119 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002120 TerminatorInst *TI = BB->getTerminator();
2121
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002122 if (isa<UnreachableInst>(TI))
2123 continue;
2124
Johannes Doerfertf5673802015-10-01 23:48:18 +00002125 isl_set *Domain = DomainMap.lookup(BB);
2126 if (!Domain) {
2127 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2128 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002129 continue;
2130 }
2131
Johannes Doerfert96425c22015-08-30 21:13:53 +00002132 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002133
2134 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2135 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2136
2137 // Build the condition sets for the successor nodes of the current region
2138 // node. If it is a non-affine subregion we will always execute the single
2139 // exit node, hence the single entry node domain is the condition set. For
2140 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002141 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002142 if (RN->isSubRegion())
2143 ConditionSets.push_back(isl_set_copy(Domain));
2144 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002145 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002146
2147 // Now iterate over the successors and set their initial domain based on
2148 // their condition set. We skip back edges here and have to be careful when
2149 // we leave a loop not to keep constraints over a dimension that doesn't
2150 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002151 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002152 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002153 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002154 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002155
2156 // Skip back edges.
2157 if (DT.dominates(SuccBB, BB)) {
2158 isl_set_free(CondSet);
2159 continue;
2160 }
2161
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002162 // Do not adjust the number of dimensions if we enter a boxed loop or are
2163 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002164 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfert6f50c292016-01-26 11:03:25 +00002165 while (BoxedLoops.count(SuccBBLoop))
2166 SuccBBLoop = SuccBBLoop->getParentLoop();
Johannes Doerfert634909c2015-10-04 14:57:41 +00002167
2168 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002169
2170 // Check if the edge to SuccBB is a loop entry or exit edge. If so
2171 // adjust the dimensionality accordingly. Lastly, if we leave a loop
2172 // and enter a new one we need to drop the old constraints.
2173 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002174 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002175 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002176 CondSet = isl_set_project_out(CondSet, isl_dim_set,
2177 isl_set_n_dim(CondSet) - LoopDepthDiff,
2178 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002179 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002180 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002181 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002182 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002183 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002184 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002185 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
2186 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 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002189 }
2190
2191 // Set the domain for the successor or merge it with an existing domain in
2192 // case there are multiple paths (without loop back edges) to the
2193 // successor block.
2194 isl_set *&SuccDomain = DomainMap[SuccBB];
2195 if (!SuccDomain)
2196 SuccDomain = CondSet;
2197 else
2198 SuccDomain = isl_set_union(SuccDomain, CondSet);
2199
2200 SuccDomain = isl_set_coalesce(SuccDomain);
Tobias Grosser75dc40c2015-12-20 13:31:48 +00002201 if (isl_set_n_basic_set(SuccDomain) > MaxConjunctsInDomain) {
2202 auto *Empty = isl_set_empty(isl_set_get_space(SuccDomain));
2203 isl_set_free(SuccDomain);
2204 SuccDomain = Empty;
2205 invalidate(ERROR_DOMAINCONJUNCTS, DebugLoc());
2206 }
Johannes Doerfert634909c2015-10-04 14:57:41 +00002207 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
2208 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002209 }
2210 }
2211}
2212
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002213/// @brief Return the domain for @p BB wrt @p DomainMap.
2214///
2215/// This helper function will lookup @p BB in @p DomainMap but also handle the
2216/// case where @p BB is contained in a non-affine subregion using the region
2217/// tree obtained by @p RI.
2218static __isl_give isl_set *
2219getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
2220 RegionInfo &RI) {
2221 auto DIt = DomainMap.find(BB);
2222 if (DIt != DomainMap.end())
2223 return isl_set_copy(DIt->getSecond());
2224
2225 Region *R = RI.getRegionFor(BB);
2226 while (R->getEntry() == BB)
2227 R = R->getParent();
2228 return getDomainForBlock(R->getEntry(), DomainMap, RI);
2229}
2230
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002231void Scop::propagateDomainConstraints(Region *R) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002232 // Iterate over the region R and propagate the domain constrains from the
2233 // predecessors to the current node. In contrast to the
2234 // buildDomainsWithBranchConstraints function, this one will pull the domain
2235 // information from the predecessors instead of pushing it to the successors.
2236 // Additionally, we assume the domains to be already present in the domain
2237 // map here. However, we iterate again in reverse post order so we know all
2238 // predecessors have been visited before a block or non-affine subregion is
2239 // visited.
2240
2241 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2242 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2243
2244 ReversePostOrderTraversal<Region *> RTraversal(R);
2245 for (auto *RN : RTraversal) {
2246
2247 // Recurse for affine subregions but go on for basic blocks and non-affine
2248 // subregions.
2249 if (RN->isSubRegion()) {
2250 Region *SubRegion = RN->getNodeAs<Region>();
2251 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002252 propagateDomainConstraints(SubRegion);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002253 continue;
2254 }
2255 }
2256
Johannes Doerfertf5673802015-10-01 23:48:18 +00002257 // Get the domain for the current block and check if it was initialized or
2258 // not. The only way it was not is if this block is only reachable via error
2259 // blocks, thus will not be executed under the assumptions we make. Such
2260 // blocks have to be skipped as their predecessors might not have domains
2261 // either. It would not benefit us to compute the domain anyway, only the
2262 // domains of the error blocks that are reachable from non-error blocks
2263 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002264 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002265 isl_set *&Domain = DomainMap[BB];
2266 if (!Domain) {
2267 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2268 << ", it is only reachable from error blocks.\n");
2269 DomainMap.erase(BB);
2270 continue;
2271 }
2272 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
2273
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002274 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2275 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2276
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002277 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2278 for (auto *PredBB : predecessors(BB)) {
2279
2280 // Skip backedges
2281 if (DT.dominates(BB, PredBB))
2282 continue;
2283
2284 isl_set *PredBBDom = nullptr;
2285
2286 // Handle the SCoP entry block with its outside predecessors.
2287 if (!getRegion().contains(PredBB))
2288 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
2289
2290 if (!PredBBDom) {
2291 // Determine the loop depth of the predecessor and adjust its domain to
2292 // the domain of the current block. This can mean we have to:
2293 // o) Drop a dimension if this block is the exit of a loop, not the
2294 // header of a new loop and the predecessor was part of the loop.
2295 // o) Add an unconstrainted new dimension if this block is the header
2296 // of a loop and the predecessor is not part of it.
2297 // o) Drop the information about the innermost loop dimension when the
2298 // predecessor and the current block are surrounded by different
2299 // loops in the same depth.
2300 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2301 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2302 while (BoxedLoops.count(PredBBLoop))
2303 PredBBLoop = PredBBLoop->getParentLoop();
2304
2305 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002306 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002307 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002308 PredBBDom = isl_set_project_out(
2309 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2310 LoopDepthDiff);
2311 else if (PredBBLoopDepth < BBLoopDepth) {
2312 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002313 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002314 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2315 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002316 PredBBDom = isl_set_drop_constraints_involving_dims(
2317 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002318 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002319 }
2320
2321 PredDom = isl_set_union(PredDom, PredBBDom);
2322 }
2323
2324 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002325 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002326
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002327 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002328 addLoopBoundsToHeaderDomain(BBLoop);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002329
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002330 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002331 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002332 IsOptimized = true;
2333 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002334 addAssumption(ERRORBLOCK, isl_set_complement(DomPar),
2335 BB->getTerminator()->getDebugLoc());
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002336 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002337 }
2338}
2339
2340/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2341/// is incremented by one and all other dimensions are equal, e.g.,
2342/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2343/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2344static __isl_give isl_map *
2345createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2346 auto *MapSpace = isl_space_map_from_set(SetSpace);
2347 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2348 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2349 if (u != Dim)
2350 NextIterationMap =
2351 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2352 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2353 C = isl_constraint_set_constant_si(C, 1);
2354 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2355 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2356 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2357 return NextIterationMap;
2358}
2359
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002360void Scop::addLoopBoundsToHeaderDomain(Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002361 int LoopDepth = getRelativeLoopDepth(L);
2362 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002363
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002364 BasicBlock *HeaderBB = L->getHeader();
2365 assert(DomainMap.count(HeaderBB));
2366 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002367
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002368 isl_map *NextIterationMap =
2369 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002370
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002371 isl_set *UnionBackedgeCondition =
2372 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002373
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002374 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2375 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002376
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002377 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002378
2379 // If the latch is only reachable via error statements we skip it.
2380 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2381 if (!LatchBBDom)
2382 continue;
2383
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002384 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002385
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002386 TerminatorInst *TI = LatchBB->getTerminator();
2387 BranchInst *BI = dyn_cast<BranchInst>(TI);
2388 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002389 BackedgeCondition = isl_set_copy(LatchBBDom);
2390 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002391 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002392 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002393 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002394
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002395 // Free the non back edge condition set as we do not need it.
2396 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002397
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002398 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002399 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002400
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002401 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2402 assert(LatchLoopDepth >= LoopDepth);
2403 BackedgeCondition =
2404 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2405 LatchLoopDepth - LoopDepth);
2406 UnionBackedgeCondition =
2407 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002408 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002409
2410 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2411 for (int i = 0; i < LoopDepth; i++)
2412 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2413
2414 isl_set *UnionBackedgeConditionComplement =
2415 isl_set_complement(UnionBackedgeCondition);
2416 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2417 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2418 UnionBackedgeConditionComplement =
2419 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2420 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2421 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2422
2423 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2424 HeaderBBDom = Parts.second;
2425
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002426 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2427 // the bounded assumptions to the context as they are already implied by the
2428 // <nsw> tag.
2429 if (Affinator.hasNSWAddRecForLoop(L)) {
2430 isl_set_free(Parts.first);
2431 return;
2432 }
2433
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002434 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2435 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002436 addAssumption(INFINITELOOP, BoundedCtx,
2437 HeaderBB->getTerminator()->getDebugLoc());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002438}
2439
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002440void Scop::buildAliasChecks(AliasAnalysis &AA) {
2441 if (!PollyUseRuntimeAliasChecks)
2442 return;
2443
2444 if (buildAliasGroups(AA))
2445 return;
2446
2447 // If a problem occurs while building the alias groups we need to delete
2448 // this SCoP and pretend it wasn't valid in the first place. To this end
2449 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002450 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002451
2452 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2453 << " could not be created as the number of parameters involved "
2454 "is too high. The SCoP will be "
2455 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2456 "the maximal number of parameters but be advised that the "
2457 "compile time might increase exponentially.\n\n");
2458}
2459
Johannes Doerfert9143d672014-09-27 11:02:39 +00002460bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002461 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002462 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002463 // for all memory accesses inside the SCoP.
2464 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002465 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002466 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002467 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002468 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002469 // if their access domains intersect, otherwise they are in different
2470 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002471 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002472 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002473 // and maximal accesses to each array of a group in read only and non
2474 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002475 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2476
2477 AliasSetTracker AST(AA);
2478
2479 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002480 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002481 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002482
2483 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002484 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002485 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2486 isl_set_free(StmtDomain);
2487 if (StmtDomainEmpty)
2488 continue;
2489
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002490 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002491 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002492 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002493 if (!MA->isRead())
2494 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002495 MemAccInst Acc(MA->getAccessInstruction());
2496 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002497 AST.add(Acc);
2498 }
2499 }
2500
2501 SmallVector<AliasGroupTy, 4> AliasGroups;
2502 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002503 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002504 continue;
2505 AliasGroupTy AG;
2506 for (auto PR : AS)
2507 AG.push_back(PtrToAcc[PR.getValue()]);
2508 assert(AG.size() > 1 &&
2509 "Alias groups should contain at least two accesses");
2510 AliasGroups.push_back(std::move(AG));
2511 }
2512
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002513 // Split the alias groups based on their domain.
2514 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2515 AliasGroupTy NewAG;
2516 AliasGroupTy &AG = AliasGroups[u];
2517 AliasGroupTy::iterator AGI = AG.begin();
2518 isl_set *AGDomain = getAccessDomain(*AGI);
2519 while (AGI != AG.end()) {
2520 MemoryAccess *MA = *AGI;
2521 isl_set *MADomain = getAccessDomain(MA);
2522 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2523 NewAG.push_back(MA);
2524 AGI = AG.erase(AGI);
2525 isl_set_free(MADomain);
2526 } else {
2527 AGDomain = isl_set_union(AGDomain, MADomain);
2528 AGI++;
2529 }
2530 }
2531 if (NewAG.size() > 1)
2532 AliasGroups.push_back(std::move(NewAG));
2533 isl_set_free(AGDomain);
2534 }
2535
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002536 auto &F = *getRegion().getEntry()->getParent();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002537 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002538 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2539 for (AliasGroupTy &AG : AliasGroups) {
2540 NonReadOnlyBaseValues.clear();
2541 ReadOnlyPairs.clear();
2542
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002543 if (AG.size() < 2) {
2544 AG.clear();
2545 continue;
2546 }
2547
Johannes Doerfert13771732014-10-01 12:40:46 +00002548 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002549 emitOptimizationRemarkAnalysis(
2550 F.getContext(), DEBUG_TYPE, F,
2551 (*II)->getAccessInstruction()->getDebugLoc(),
2552 "Possibly aliasing pointer, use restrict keyword.");
2553
Johannes Doerfert13771732014-10-01 12:40:46 +00002554 Value *BaseAddr = (*II)->getBaseAddr();
2555 if (HasWriteAccess.count(BaseAddr)) {
2556 NonReadOnlyBaseValues.insert(BaseAddr);
2557 II++;
2558 } else {
2559 ReadOnlyPairs[BaseAddr].insert(*II);
2560 II = AG.erase(II);
2561 }
2562 }
2563
2564 // If we don't have read only pointers check if there are at least two
2565 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002566 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002567 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002568 continue;
2569 }
2570
2571 // If we don't have non read only pointers clear the alias group.
2572 if (NonReadOnlyBaseValues.empty()) {
2573 AG.clear();
2574 continue;
2575 }
2576
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002577 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002578 MinMaxAliasGroups.emplace_back();
2579 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2580 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2581 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2582 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002583
2584 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002585
2586 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002587 for (MemoryAccess *MA : AG)
2588 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002589
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002590 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2591 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002592
2593 // Bail out if the number of values we need to compare is too large.
2594 // This is important as the number of comparisions grows quadratically with
2595 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002596 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2597 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002598 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002599
2600 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002601 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002602 Accesses = isl_union_map_empty(getParamSpace());
2603
2604 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2605 for (MemoryAccess *MA : ReadOnlyPair.second)
2606 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2607
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002608 Valid =
2609 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002610
2611 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002612 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002613 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002614
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002615 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002616}
2617
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002618/// @brief Get the smallest loop that contains @p R but is not in @p R.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002619static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002620 // Start with the smallest loop containing the entry and expand that
2621 // loop until it contains all blocks in the region. If there is a loop
2622 // containing all blocks in the region check if it is itself contained
2623 // and if so take the parent loop as it will be the smallest containing
2624 // the region but not contained by it.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002625 Loop *L = LI.getLoopFor(R.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002626 while (L) {
2627 bool AllContained = true;
2628 for (auto *BB : R.blocks())
2629 AllContained &= L->contains(BB);
2630 if (AllContained)
2631 break;
2632 L = L->getParentLoop();
2633 }
2634
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002635 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2636}
2637
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002638static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2639 ScopDetection &SD) {
2640
2641 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2642
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002643 unsigned MinLD = INT_MAX, MaxLD = 0;
2644 for (BasicBlock *BB : R.blocks()) {
2645 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002646 if (!R.contains(L))
2647 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002648 if (BoxedLoops && BoxedLoops->count(L))
2649 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002650 unsigned LD = L->getLoopDepth();
2651 MinLD = std::min(MinLD, LD);
2652 MaxLD = std::max(MaxLD, LD);
2653 }
2654 }
2655
2656 // Handle the case that there is no loop in the SCoP first.
2657 if (MaxLD == 0)
2658 return 1;
2659
2660 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2661 assert(MaxLD >= MinLD &&
2662 "Maximal loop depth was smaller than mininaml loop depth?");
2663 return MaxLD - MinLD + 1;
2664}
2665
Johannes Doerfert478a7de2015-10-02 13:09:31 +00002666Scop::Scop(Region &R, AccFuncMapType &AccFuncMap, ScopDetection &SD,
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002667 ScalarEvolution &ScalarEvolution, DominatorTree &DT, LoopInfo &LI,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002668 isl_ctx *Context, unsigned MaxLoopDepth)
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002669 : LI(LI), DT(DT), SE(&ScalarEvolution), SD(SD), R(R),
2670 AccFuncMap(AccFuncMap), IsOptimized(false),
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002671 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
2672 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Context(nullptr),
2673 Affinator(this), AssumedContext(nullptr), BoundaryContext(nullptr),
2674 Schedule(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002675
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002676void Scop::init(AliasAnalysis &AA, AssumptionCache &AC) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002677 buildContext();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002678 addUserAssumptions(AC);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002679 buildInvariantEquivalenceClasses();
2680
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002681 buildDomains(&R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002682
Michael Krusecac948e2015-10-02 13:53:07 +00002683 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002684 // Exit early in case there are no executable statements left in this scop.
Michael Krusecac948e2015-10-02 13:53:07 +00002685 simplifySCoP(true);
Michael Kruseafe06702015-10-02 16:33:27 +00002686 if (Stmts.empty())
2687 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002688
Michael Krusecac948e2015-10-02 13:53:07 +00002689 // The ScopStmts now have enough information to initialize themselves.
2690 for (ScopStmt &Stmt : Stmts)
2691 Stmt.init();
2692
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00002693 buildSchedule();
Tobias Grosser75805372011-04-29 06:27:02 +00002694
Tobias Grosser8286b832015-11-02 11:29:32 +00002695 if (isl_set_is_empty(AssumedContext))
2696 return;
2697
2698 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002699 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002700 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002701 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002702 buildBoundaryContext();
2703 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002704 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002705
2706 hoistInvariantLoads();
Michael Krusecac948e2015-10-02 13:53:07 +00002707 simplifySCoP(false);
Tobias Grosser75805372011-04-29 06:27:02 +00002708}
2709
2710Scop::~Scop() {
2711 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002712 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002713 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002714 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002715
Johannes Doerfert96425c22015-08-30 21:13:53 +00002716 for (auto It : DomainMap)
2717 isl_set_free(It.second);
2718
Johannes Doerfertb164c792014-09-18 11:17:17 +00002719 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002720 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002721 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002722 isl_pw_multi_aff_free(MMA.first);
2723 isl_pw_multi_aff_free(MMA.second);
2724 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002725 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002726 isl_pw_multi_aff_free(MMA.first);
2727 isl_pw_multi_aff_free(MMA.second);
2728 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002729 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002730
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002731 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002732 isl_set_free(std::get<2>(IAClass));
Tobias Grosser75805372011-04-29 06:27:02 +00002733}
2734
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002735void Scop::updateAccessDimensionality() {
2736 for (auto &Stmt : *this)
2737 for (auto &Access : Stmt)
2738 Access->updateDimensionality();
2739}
2740
Michael Krusecac948e2015-10-02 13:53:07 +00002741void Scop::simplifySCoP(bool RemoveIgnoredStmts) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002742 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2743 ScopStmt &Stmt = *StmtIt;
Michael Krusecac948e2015-10-02 13:53:07 +00002744 RegionNode *RN = Stmt.isRegionStmt()
2745 ? Stmt.getRegion()->getNode()
2746 : getRegion().getBBNode(Stmt.getBasicBlock());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002747
Johannes Doerferteca9e892015-11-03 16:54:49 +00002748 bool RemoveStmt = StmtIt->isEmpty();
2749 if (!RemoveStmt)
2750 RemoveStmt = isl_set_is_empty(DomainMap[getRegionNodeBasicBlock(RN)]);
2751 if (!RemoveStmt)
2752 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002753
Johannes Doerferteca9e892015-11-03 16:54:49 +00002754 // Remove read only statements only after invariant loop hoisting.
2755 if (!RemoveStmt && !RemoveIgnoredStmts) {
2756 bool OnlyRead = true;
2757 for (MemoryAccess *MA : Stmt) {
2758 if (MA->isRead())
2759 continue;
2760
2761 OnlyRead = false;
2762 break;
2763 }
2764
2765 RemoveStmt = OnlyRead;
2766 }
2767
2768 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00002769 // Remove the statement because it is unnecessary.
2770 if (Stmt.isRegionStmt())
2771 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2772 StmtMap.erase(BB);
2773 else
2774 StmtMap.erase(Stmt.getBasicBlock());
2775
2776 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002777 continue;
2778 }
2779
Michael Krusecac948e2015-10-02 13:53:07 +00002780 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002781 }
2782}
2783
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002784const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2785 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2786 if (!LInst)
2787 return nullptr;
2788
2789 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2790 LInst = cast<LoadInst>(Rep);
2791
2792 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2793 for (auto &IAClass : InvariantEquivClasses)
2794 if (PointerSCEV == std::get<0>(IAClass))
2795 return &IAClass;
2796
2797 return nullptr;
2798}
2799
2800void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2801
2802 // Get the context under which the statement is executed.
2803 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2804 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2805 DomainCtx = isl_set_detect_equalities(DomainCtx);
2806 DomainCtx = isl_set_coalesce(DomainCtx);
2807
2808 // Project out all parameters that relate to loads in the statement. Otherwise
2809 // we could have cyclic dependences on the constraints under which the
2810 // hoisted loads are executed and we could not determine an order in which to
2811 // pre-load them. This happens because not only lower bounds are part of the
2812 // domain but also upper bounds.
2813 for (MemoryAccess *MA : InvMAs) {
2814 Instruction *AccInst = MA->getAccessInstruction();
2815 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00002816 SetVector<Value *> Values;
2817 for (const SCEV *Parameter : Parameters) {
2818 Values.clear();
2819 findValues(Parameter, Values);
2820 if (!Values.count(AccInst))
2821 continue;
2822
2823 if (isl_id *ParamId = getIdForParam(Parameter)) {
2824 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2825 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2826 isl_id_free(ParamId);
2827 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002828 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002829 }
2830 }
2831
2832 for (MemoryAccess *MA : InvMAs) {
2833 // Check for another invariant access that accesses the same location as
2834 // MA and if found consolidate them. Otherwise create a new equivalence
2835 // class at the end of InvariantEquivClasses.
2836 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
2837 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2838
2839 bool Consolidated = false;
2840 for (auto &IAClass : InvariantEquivClasses) {
2841 if (PointerSCEV != std::get<0>(IAClass))
2842 continue;
2843
2844 Consolidated = true;
2845
2846 // Add MA to the list of accesses that are in this class.
2847 auto &MAs = std::get<1>(IAClass);
2848 MAs.push_front(MA);
2849
2850 // Unify the execution context of the class and this statement.
2851 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002852 if (IAClassDomainCtx)
2853 IAClassDomainCtx = isl_set_coalesce(
2854 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
2855 else
2856 IAClassDomainCtx = isl_set_copy(DomainCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002857 break;
2858 }
2859
2860 if (Consolidated)
2861 continue;
2862
2863 // If we did not consolidate MA, thus did not find an equivalence class
2864 // for it, we create a new one.
2865 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
2866 isl_set_copy(DomainCtx));
2867 }
2868
2869 isl_set_free(DomainCtx);
2870}
2871
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002872bool Scop::isHoistableAccess(MemoryAccess *Access,
2873 __isl_keep isl_union_map *Writes) {
2874 // TODO: Loads that are not loop carried, hence are in a statement with
2875 // zero iterators, are by construction invariant, though we
2876 // currently "hoist" them anyway. This is necessary because we allow
2877 // them to be treated as parameters (e.g., in conditions) and our code
2878 // generation would otherwise use the old value.
2879
2880 auto &Stmt = *Access->getStatement();
2881 BasicBlock *BB =
2882 Stmt.isBlockStmt() ? Stmt.getBasicBlock() : Stmt.getRegion()->getEntry();
2883
2884 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
2885 return false;
2886
2887 // Skip accesses that have an invariant base pointer which is defined but
2888 // not loaded inside the SCoP. This can happened e.g., if a readnone call
2889 // returns a pointer that is used as a base address. However, as we want
2890 // to hoist indirect pointers, we allow the base pointer to be defined in
2891 // the region if it is also a memory access. Each ScopArrayInfo object
2892 // that has a base pointer origin has a base pointer that is loaded and
2893 // that it is invariant, thus it will be hoisted too. However, if there is
2894 // no base pointer origin we check that the base pointer is defined
2895 // outside the region.
2896 const ScopArrayInfo *SAI = Access->getScopArrayInfo();
2897 while (auto *BasePtrOriginSAI = SAI->getBasePtrOriginSAI())
2898 SAI = BasePtrOriginSAI;
2899
2900 if (auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr()))
2901 if (R.contains(BasePtrInst))
2902 return false;
2903
2904 // Skip accesses in non-affine subregions as they might not be executed
2905 // under the same condition as the entry of the non-affine subregion.
2906 if (BB != Access->getAccessInstruction()->getParent())
2907 return false;
2908
2909 isl_map *AccessRelation = Access->getAccessRelation();
2910
2911 // Skip accesses that have an empty access relation. These can be caused
2912 // by multiple offsets with a type cast in-between that cause the overall
2913 // byte offset to be not divisible by the new types sizes.
2914 if (isl_map_is_empty(AccessRelation)) {
2915 isl_map_free(AccessRelation);
2916 return false;
2917 }
2918
2919 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
2920 Stmt.getNumIterators())) {
2921 isl_map_free(AccessRelation);
2922 return false;
2923 }
2924
2925 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
2926 isl_set *AccessRange = isl_map_range(AccessRelation);
2927
2928 isl_union_map *Written = isl_union_map_intersect_range(
2929 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
2930 bool IsWritten = !isl_union_map_is_empty(Written);
2931 isl_union_map_free(Written);
2932
2933 if (IsWritten)
2934 return false;
2935
2936 return true;
2937}
2938
2939void Scop::verifyInvariantLoads() {
2940 auto &RIL = *SD.getRequiredInvariantLoads(&getRegion());
2941 for (LoadInst *LI : RIL) {
2942 assert(LI && getRegion().contains(LI));
2943 ScopStmt *Stmt = getStmtForBasicBlock(LI->getParent());
Tobias Grosser949e8c62015-12-21 07:10:39 +00002944 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002945 invalidate(INVARIANTLOAD, LI->getDebugLoc());
2946 return;
2947 }
2948 }
2949}
2950
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002951void Scop::hoistInvariantLoads() {
2952 isl_union_map *Writes = getWrites();
2953 for (ScopStmt &Stmt : *this) {
2954
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002955 MemoryAccessList InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002956
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002957 for (MemoryAccess *Access : Stmt)
2958 if (isHoistableAccess(Access, Writes))
2959 InvariantAccesses.push_front(Access);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002960
2961 // We inserted invariant accesses always in the front but need them to be
2962 // sorted in a "natural order". The statements are already sorted in reverse
2963 // post order and that suffices for the accesses too. The reason we require
2964 // an order in the first place is the dependences between invariant loads
2965 // that can be caused by indirect loads.
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002966 InvariantAccesses.reverse();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002967
2968 // Transfer the memory access from the statement to the SCoP.
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002969 Stmt.removeMemoryAccesses(InvariantAccesses);
2970 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002971 }
2972 isl_union_map_free(Writes);
2973
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002974 verifyInvariantLoads();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002975}
2976
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002977const ScopArrayInfo *
2978Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002979 ArrayRef<const SCEV *> Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00002980 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002981 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002982 if (!SAI) {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00002983 auto &DL = getRegion().getEntry()->getModule()->getDataLayout();
2984 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, Kind,
2985 DL, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002986 } else {
Tobias Grosser8286b832015-11-02 11:29:32 +00002987 // In case of mismatching array sizes, we bail out by setting the run-time
2988 // context to false.
2989 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002990 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002991 }
Tobias Grosserab671442015-05-23 05:58:27 +00002992 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002993}
2994
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002995const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00002996 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002997 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002998 assert(SAI && "No ScopArrayInfo available for this base pointer");
2999 return SAI;
3000}
3001
Tobias Grosser74394f02013-01-14 22:40:23 +00003002std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003003std::string Scop::getAssumedContextStr() const {
3004 return stringFromIslObj(AssumedContext);
3005}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003006std::string Scop::getBoundaryContextStr() const {
3007 return stringFromIslObj(BoundaryContext);
3008}
Tobias Grosser75805372011-04-29 06:27:02 +00003009
3010std::string Scop::getNameStr() const {
3011 std::string ExitName, EntryName;
3012 raw_string_ostream ExitStr(ExitName);
3013 raw_string_ostream EntryStr(EntryName);
3014
Tobias Grosserf240b482014-01-09 10:42:15 +00003015 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003016 EntryStr.str();
3017
3018 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003019 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003020 ExitStr.str();
3021 } else
3022 ExitName = "FunctionExit";
3023
3024 return EntryName + "---" + ExitName;
3025}
3026
Tobias Grosser74394f02013-01-14 22:40:23 +00003027__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003028__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003029 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003030}
3031
Tobias Grossere86109f2013-10-29 21:05:49 +00003032__isl_give isl_set *Scop::getAssumedContext() const {
3033 return isl_set_copy(AssumedContext);
3034}
3035
Johannes Doerfert43788c52015-08-20 05:58:56 +00003036__isl_give isl_set *Scop::getRuntimeCheckContext() const {
3037 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003038 RuntimeCheckContext =
3039 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
3040 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00003041 return RuntimeCheckContext;
3042}
3043
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003044bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003045 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003046 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00003047 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
3048 isl_set_free(RuntimeCheckContext);
3049 return IsFeasible;
3050}
3051
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003052static std::string toString(AssumptionKind Kind) {
3053 switch (Kind) {
3054 case ALIASING:
3055 return "No-aliasing";
3056 case INBOUNDS:
3057 return "Inbounds";
3058 case WRAPPING:
3059 return "No-overflows";
Johannes Doerferta4b77c02015-11-12 20:15:32 +00003060 case ALIGNMENT:
3061 return "Alignment";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003062 case ERRORBLOCK:
3063 return "No-error";
3064 case INFINITELOOP:
3065 return "Finite loop";
3066 case INVARIANTLOAD:
3067 return "Invariant load";
3068 case DELINEARIZATION:
3069 return "Delinearization";
Tobias Grosser75dc40c2015-12-20 13:31:48 +00003070 case ERROR_DOMAINCONJUNCTS:
3071 return "Low number of domain conjuncts";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003072 }
3073 llvm_unreachable("Unknown AssumptionKind!");
3074}
3075
3076void Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3077 DebugLoc Loc) {
3078 if (isl_set_is_subset(Context, Set))
3079 return;
3080
3081 if (isl_set_is_subset(AssumedContext, Set))
3082 return;
3083
3084 auto &F = *getRegion().getEntry()->getParent();
3085 std::string Msg = toString(Kind) + " assumption:\t" + stringFromIslObj(Set);
3086 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
3087}
3088
3089void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
3090 DebugLoc Loc) {
3091 trackAssumption(Kind, Set, Loc);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003092 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003093
Johannes Doerfert9d7899e2015-11-11 20:01:31 +00003094 int NSets = isl_set_n_basic_set(AssumedContext);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003095 if (NSets >= MaxDisjunctsAssumed) {
3096 isl_space *Space = isl_set_get_space(AssumedContext);
3097 isl_set_free(AssumedContext);
Tobias Grossere19fca42015-11-11 20:21:39 +00003098 AssumedContext = isl_set_empty(Space);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003099 }
3100
Tobias Grosser7b50bee2014-11-25 10:51:12 +00003101 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003102}
3103
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003104void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
3105 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc);
3106}
3107
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003108__isl_give isl_set *Scop::getBoundaryContext() const {
3109 return isl_set_copy(BoundaryContext);
3110}
3111
Tobias Grosser75805372011-04-29 06:27:02 +00003112void Scop::printContext(raw_ostream &OS) const {
3113 OS << "Context:\n";
3114
3115 if (!Context) {
3116 OS.indent(4) << "n/a\n\n";
3117 return;
3118 }
3119
3120 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003121
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003122 OS.indent(4) << "Assumed Context:\n";
3123 if (!AssumedContext) {
3124 OS.indent(4) << "n/a\n\n";
3125 return;
3126 }
3127
3128 OS.indent(4) << getAssumedContextStr() << "\n";
3129
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003130 OS.indent(4) << "Boundary Context:\n";
3131 if (!BoundaryContext) {
3132 OS.indent(4) << "n/a\n\n";
3133 return;
3134 }
3135
3136 OS.indent(4) << getBoundaryContextStr() << "\n";
3137
Tobias Grosser083d3d32014-06-28 08:59:45 +00003138 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00003139 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00003140 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
3141 }
Tobias Grosser75805372011-04-29 06:27:02 +00003142}
3143
Johannes Doerfertb164c792014-09-18 11:17:17 +00003144void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003145 int noOfGroups = 0;
3146 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003147 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003148 noOfGroups += 1;
3149 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003150 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003151 }
3152
Tobias Grosserbb853c22015-07-25 12:31:03 +00003153 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003154 if (MinMaxAliasGroups.empty()) {
3155 OS.indent(8) << "n/a\n";
3156 return;
3157 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003158
Tobias Grosserbb853c22015-07-25 12:31:03 +00003159 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003160
3161 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003162 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003163 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003164 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003165 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3166 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003167 }
3168 OS << " ]]\n";
3169 }
3170
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003171 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003172 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003173 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003174 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003175 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3176 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003177 }
3178 OS << " ]]\n";
3179 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003180 }
3181}
3182
Tobias Grosser75805372011-04-29 06:27:02 +00003183void Scop::printStatements(raw_ostream &OS) const {
3184 OS << "Statements {\n";
3185
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003186 for (const ScopStmt &Stmt : *this)
3187 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003188
3189 OS.indent(4) << "}\n";
3190}
3191
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003192void Scop::printArrayInfo(raw_ostream &OS) const {
3193 OS << "Arrays {\n";
3194
Tobias Grosserab671442015-05-23 05:58:27 +00003195 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003196 Array.second->print(OS);
3197
3198 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003199
3200 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3201
3202 for (auto &Array : arrays())
3203 Array.second->print(OS, /* SizeAsPwAff */ true);
3204
3205 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003206}
3207
Tobias Grosser75805372011-04-29 06:27:02 +00003208void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00003209 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
3210 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003211 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003212 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003213 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003214 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003215 const auto &MAs = std::get<1>(IAClass);
3216 if (MAs.empty()) {
3217 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003218 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003219 MAs.front()->print(OS);
3220 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003221 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003222 }
3223 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003224 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003225 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003226 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003227 printStatements(OS.indent(4));
3228}
3229
3230void Scop::dump() const { print(dbgs()); }
3231
Tobias Grosser9a38ab82011-11-08 15:41:03 +00003232isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00003233
Johannes Doerfertcef616f2015-09-15 22:49:04 +00003234__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
3235 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003236}
3237
Tobias Grosser808cd692015-07-14 09:33:13 +00003238__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003239 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003240
Tobias Grosser808cd692015-07-14 09:33:13 +00003241 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003242 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003243
3244 return Domain;
3245}
3246
Tobias Grossere5a35142015-11-12 14:07:09 +00003247__isl_give isl_union_map *
3248Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3249 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003250
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003251 for (ScopStmt &Stmt : *this) {
3252 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003253 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003254 continue;
3255
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003256 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003257 isl_map *AccessDomain = MA->getAccessRelation();
3258 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003259 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003260 }
3261 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003262 return isl_union_map_coalesce(Accesses);
3263}
3264
3265__isl_give isl_union_map *Scop::getMustWrites() {
3266 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003267}
3268
3269__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003270 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003271}
3272
Tobias Grosser37eb4222014-02-20 21:43:54 +00003273__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003274 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003275}
3276
3277__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003278 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003279}
3280
Tobias Grosser2ac23382015-11-12 14:07:13 +00003281__isl_give isl_union_map *Scop::getAccesses() {
3282 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3283}
3284
Tobias Grosser808cd692015-07-14 09:33:13 +00003285__isl_give isl_union_map *Scop::getSchedule() const {
3286 auto Tree = getScheduleTree();
3287 auto S = isl_schedule_get_map(Tree);
3288 isl_schedule_free(Tree);
3289 return S;
3290}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003291
Tobias Grosser808cd692015-07-14 09:33:13 +00003292__isl_give isl_schedule *Scop::getScheduleTree() const {
3293 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3294 getDomains());
3295}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003296
Tobias Grosser808cd692015-07-14 09:33:13 +00003297void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3298 auto *S = isl_schedule_from_domain(getDomains());
3299 S = isl_schedule_insert_partial_schedule(
3300 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3301 isl_schedule_free(Schedule);
3302 Schedule = S;
3303}
3304
3305void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3306 isl_schedule_free(Schedule);
3307 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003308}
3309
3310bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3311 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003312 for (ScopStmt &Stmt : *this) {
3313 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003314 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3315 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3316
3317 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3318 isl_union_set_free(StmtDomain);
3319 isl_union_set_free(NewStmtDomain);
3320 continue;
3321 }
3322
3323 Changed = true;
3324
3325 isl_union_set_free(StmtDomain);
3326 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3327
3328 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003329 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003330 isl_union_set_free(NewStmtDomain);
3331 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003332 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003333 }
3334 isl_union_set_free(Domain);
3335 return Changed;
3336}
3337
Tobias Grosser75805372011-04-29 06:27:02 +00003338ScalarEvolution *Scop::getSE() const { return SE; }
3339
Johannes Doerfertf5673802015-10-01 23:48:18 +00003340bool Scop::isIgnored(RegionNode *RN) {
3341 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Michael Krusea902ba62015-12-13 19:21:45 +00003342 ScopStmt *Stmt = getStmtForRegionNode(RN);
3343
3344 // If there is no stmt, then it already has been removed.
3345 if (!Stmt)
3346 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00003347
Johannes Doerfertf5673802015-10-01 23:48:18 +00003348 // Check if there are accesses contained.
Michael Krusea902ba62015-12-13 19:21:45 +00003349 if (Stmt->isEmpty())
Johannes Doerfertf5673802015-10-01 23:48:18 +00003350 return true;
3351
3352 // Check for reachability via non-error blocks.
3353 if (!DomainMap.count(BB))
3354 return true;
3355
3356 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003357 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003358 return true;
3359
3360 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003361}
3362
Tobias Grosser808cd692015-07-14 09:33:13 +00003363struct MapToDimensionDataTy {
3364 int N;
3365 isl_union_pw_multi_aff *Res;
3366};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003367
Tobias Grosser808cd692015-07-14 09:33:13 +00003368// @brief Create a function that maps the elements of 'Set' to its N-th
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003369// dimension and add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00003370//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003371// @param Set The input set.
3372// @param User->N The dimension to map to.
3373// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00003374//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003375// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00003376static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3377 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3378 int Dim;
3379 isl_space *Space;
3380 isl_pw_multi_aff *PMA;
3381
3382 Dim = isl_set_dim(Set, isl_dim_set);
3383 Space = isl_set_get_space(Set);
3384 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3385 Dim - Data->N);
3386 if (Data->N > 1)
3387 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3388 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3389
3390 isl_set_free(Set);
3391
3392 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003393}
3394
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003395// @brief Create an isl_multi_union_aff that defines an identity mapping
3396// from the elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003397//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003398// # Example:
3399//
3400// Domain: { A[i,j]; B[i,j,k] }
3401// N: 1
3402//
3403// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
3404//
3405// @param USet A union set describing the elements for which to generate a
3406// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00003407// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003408// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003409static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003410mapToDimension(__isl_take isl_union_set *USet, int N) {
3411 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00003412 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003413 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003414
Tobias Grosser808cd692015-07-14 09:33:13 +00003415 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00003416
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003417 auto *Space = isl_union_set_get_space(USet);
3418 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00003419
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003420 Data = {N, PwAff};
3421
3422 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
3423
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00003424 (void)Res;
3425
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003426 assert(Res == isl_stat_ok);
3427
3428 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00003429 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3430}
3431
Tobias Grosser316b5b22015-11-11 19:28:14 +00003432void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003433 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003434 Stmts.emplace_back(*this, *BB);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003435 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003436 StmtMap[BB] = Stmt;
3437 } else {
3438 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003439 Stmts.emplace_back(*this, *R);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003440 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003441 for (BasicBlock *BB : R->blocks())
3442 StmtMap[BB] = Stmt;
3443 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003444}
3445
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003446void Scop::buildSchedule() {
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003447 Loop *L = getLoopSurroundingRegion(getRegion(), LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003448 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
3449 buildSchedule(getRegion().getNode(), LoopStack);
3450 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
3451 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003452}
3453
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003454/// To generate a schedule for the elements in a Region we traverse the Region
3455/// in reverse-post-order and add the contained RegionNodes in traversal order
3456/// to the schedule of the loop that is currently at the top of the LoopStack.
3457/// For loop-free codes, this results in a correct sequential ordering.
3458///
3459/// Example:
3460/// bb1(0)
3461/// / \.
3462/// bb2(1) bb3(2)
3463/// \ / \.
3464/// bb4(3) bb5(4)
3465/// \ /
3466/// bb6(5)
3467///
3468/// Including loops requires additional processing. Whenever a loop header is
3469/// encountered, the corresponding loop is added to the @p LoopStack. Starting
3470/// from an empty schedule, we first process all RegionNodes that are within
3471/// this loop and complete the sequential schedule at this loop-level before
3472/// processing about any other nodes. To implement this
3473/// loop-nodes-first-processing, the reverse post-order traversal is
3474/// insufficient. Hence, we additionally check if the traversal yields
3475/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
3476/// These region-nodes are then queue and only traverse after the all nodes
3477/// within the current loop have been processed.
3478void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack) {
3479 Loop *OuterScopLoop = getLoopSurroundingRegion(getRegion(), LI);
3480
3481 ReversePostOrderTraversal<Region *> RTraversal(R);
3482 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
3483 std::deque<RegionNode *> DelayList;
3484 bool LastRNWaiting = false;
3485
3486 // Iterate over the region @p R in reverse post-order but queue
3487 // sub-regions/blocks iff they are not part of the last encountered but not
3488 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
3489 // that we queued the last sub-region/block from the reverse post-order
3490 // iterator. If it is set we have to explore the next sub-region/block from
3491 // the iterator (if any) to guarantee progress. If it is not set we first try
3492 // the next queued sub-region/blocks.
3493 while (!WorkList.empty() || !DelayList.empty()) {
3494 RegionNode *RN;
3495
3496 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
3497 RN = WorkList.front();
3498 WorkList.pop_front();
3499 LastRNWaiting = false;
3500 } else {
3501 RN = DelayList.front();
3502 DelayList.pop_front();
3503 }
3504
3505 Loop *L = getRegionNodeLoop(RN, LI);
3506 if (!getRegion().contains(L))
3507 L = OuterScopLoop;
3508
3509 Loop *LastLoop = LoopStack.back().L;
3510 if (LastLoop != L) {
3511 if (!LastLoop->contains(L)) {
3512 LastRNWaiting = true;
3513 DelayList.push_back(RN);
3514 continue;
3515 }
3516 LoopStack.push_back({L, nullptr, 0});
3517 }
3518 buildSchedule(RN, LoopStack);
3519 }
3520
3521 return;
3522}
3523
3524void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack) {
Michael Kruse046dde42015-08-10 13:01:57 +00003525
Tobias Grosser8362c262016-01-06 15:30:06 +00003526 if (RN->isSubRegion()) {
3527 auto *LocalRegion = RN->getNodeAs<Region>();
3528 if (!SD.isNonAffineSubRegion(LocalRegion, &getRegion())) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003529 buildSchedule(LocalRegion, LoopStack);
Tobias Grosser8362c262016-01-06 15:30:06 +00003530 return;
3531 }
3532 }
Michael Kruse046dde42015-08-10 13:01:57 +00003533
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003534 auto &LoopData = LoopStack.back();
3535 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00003536
Tobias Grosserc9abde82016-01-23 20:23:06 +00003537 if (auto *Stmt = getStmtForRegionNode(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00003538 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3539 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003540 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00003541 }
3542
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003543 // Check if we just processed the last node in this loop. If we did, finalize
3544 // the loop by:
3545 //
3546 // - adding new schedule dimensions
3547 // - folding the resulting schedule into the parent loop schedule
3548 // - dropping the loop schedule from the LoopStack.
3549 //
3550 // Then continue to check surrounding loops, which might also have been
3551 // completed by this node.
3552 while (LoopData.L &&
3553 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
3554 auto Schedule = LoopData.Schedule;
3555 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00003556
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003557 LoopStack.pop_back();
3558 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00003559
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003560 if (Schedule) {
3561 auto *Domain = isl_schedule_get_domain(Schedule);
3562 auto *MUPA = mapToDimension(Domain, LoopStack.size());
3563 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
3564 NextLoopData.Schedule =
3565 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003566 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003567
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003568 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
3569 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00003570 }
Tobias Grosser75805372011-04-29 06:27:02 +00003571}
3572
Johannes Doerfert7c494212014-10-31 23:13:39 +00003573ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003574 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003575 if (StmtMapIt == StmtMap.end())
3576 return nullptr;
3577 return StmtMapIt->second;
3578}
3579
Michael Krusea902ba62015-12-13 19:21:45 +00003580ScopStmt *Scop::getStmtForRegionNode(RegionNode *RN) const {
3581 return getStmtForBasicBlock(getRegionNodeBasicBlock(RN));
3582}
3583
Johannes Doerfert96425c22015-08-30 21:13:53 +00003584int Scop::getRelativeLoopDepth(const Loop *L) const {
3585 Loop *OuterLoop =
3586 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3587 if (!OuterLoop)
3588 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003589 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3590}
3591
Michael Krused868b5d2015-09-10 15:25:24 +00003592void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003593 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003594
3595 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3596 // true, are not modeled as ordinary PHI nodes as they are not part of the
3597 // region. However, we model the operands in the predecessor blocks that are
3598 // part of the region as regular scalar accesses.
3599
3600 // If we can synthesize a PHI we can skip it, however only if it is in
3601 // the region. If it is not it can only be in the exit block of the region.
3602 // In this case we model the operands but not the PHI itself.
3603 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3604 return;
3605
3606 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3607 // detection. Hence, the PHI is a load of a new memory location in which the
3608 // incoming value was written at the end of the incoming basic block.
3609 bool OnlyNonAffineSubRegionOperands = true;
3610 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3611 Value *Op = PHI->getIncomingValue(u);
3612 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3613
3614 // Do not build scalar dependences inside a non-affine subregion.
3615 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3616 continue;
3617
3618 OnlyNonAffineSubRegionOperands = false;
3619
3620 if (!R.contains(OpBB))
3621 continue;
3622
3623 Instruction *OpI = dyn_cast<Instruction>(Op);
3624 if (OpI) {
3625 BasicBlock *OpIBB = OpI->getParent();
3626 // As we pretend there is a use (or more precise a write) of OpI in OpBB
3627 // we have to insert a scalar dependence from the definition of OpI to
3628 // OpBB if the definition is not in OpBB.
Michael Kruse668af712015-10-15 14:45:48 +00003629 if (scop->getStmtForBasicBlock(OpIBB) !=
3630 scop->getStmtForBasicBlock(OpBB)) {
Michael Krusead28e5a2016-01-26 13:33:15 +00003631 ensureValueRead(OpI, OpBB);
Michael Kruse436db622016-01-26 13:33:10 +00003632 ensureValueWrite(OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003633 }
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003634 } else if (ModelReadOnlyScalars && !isa<Constant>(Op)) {
Michael Krusead28e5a2016-01-26 13:33:15 +00003635 ensureValueRead(Op, OpBB);
Michael Kruse7bf39442015-09-10 12:46:52 +00003636 }
3637
Michael Kruseee6a4fc2016-01-26 13:33:27 +00003638 ensurePHIWrite(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003639 }
3640
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003641 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3642 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003643 }
3644}
3645
Michael Krused868b5d2015-09-10 15:25:24 +00003646bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
3647 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003648 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
3649 if (isIgnoredIntrinsic(Inst))
3650 return false;
3651
3652 bool AnyCrossStmtUse = false;
3653 BasicBlock *ParentBB = Inst->getParent();
3654
3655 for (User *U : Inst->users()) {
3656 Instruction *UI = dyn_cast<Instruction>(U);
3657
3658 // Ignore the strange user
3659 if (UI == 0)
3660 continue;
3661
3662 BasicBlock *UseParent = UI->getParent();
3663
Tobias Grosserbaffa092015-10-24 20:55:27 +00003664 // Ignore basic block local uses. A value that is defined in a scop, but
3665 // used in a PHI node in the same basic block does not count as basic block
3666 // local, as for such cases a control flow edge is passed between definition
3667 // and use.
3668 if (UseParent == ParentBB && !isa<PHINode>(UI))
Michael Kruse7bf39442015-09-10 12:46:52 +00003669 continue;
3670
Michael Krusef714d472015-11-05 13:18:43 +00003671 // Uses by PHI nodes in the entry node count as external uses in case the
3672 // use is through an incoming block that is itself not contained in the
3673 // region.
3674 if (R->getEntry() == UseParent) {
3675 if (auto *PHI = dyn_cast<PHINode>(UI)) {
3676 bool ExternalUse = false;
3677 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
3678 if (PHI->getIncomingValue(i) == Inst &&
3679 !R->contains(PHI->getIncomingBlock(i))) {
3680 ExternalUse = true;
3681 break;
3682 }
3683 }
3684
3685 if (ExternalUse) {
3686 AnyCrossStmtUse = true;
3687 continue;
3688 }
3689 }
3690 }
3691
Michael Kruse7bf39442015-09-10 12:46:52 +00003692 // Do not build scalar dependences inside a non-affine subregion.
3693 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
3694 continue;
3695
Michael Kruse01cb3792015-10-17 21:07:08 +00003696 // Check for PHI nodes in the region exit and skip them, if they will be
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003697 // modeled as PHI nodes.
Michael Kruse01cb3792015-10-17 21:07:08 +00003698 //
3699 // PHI nodes in the region exit that have more than two incoming edges need
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003700 // to be modeled as PHI-Nodes to correctly model the fact that depending on
3701 // the control flow a different value will be assigned to the PHI node. In
3702 // case this is the case, there is no need to create an additional normal
3703 // scalar dependence. Hence, bail out before we register an "out-of-region"
3704 // use for this definition.
Michael Kruse01cb3792015-10-17 21:07:08 +00003705 if (isa<PHINode>(UI) && UI->getParent() == R->getExit() &&
3706 !R->getExitingBlock())
3707 continue;
3708
Michael Kruse7bf39442015-09-10 12:46:52 +00003709 // Check whether or not the use is in the SCoP.
Tobias Grosserc73d8b02015-10-23 22:36:22 +00003710 if (!R->contains(UseParent)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003711 AnyCrossStmtUse = true;
3712 continue;
3713 }
3714
3715 // If the instruction can be synthesized and the user is in the region
3716 // we do not need to add scalar dependences.
3717 if (canSynthesizeInst)
3718 continue;
3719
3720 // No need to translate these scalar dependences into polyhedral form,
3721 // because synthesizable scalars can be generated by the code generator.
3722 if (canSynthesize(UI, LI, SE, R))
3723 continue;
3724
3725 // Skip PHI nodes in the region as they handle their operands on their own.
3726 if (isa<PHINode>(UI))
3727 continue;
3728
3729 // Now U is used in another statement.
3730 AnyCrossStmtUse = true;
3731
3732 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00003733 // Use the def instruction as base address of the MemoryAccess, so that it
3734 // will become the name of the scalar access in the polyhedral form.
Michael Krusead28e5a2016-01-26 13:33:15 +00003735 ensureValueRead(Inst, UI->getParent());
Michael Kruse7bf39442015-09-10 12:46:52 +00003736 }
3737
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003738 if (ModelReadOnlyScalars && !isa<PHINode>(Inst)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003739 for (Value *Op : Inst->operands()) {
3740 if (canSynthesize(Op, LI, SE, R))
3741 continue;
3742
3743 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
3744 if (R->contains(OpInst))
3745 continue;
3746
3747 if (isa<Constant>(Op))
3748 continue;
3749
Michael Krusead28e5a2016-01-26 13:33:15 +00003750 ensureValueRead(Op, Inst->getParent());
Michael Kruse7bf39442015-09-10 12:46:52 +00003751 }
3752 }
3753
3754 return AnyCrossStmtUse;
3755}
3756
3757extern MapInsnToMemAcc InsnToMemAcc;
3758
Michael Krusee2bccbb2015-09-18 19:59:43 +00003759void ScopInfo::buildMemoryAccess(
Michael Kruse70131d32016-01-27 17:09:17 +00003760 MemAccInst Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003761 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3762 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003763
Michael Kruse70131d32016-01-27 17:09:17 +00003764 Value *Address = Inst.getPointerOperand();
3765 Value *Val = Inst.getValueOperand();
3766 Type *SizeType = Val->getType();
3767 unsigned Size = TD->getTypeAllocSize(SizeType);
3768 enum MemoryAccess::AccessType Type =
3769 Inst.isLoad() ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003770
3771 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003772 const SCEVUnknown *BasePointer =
3773 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3774
3775 assert(BasePointer && "Could not find base pointer");
3776 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
3777
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003778 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3779 auto NewAddress = Address;
3780 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3781 auto Src = BitCast->getOperand(0);
3782 auto SrcTy = Src->getType();
3783 auto DstTy = BitCast->getType();
3784 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3785 NewAddress = Src;
3786 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003787
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003788 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3789 std::vector<const SCEV *> Subscripts;
3790 std::vector<int> Sizes;
3791 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3792 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003793
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003794 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003795
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003796 bool AllAffineSubcripts = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003797 for (auto Subscript : Subscripts) {
3798 InvariantLoadsSetTy AccessILS;
3799 AllAffineSubcripts =
3800 isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS);
3801
3802 for (LoadInst *LInst : AccessILS)
3803 if (!ScopRIL.count(LInst))
3804 AllAffineSubcripts = false;
3805
3806 if (!AllAffineSubcripts)
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003807 break;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003808 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003809
3810 if (AllAffineSubcripts && Sizes.size() > 0) {
3811 for (auto V : Sizes)
3812 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3813 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003814 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003815 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003816
Tobias Grossera535dff2015-12-13 19:59:01 +00003817 addArrayAccess(Inst, Type, BasePointer->getValue(), Size, true,
3818 Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00003819 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003820 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003821 }
3822 }
3823
Michael Kruse7bf39442015-09-10 12:46:52 +00003824 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003825 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003826 addArrayAccess(Inst, Type, BasePointer->getValue(), Size, true,
3827 AccItr->second.DelinearizedSubscripts,
3828 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003829 return;
3830 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003831
3832 // Check if the access depends on a loop contained in a non-affine subregion.
3833 bool isVariantInNonAffineLoop = false;
3834 if (BoxedLoops) {
3835 SetVector<const Loop *> Loops;
3836 findLoops(AccessFunction, Loops);
3837 for (const Loop *L : Loops)
3838 if (BoxedLoops->count(L))
3839 isVariantInNonAffineLoop = true;
3840 }
3841
Johannes Doerfert09e36972015-10-07 20:17:36 +00003842 InvariantLoadsSetTy AccessILS;
3843 bool IsAffine =
3844 !isVariantInNonAffineLoop &&
3845 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3846
3847 for (LoadInst *LInst : AccessILS)
3848 if (!ScopRIL.count(LInst))
3849 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003850
Michael Krusecaac2b62015-09-26 15:51:44 +00003851 // FIXME: Size of the number of bytes of an array element, not the number of
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003852 // elements as probably intended here.
Tobias Grossera43b6e92015-09-27 17:54:50 +00003853 const SCEV *SizeSCEV =
Michael Kruse70131d32016-01-27 17:09:17 +00003854 SE->getConstant(TD->getIntPtrType(Inst.getContext()), Size);
Michael Kruse7bf39442015-09-10 12:46:52 +00003855
Michael Krusee2bccbb2015-09-18 19:59:43 +00003856 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3857 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003858
Tobias Grossera535dff2015-12-13 19:59:01 +00003859 addArrayAccess(Inst, Type, BasePointer->getValue(), Size, IsAffine,
3860 ArrayRef<const SCEV *>(AccessFunction),
3861 ArrayRef<const SCEV *>(SizeSCEV), Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003862}
3863
Michael Krused868b5d2015-09-10 15:25:24 +00003864void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003865
3866 if (SD->isNonAffineSubRegion(&SR, &R)) {
3867 for (BasicBlock *BB : SR.blocks())
3868 buildAccessFunctions(R, *BB, &SR);
3869 return;
3870 }
3871
3872 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3873 if (I->isSubRegion())
3874 buildAccessFunctions(R, *I->getNodeAs<Region>());
3875 else
3876 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
3877}
3878
Michael Krusecac948e2015-10-02 13:53:07 +00003879void ScopInfo::buildStmts(Region &SR) {
3880 Region *R = getRegion();
3881
3882 if (SD->isNonAffineSubRegion(&SR, R)) {
3883 scop->addScopStmt(nullptr, &SR);
3884 return;
3885 }
3886
3887 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3888 if (I->isSubRegion())
3889 buildStmts(*I->getNodeAs<Region>());
3890 else
3891 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
3892}
3893
Michael Krused868b5d2015-09-10 15:25:24 +00003894void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
3895 Region *NonAffineSubRegion,
3896 bool IsExitBlock) {
Tobias Grosser910cf262015-11-11 20:15:49 +00003897 // We do not build access functions for error blocks, as they may contain
3898 // instructions we can not model.
3899 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3900 if (isErrorBlock(BB, R, *LI, DT) && !IsExitBlock)
3901 return;
3902
Michael Kruse7bf39442015-09-10 12:46:52 +00003903 Loop *L = LI->getLoopFor(&BB);
3904
3905 // The set of loops contained in non-affine subregions that are part of R.
3906 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3907
Johannes Doerfert09e36972015-10-07 20:17:36 +00003908 // The set of loads that are required to be invariant.
3909 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
3910
Michael Kruse7bf39442015-09-10 12:46:52 +00003911 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00003912 Instruction *Inst = &*I;
Michael Kruse7bf39442015-09-10 12:46:52 +00003913
3914 PHINode *PHI = dyn_cast<PHINode>(Inst);
3915 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003916 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003917
3918 // For the exit block we stop modeling after the last PHI node.
3919 if (!PHI && IsExitBlock)
3920 break;
3921
Johannes Doerfert09e36972015-10-07 20:17:36 +00003922 // TODO: At this point we only know that elements of ScopRIL have to be
3923 // invariant and will be hoisted for the SCoP to be processed. Though,
3924 // there might be other invariant accesses that will be hoisted and
3925 // that would allow to make a non-affine access affine.
Michael Kruse70131d32016-01-27 17:09:17 +00003926 if (auto MemInst = MemAccInst::dyn_cast(Inst))
3927 buildMemoryAccess(MemInst, L, &R, BoxedLoops, ScopRIL);
Michael Kruse7bf39442015-09-10 12:46:52 +00003928
3929 if (isIgnoredIntrinsic(Inst))
3930 continue;
3931
Johannes Doerfert09e36972015-10-07 20:17:36 +00003932 // Do not build scalar dependences for required invariant loads as we will
3933 // hoist them later on anyway or drop the SCoP if we cannot.
3934 if (ScopRIL.count(dyn_cast<LoadInst>(Inst)))
3935 continue;
3936
Michael Kruse7bf39442015-09-10 12:46:52 +00003937 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00003938 if (!isa<StoreInst>(Inst))
Michael Kruse436db622016-01-26 13:33:10 +00003939 ensureValueWrite(Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003940 }
3941 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003942}
Michael Kruse7bf39442015-09-10 12:46:52 +00003943
Michael Kruseee6a4fc2016-01-26 13:33:27 +00003944MemoryAccess *ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3945 MemoryAccess::AccessType Type,
3946 Value *BaseAddress, unsigned ElemBytes,
3947 bool Affine, Value *AccessValue,
3948 ArrayRef<const SCEV *> Subscripts,
3949 ArrayRef<const SCEV *> Sizes,
3950 ScopArrayInfo::MemoryKind Kind) {
Michael Krusecac948e2015-10-02 13:53:07 +00003951 ScopStmt *Stmt = scop->getStmtForBasicBlock(BB);
3952
3953 // Do not create a memory access for anything not in the SCoP. It would be
3954 // ignored anyway.
3955 if (!Stmt)
Michael Kruseee6a4fc2016-01-26 13:33:27 +00003956 return nullptr;
Michael Krusecac948e2015-10-02 13:53:07 +00003957
Michael Krusee2bccbb2015-09-18 19:59:43 +00003958 AccFuncSetType &AccList = AccFuncMap[BB];
Michael Krusee2bccbb2015-09-18 19:59:43 +00003959 Value *BaseAddr = BaseAddress;
3960 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3961
Tobias Grosserf4f68702015-12-14 15:05:37 +00003962 bool isKnownMustAccess = false;
3963
3964 // Accesses in single-basic block statements are always excuted.
3965 if (Stmt->isBlockStmt())
3966 isKnownMustAccess = true;
3967
3968 if (Stmt->isRegionStmt()) {
3969 // Accesses that dominate the exit block of a non-affine region are always
3970 // executed. In non-affine regions there may exist MK_Values that do not
3971 // dominate the exit. MK_Values will always dominate the exit and MK_PHIs
3972 // only if there is at most one PHI_WRITE in the non-affine region.
3973 if (DT->dominates(BB, Stmt->getRegion()->getExit()))
3974 isKnownMustAccess = true;
3975 }
3976
Michael Kruseee6a4fc2016-01-26 13:33:27 +00003977 // Non-affine PHI writes do not "happen" at a particular instruction, but
3978 // after exiting the statement. Therefore they are guaranteed execute and
3979 // overwrite the old value.
3980 if (Kind == ScopArrayInfo::MK_PHI || Kind == ScopArrayInfo::MK_ExitPHI)
3981 isKnownMustAccess = true;
3982
Tobias Grosserf4f68702015-12-14 15:05:37 +00003983 if (!isKnownMustAccess && Type == MemoryAccess::MUST_WRITE)
Michael Krusecac948e2015-10-02 13:53:07 +00003984 Type = MemoryAccess::MAY_WRITE;
3985
Tobias Grosserf1bfd752015-11-05 20:15:37 +00003986 AccList.emplace_back(Stmt, Inst, Type, BaseAddress, ElemBytes, Affine,
Tobias Grossera535dff2015-12-13 19:59:01 +00003987 Subscripts, Sizes, AccessValue, Kind, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00003988 Stmt->addAccess(&AccList.back());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00003989 return &AccList.back();
Michael Kruse7bf39442015-09-10 12:46:52 +00003990}
3991
Michael Kruse70131d32016-01-27 17:09:17 +00003992void ScopInfo::addArrayAccess(MemAccInst MemAccInst,
Tobias Grossera535dff2015-12-13 19:59:01 +00003993 MemoryAccess::AccessType Type, Value *BaseAddress,
3994 unsigned ElemBytes, bool IsAffine,
3995 ArrayRef<const SCEV *> Subscripts,
3996 ArrayRef<const SCEV *> Sizes,
3997 Value *AccessValue) {
Michael Kruse70131d32016-01-27 17:09:17 +00003998 assert(MemAccInst.isLoad() == (Type == MemoryAccess::READ));
3999 addMemoryAccess(MemAccInst.getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00004000 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00004001 ScopArrayInfo::MK_Array);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004002}
Michael Kruse436db622016-01-26 13:33:10 +00004003void ScopInfo::ensureValueWrite(Instruction *Value) {
4004 ScopStmt *Stmt = scop->getStmtForBasicBlock(Value->getParent());
4005
4006 // Value not defined within this SCoP.
4007 if (!Stmt)
4008 return;
4009
4010 // Do not process further if the value is already written.
4011 if (Stmt->lookupValueWriteOf(Value))
4012 return;
4013
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004014 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
4015 true, Value, ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004016 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004017}
Michael Krusead28e5a2016-01-26 13:33:15 +00004018void ScopInfo::ensureValueRead(Value *Value, BasicBlock *UserBB) {
Michael Krusefd463082016-01-27 22:51:56 +00004019
4020 // If the instruction can be synthesized and the user is in the region we do
4021 // not need to add a value dependences.
4022 Region &ScopRegion = scop->getRegion();
4023 if (canSynthesize(Value, LI, SE, &ScopRegion))
4024 return;
4025
Michael Krusead28e5a2016-01-26 13:33:15 +00004026 ScopStmt *UserStmt = scop->getStmtForBasicBlock(UserBB);
4027
4028 // We do not model uses outside the scop.
4029 if (!UserStmt)
4030 return;
4031
4032 // Do not create another MemoryAccess for reloading the value if one already
4033 // exists.
4034 if (UserStmt->lookupValueReadOf(Value))
4035 return;
4036
4037 addMemoryAccess(UserBB, nullptr, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00004038 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004039 ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004040}
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004041void ScopInfo::ensurePHIWrite(PHINode *PHI, BasicBlock *IncomingBlock,
4042 Value *IncomingValue, bool IsExitBlock) {
4043 ScopStmt *IncomingStmt = scop->getStmtForBasicBlock(IncomingBlock);
4044
4045 // Do not add more than one MemoryAccess per PHINode and ScopStmt.
4046 if (MemoryAccess *Acc = IncomingStmt->lookupPHIWriteOf(PHI)) {
4047 assert(Acc->getAccessInstruction() == PHI);
4048 Acc->addIncoming(IncomingBlock, IncomingValue);
4049 return;
4050 }
4051
4052 MemoryAccess *Acc = addMemoryAccess(
4053 IncomingStmt->isBlockStmt() ? IncomingBlock
4054 : IncomingStmt->getRegion()->getEntry(),
4055 PHI, MemoryAccess::MUST_WRITE, PHI, 1, true, PHI,
4056 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
4057 IsExitBlock ? ScopArrayInfo::MK_ExitPHI : ScopArrayInfo::MK_PHI);
4058 assert(Acc);
4059 Acc->addIncoming(IncomingBlock, IncomingValue);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004060}
4061void ScopInfo::addPHIReadAccess(PHINode *PHI) {
4062 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00004063 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004064 ScopArrayInfo::MK_PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004065}
4066
Michael Krusedaf66942015-12-13 22:10:37 +00004067void ScopInfo::buildScop(Region &R, AssumptionCache &AC) {
Michael Kruse9d080092015-09-11 21:41:48 +00004068 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Michael Krusedaf66942015-12-13 22:10:37 +00004069 scop = new Scop(R, AccFuncMap, *SD, *SE, *DT, *LI, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00004070
Michael Krusecac948e2015-10-02 13:53:07 +00004071 buildStmts(R);
Michael Kruse7bf39442015-09-10 12:46:52 +00004072 buildAccessFunctions(R, R);
4073
4074 // In case the region does not have an exiting block we will later (during
4075 // code generation) split the exit block. This will move potential PHI nodes
4076 // from the current exit block into the new region exiting block. Hence, PHI
4077 // nodes that are at this point not part of the region will be.
4078 // To handle these PHI nodes later we will now model their operands as scalar
4079 // accesses. Note that we do not model anything in the exit block if we have
4080 // an exiting block in the region, as there will not be any splitting later.
4081 if (!R.getExitingBlock())
4082 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
4083
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004084 scop->init(*AA, AC);
Michael Kruse7bf39442015-09-10 12:46:52 +00004085}
4086
Michael Krused868b5d2015-09-10 15:25:24 +00004087void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00004088 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00004089 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00004090 return;
4091 }
4092
Michael Kruse9d080092015-09-11 21:41:48 +00004093 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00004094}
4095
Michael Krused868b5d2015-09-10 15:25:24 +00004096void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00004097 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00004098 if (scop) {
4099 delete scop;
4100 scop = 0;
4101 }
Michael Kruse7bf39442015-09-10 12:46:52 +00004102}
4103
4104//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00004105ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00004106 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00004107 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00004108}
4109
4110ScopInfo::~ScopInfo() {
4111 clear();
4112 isl_ctx_free(ctx);
4113}
4114
Tobias Grosser75805372011-04-29 06:27:02 +00004115void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00004116 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00004117 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00004118 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00004119 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4120 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004121 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004122 AU.addRequired<AssumptionCacheTracker>();
Tobias Grosser75805372011-04-29 06:27:02 +00004123 AU.setPreservesAll();
4124}
4125
4126bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00004127 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00004128
Michael Krused868b5d2015-09-10 15:25:24 +00004129 if (!SD->isMaxRegionInScop(*R))
4130 return false;
4131
4132 Function *F = R->getEntry()->getParent();
4133 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4134 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4135 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
4136 TD = &F->getParent()->getDataLayout();
Michael Krusedaf66942015-12-13 22:10:37 +00004137 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004138 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krused868b5d2015-09-10 15:25:24 +00004139
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004140 DebugLoc Beg, End;
4141 getDebugLocations(R, Beg, End);
4142 std::string Msg = "SCoP begins here.";
4143 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg);
4144
Michael Krusedaf66942015-12-13 22:10:37 +00004145 buildScop(*R, AC);
Tobias Grosser75805372011-04-29 06:27:02 +00004146
Tobias Grosserd6a50b32015-05-30 06:26:21 +00004147 DEBUG(scop->print(dbgs()));
4148
Michael Kruseafe06702015-10-02 16:33:27 +00004149 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004150 Msg = "SCoP ends here but was dismissed.";
Johannes Doerfert43788c52015-08-20 05:58:56 +00004151 delete scop;
4152 scop = nullptr;
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004153 } else {
4154 Msg = "SCoP ends here.";
4155 ++ScopFound;
4156 if (scop->getMaxLoopDepth() > 0)
4157 ++RichScopFound;
Johannes Doerfert43788c52015-08-20 05:58:56 +00004158 }
4159
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004160 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg);
4161
Tobias Grosser75805372011-04-29 06:27:02 +00004162 return false;
4163}
4164
4165char ScopInfo::ID = 0;
4166
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004167Pass *polly::createScopInfoPass() { return new ScopInfo(); }
4168
Tobias Grosser73600b82011-10-08 00:30:40 +00004169INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
4170 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004171 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004172INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004173INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004174INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004175INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004176INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004177INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004178INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00004179INITIALIZE_PASS_END(ScopInfo, "polly-scops",
4180 "Polly - Create polyhedral description of Scops", false,
4181 false)