blob: 71c180d53966b610c119434b3a5fff2d785c7265 [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);
296}
297
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000298const std::string
299MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
300 switch (RT) {
301 case MemoryAccess::RT_NONE:
302 llvm_unreachable("Requested a reduction operator string for a memory "
303 "access which isn't a reduction");
304 case MemoryAccess::RT_ADD:
305 return "+";
306 case MemoryAccess::RT_MUL:
307 return "*";
308 case MemoryAccess::RT_BOR:
309 return "|";
310 case MemoryAccess::RT_BXOR:
311 return "^";
312 case MemoryAccess::RT_BAND:
313 return "&";
314 }
315 llvm_unreachable("Unknown reduction type");
316 return "";
317}
318
Johannes Doerfertf6183392014-07-01 20:52:51 +0000319/// @brief Return the reduction type for a given binary operator
320static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
321 const Instruction *Load) {
322 if (!BinOp)
323 return MemoryAccess::RT_NONE;
324 switch (BinOp->getOpcode()) {
325 case Instruction::FAdd:
326 if (!BinOp->hasUnsafeAlgebra())
327 return MemoryAccess::RT_NONE;
328 // Fall through
329 case Instruction::Add:
330 return MemoryAccess::RT_ADD;
331 case Instruction::Or:
332 return MemoryAccess::RT_BOR;
333 case Instruction::Xor:
334 return MemoryAccess::RT_BXOR;
335 case Instruction::And:
336 return MemoryAccess::RT_BAND;
337 case Instruction::FMul:
338 if (!BinOp->hasUnsafeAlgebra())
339 return MemoryAccess::RT_NONE;
340 // Fall through
341 case Instruction::Mul:
342 if (DisableMultiplicativeReductions)
343 return MemoryAccess::RT_NONE;
344 return MemoryAccess::RT_MUL;
345 default:
346 return MemoryAccess::RT_NONE;
347 }
348}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000349
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000350/// @brief Derive the individual index expressions from a GEP instruction
351///
352/// This function optimistically assumes the GEP references into a fixed size
353/// array. If this is actually true, this function returns a list of array
354/// subscript expressions as SCEV as well as a list of integers describing
355/// the size of the individual array dimensions. Both lists have either equal
356/// length of the size list is one element shorter in case there is no known
357/// size available for the outermost array dimension.
358///
359/// @param GEP The GetElementPtr instruction to analyze.
360///
361/// @return A tuple with the subscript expressions and the dimension sizes.
362static std::tuple<std::vector<const SCEV *>, std::vector<int>>
363getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
364 std::vector<const SCEV *> Subscripts;
365 std::vector<int> Sizes;
366
367 Type *Ty = GEP->getPointerOperandType();
368
369 bool DroppedFirstDim = false;
370
Michael Kruse26ed65e2015-09-24 17:32:49 +0000371 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000372
373 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
374
375 if (i == 1) {
376 if (auto PtrTy = dyn_cast<PointerType>(Ty)) {
377 Ty = PtrTy->getElementType();
378 } else if (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
379 Ty = ArrayTy->getElementType();
380 } else {
381 Subscripts.clear();
382 Sizes.clear();
383 break;
384 }
385 if (auto Const = dyn_cast<SCEVConstant>(Expr))
386 if (Const->getValue()->isZero()) {
387 DroppedFirstDim = true;
388 continue;
389 }
390 Subscripts.push_back(Expr);
391 continue;
392 }
393
394 auto ArrayTy = dyn_cast<ArrayType>(Ty);
395 if (!ArrayTy) {
396 Subscripts.clear();
397 Sizes.clear();
398 break;
399 }
400
401 Subscripts.push_back(Expr);
402 if (!(DroppedFirstDim && i == 2))
403 Sizes.push_back(ArrayTy->getNumElements());
404
405 Ty = ArrayTy->getElementType();
406 }
407
408 return std::make_tuple(Subscripts, Sizes);
409}
410
Tobias Grosser75805372011-04-29 06:27:02 +0000411MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000412 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000413 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000414 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000415}
416
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000417const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
418 isl_id *ArrayId = getArrayId();
419 void *User = isl_id_get_user(ArrayId);
420 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
421 isl_id_free(ArrayId);
422 return SAI;
423}
424
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000425__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000426 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
427}
428
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000429__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
430 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000431 isl_map *Schedule, *ScheduledAccRel;
432 isl_union_set *UDomain;
433
434 UDomain = isl_union_set_from_set(getStatement()->getDomain());
435 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
436 Schedule = isl_map_from_union_map(USchedule);
437 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
438 return isl_pw_multi_aff_from_map(ScheduledAccRel);
439}
440
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000441__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000442 return isl_map_copy(AccessRelation);
443}
444
Johannes Doerferta99130f2014-10-13 12:58:03 +0000445std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000446 return stringFromIslObj(AccessRelation);
447}
448
Johannes Doerferta99130f2014-10-13 12:58:03 +0000449__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000450 return isl_map_get_space(AccessRelation);
451}
452
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000453__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000454 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000455}
456
Tobias Grosser6f730082015-09-05 07:46:47 +0000457std::string MemoryAccess::getNewAccessRelationStr() const {
458 return stringFromIslObj(NewAccessRelation);
459}
460
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000461__isl_give isl_basic_map *
462MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000463 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000464 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000465
Tobias Grosser084d8f72012-05-29 09:29:44 +0000466 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000467 isl_basic_set_universe(Statement->getDomainSpace()),
468 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000469}
470
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000471// Formalize no out-of-bound access assumption
472//
473// When delinearizing array accesses we optimistically assume that the
474// delinearized accesses do not access out of bound locations (the subscript
475// expression of each array evaluates for each statement instance that is
476// executed to a value that is larger than zero and strictly smaller than the
477// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000478// dimension for which we do not need to assume any upper bound. At this point
479// we formalize this assumption to ensure that at code generation time the
480// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000481//
482// To find the set of constraints necessary to avoid out of bound accesses, we
483// first build the set of data locations that are not within array bounds. We
484// then apply the reverse access relation to obtain the set of iterations that
485// may contain invalid accesses and reduce this set of iterations to the ones
486// that are actually executed by intersecting them with the domain of the
487// statement. If we now project out all loop dimensions, we obtain a set of
488// parameters that may cause statement instances to be executed that may
489// possibly yield out of bound memory accesses. The complement of these
490// constraints is the set of constraints that needs to be assumed to ensure such
491// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000492void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000493 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000494 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Michael Krusee2bccbb2015-09-18 19:59:43 +0000495 for (int i = 1, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000496 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
497 isl_pw_aff *Var =
498 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
499 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
500
501 isl_set *DimOutside;
502
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000503 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Michael Krusee2bccbb2015-09-18 19:59:43 +0000504 isl_pw_aff *SizeE = Statement->getPwAff(Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000505
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000506 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
507 Statement->getNumIterators());
508 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
509 isl_space_dim(Space, isl_dim_set));
510 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
511 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000512
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000513 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000514
515 Outside = isl_set_union(Outside, DimOutside);
516 }
517
518 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
519 Outside = isl_set_intersect(Outside, Statement->getDomain());
520 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000521
522 // Remove divs to avoid the construction of overly complicated assumptions.
523 // Doing so increases the set of parameter combinations that are assumed to
524 // not appear. This is always save, but may make the resulting run-time check
525 // bail out more often than strictly necessary.
526 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000527 Outside = isl_set_complement(Outside);
Johannes Doerfertd84493e2015-11-12 02:33:38 +0000528 Statement->getParent()->addAssumption(INBOUNDS, Outside,
529 getAccessInstruction()->getDebugLoc());
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
536 Value *Ptr = getPointerOperand(*getAccessInstruction());
537 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
Michael Krusee2bccbb2015-09-18 19:59:43 +0000699 assumeNoOutOfBound();
Tobias Grosseraa660a92015-03-30 00:07:50 +0000700 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000701 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000702}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000703
Michael Krusecac948e2015-10-02 13:53:07 +0000704MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000705 AccessType Type, Value *BaseAddress,
706 unsigned ElemBytes, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000707 ArrayRef<const SCEV *> Subscripts,
708 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000709 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
710 : Kind(Kind), AccType(Type), RedType(RT_NONE), Statement(Stmt),
Michael Krusecac948e2015-10-02 13:53:07 +0000711 BaseAddr(BaseAddress), BaseName(BaseName), ElemBytes(ElemBytes),
712 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
713 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000714 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000715 NewAccessRelation(nullptr) {
716
717 std::string IdName = "__polly_array_ref";
718 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
719}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000720
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000721void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000722 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000723 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000724}
725
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000726const std::string MemoryAccess::getReductionOperatorStr() const {
727 return MemoryAccess::getReductionOperatorStr(getReductionType());
728}
729
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000730__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
731
Johannes Doerfertf6183392014-07-01 20:52:51 +0000732raw_ostream &polly::operator<<(raw_ostream &OS,
733 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000734 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000735 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000736 else
737 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000738 return OS;
739}
740
Tobias Grosser75805372011-04-29 06:27:02 +0000741void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000742 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000743 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000744 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000745 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000746 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000747 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000748 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000749 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000750 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000751 break;
752 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000753 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000754 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000755 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000756 if (hasNewAccessRelation())
757 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000758}
759
Tobias Grosser74394f02013-01-14 22:40:23 +0000760void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000761
762// Create a map in the size of the provided set domain, that maps from the
763// one element of the provided set domain to another element of the provided
764// set domain.
765// The mapping is limited to all points that are equal in all but the last
766// dimension and for which the last dimension of the input is strict smaller
767// than the last dimension of the output.
768//
769// getEqualAndLarger(set[i0, i1, ..., iX]):
770//
771// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
772// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
773//
Tobias Grosserf5338802011-10-06 00:03:35 +0000774static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000775 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000776 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000777 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000778
779 // Set all but the last dimension to be equal for the input and output
780 //
781 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
782 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000783 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000784 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000785
786 // Set the last dimension of the input to be strict smaller than the
787 // last dimension of the output.
788 //
789 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000790 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
791 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000792 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000793}
794
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000795__isl_give isl_set *
796MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000797 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000798 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000799 isl_space *Space = isl_space_range(isl_map_get_space(S));
800 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000801
Sebastian Popa00a0292012-12-18 07:46:06 +0000802 S = isl_map_reverse(S);
803 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000804
Sebastian Popa00a0292012-12-18 07:46:06 +0000805 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
806 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
807 NextScatt = isl_map_apply_domain(NextScatt, S);
808 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000809
Sebastian Popa00a0292012-12-18 07:46:06 +0000810 isl_set *Deltas = isl_map_deltas(NextScatt);
811 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000812}
813
Sebastian Popa00a0292012-12-18 07:46:06 +0000814bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000815 int StrideWidth) const {
816 isl_set *Stride, *StrideX;
817 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000818
Sebastian Popa00a0292012-12-18 07:46:06 +0000819 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000820 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000821 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
822 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
823 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
824 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000825 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000826
Tobias Grosser28dd4862012-01-24 16:42:16 +0000827 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000828 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000829
Tobias Grosser28dd4862012-01-24 16:42:16 +0000830 return IsStrideX;
831}
832
Sebastian Popa00a0292012-12-18 07:46:06 +0000833bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
834 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000835}
836
Sebastian Popa00a0292012-12-18 07:46:06 +0000837bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
838 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000839}
840
Tobias Grosser166c4222015-09-05 07:46:40 +0000841void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
842 isl_map_free(NewAccessRelation);
843 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000844}
Tobias Grosser75805372011-04-29 06:27:02 +0000845
846//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000847
Tobias Grosser808cd692015-07-14 09:33:13 +0000848isl_map *ScopStmt::getSchedule() const {
849 isl_set *Domain = getDomain();
850 if (isl_set_is_empty(Domain)) {
851 isl_set_free(Domain);
852 return isl_map_from_aff(
853 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
854 }
855 auto *Schedule = getParent()->getSchedule();
856 Schedule = isl_union_map_intersect_domain(
857 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
858 if (isl_union_map_is_empty(Schedule)) {
859 isl_set_free(Domain);
860 isl_union_map_free(Schedule);
861 return isl_map_from_aff(
862 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
863 }
864 auto *M = isl_map_from_union_map(Schedule);
865 M = isl_map_coalesce(M);
866 M = isl_map_gist_domain(M, Domain);
867 M = isl_map_coalesce(M);
868 return M;
869}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000870
Johannes Doerfert574182d2015-08-12 10:19:50 +0000871__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000872 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
873 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000874}
875
Tobias Grosser37eb4222014-02-20 21:43:54 +0000876void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
877 assert(isl_set_is_subset(NewDomain, Domain) &&
878 "New domain is not a subset of old domain!");
879 isl_set_free(Domain);
880 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000881}
882
Michael Krusecac948e2015-10-02 13:53:07 +0000883void ScopStmt::buildAccessRelations() {
884 for (MemoryAccess *Access : MemAccs) {
885 Type *ElementType = Access->getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000886
Tobias Grossera535dff2015-12-13 19:59:01 +0000887 ScopArrayInfo::MemoryKind Ty;
888 if (Access->isPHIKind())
889 Ty = ScopArrayInfo::MK_PHI;
890 else if (Access->isExitPHIKind())
891 Ty = ScopArrayInfo::MK_ExitPHI;
892 else if (Access->isValueKind())
893 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000894 else
Tobias Grossera535dff2015-12-13 19:59:01 +0000895 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000896
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000897 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000898 Access->getBaseAddr(), ElementType, Access->Sizes, Ty);
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000899
Michael Krusecac948e2015-10-02 13:53:07 +0000900 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +0000901 }
902}
903
Michael Krusecac948e2015-10-02 13:53:07 +0000904void ScopStmt::addAccess(MemoryAccess *Access) {
905 Instruction *AccessInst = Access->getAccessInstruction();
906
Tobias Grosser10120182015-12-16 16:14:03 +0000907 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
908 MAL.emplace_front(Access);
909 MemAccs.push_back(MAL.front());
Michael Krusecac948e2015-10-02 13:53:07 +0000910}
911
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000912void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000913 for (MemoryAccess *MA : *this)
914 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000915
916 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000917}
918
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000919/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
920static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
921 void *User) {
922 isl_set **BoundedParts = static_cast<isl_set **>(User);
923 if (isl_basic_set_is_bounded(BSet))
924 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
925 else
926 isl_basic_set_free(BSet);
927 return isl_stat_ok;
928}
929
930/// @brief Return the bounded parts of @p S.
931static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
932 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
933 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
934 isl_set_free(S);
935 return BoundedParts;
936}
937
938/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
939///
940/// @returns A separation of @p S into first an unbounded then a bounded subset,
941/// both with regards to the dimension @p Dim.
942static std::pair<__isl_give isl_set *, __isl_give isl_set *>
943partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
944
945 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000946 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000947
948 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000949 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000950
951 // Remove dimensions that are greater than Dim as they are not interesting.
952 assert(NumDimsS >= Dim + 1);
953 OnlyDimS =
954 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
955
956 // Create artificial parametric upper bounds for dimensions smaller than Dim
957 // as we are not interested in them.
958 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
959 for (unsigned u = 0; u < Dim; u++) {
960 isl_constraint *C = isl_inequality_alloc(
961 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
962 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
963 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
964 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
965 }
966
967 // Collect all bounded parts of OnlyDimS.
968 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
969
970 // Create the dimensions greater than Dim again.
971 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
972 NumDimsS - Dim - 1);
973
974 // Remove the artificial upper bound parameters again.
975 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
976
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000977 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000978 return std::make_pair(UnboundedParts, BoundedParts);
979}
980
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000981/// @brief Set the dimension Ids from @p From in @p To.
982static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
983 __isl_take isl_set *To) {
984 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
985 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
986 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
987 }
988 return To;
989}
990
991/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000992static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000993 __isl_take isl_pw_aff *L,
994 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +0000995 switch (Pred) {
996 case ICmpInst::ICMP_EQ:
997 return isl_pw_aff_eq_set(L, R);
998 case ICmpInst::ICMP_NE:
999 return isl_pw_aff_ne_set(L, R);
1000 case ICmpInst::ICMP_SLT:
1001 return isl_pw_aff_lt_set(L, R);
1002 case ICmpInst::ICMP_SLE:
1003 return isl_pw_aff_le_set(L, R);
1004 case ICmpInst::ICMP_SGT:
1005 return isl_pw_aff_gt_set(L, R);
1006 case ICmpInst::ICMP_SGE:
1007 return isl_pw_aff_ge_set(L, R);
1008 case ICmpInst::ICMP_ULT:
1009 return isl_pw_aff_lt_set(L, R);
1010 case ICmpInst::ICMP_UGT:
1011 return isl_pw_aff_gt_set(L, R);
1012 case ICmpInst::ICMP_ULE:
1013 return isl_pw_aff_le_set(L, R);
1014 case ICmpInst::ICMP_UGE:
1015 return isl_pw_aff_ge_set(L, R);
1016 default:
1017 llvm_unreachable("Non integer predicate not supported");
1018 }
1019}
1020
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001021/// @brief Create the conditions under which @p L @p Pred @p R is true.
1022///
1023/// Helper function that will make sure the dimensions of the result have the
1024/// same isl_id's as the @p Domain.
1025static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1026 __isl_take isl_pw_aff *L,
1027 __isl_take isl_pw_aff *R,
1028 __isl_keep isl_set *Domain) {
1029 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1030 return setDimensionIds(Domain, ConsequenceCondSet);
1031}
1032
1033/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001034///
1035/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001036/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1037/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001038static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001039buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001040 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1041
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001042 Value *Condition = getConditionFromTerminator(SI);
1043 assert(Condition && "No condition for switch");
1044
1045 ScalarEvolution &SE = *S.getSE();
1046 BasicBlock *BB = SI->getParent();
1047 isl_pw_aff *LHS, *RHS;
1048 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
1049
1050 unsigned NumSuccessors = SI->getNumSuccessors();
1051 ConditionSets.resize(NumSuccessors);
1052 for (auto &Case : SI->cases()) {
1053 unsigned Idx = Case.getSuccessorIndex();
1054 ConstantInt *CaseValue = Case.getCaseValue();
1055
1056 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
1057 isl_set *CaseConditionSet =
1058 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1059 ConditionSets[Idx] = isl_set_coalesce(
1060 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1061 }
1062
1063 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1064 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1065 for (unsigned u = 2; u < NumSuccessors; u++)
1066 ConditionSetUnion =
1067 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1068 ConditionSets[0] = setDimensionIds(
1069 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1070
1071 S.markAsOptimized();
1072 isl_pw_aff_free(LHS);
1073}
1074
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001075/// @brief Build the conditions sets for the branch condition @p Condition in
1076/// the @p Domain.
1077///
1078/// This will fill @p ConditionSets with the conditions under which control
1079/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001080/// have as many elements as @p TI has successors. If @p TI is nullptr the
1081/// context under which @p Condition is true/false will be returned as the
1082/// new elements of @p ConditionSets.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001083static void
1084buildConditionSets(Scop &S, Value *Condition, TerminatorInst *TI, Loop *L,
1085 __isl_keep isl_set *Domain,
1086 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1087
1088 isl_set *ConsequenceCondSet = nullptr;
1089 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1090 if (CCond->isZero())
1091 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1092 else
1093 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1094 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1095 auto Opcode = BinOp->getOpcode();
1096 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1097
1098 buildConditionSets(S, BinOp->getOperand(0), TI, L, Domain, ConditionSets);
1099 buildConditionSets(S, BinOp->getOperand(1), TI, L, Domain, ConditionSets);
1100
1101 isl_set_free(ConditionSets.pop_back_val());
1102 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1103 isl_set_free(ConditionSets.pop_back_val());
1104 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1105
1106 if (Opcode == Instruction::And)
1107 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1108 else
1109 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1110 } else {
1111 auto *ICond = dyn_cast<ICmpInst>(Condition);
1112 assert(ICond &&
1113 "Condition of exiting branch was neither constant nor ICmp!");
1114
1115 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001116 BasicBlock *BB = TI ? TI->getParent() : nullptr;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001117 isl_pw_aff *LHS, *RHS;
1118 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1119 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
1120 ConsequenceCondSet =
1121 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1122 }
1123
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001124 // If no terminator was given we are only looking for parameter constraints
1125 // under which @p Condition is true/false.
1126 if (!TI)
1127 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
1128
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001129 assert(ConsequenceCondSet);
1130 isl_set *AlternativeCondSet =
1131 isl_set_complement(isl_set_copy(ConsequenceCondSet));
1132
1133 ConditionSets.push_back(isl_set_coalesce(
1134 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
1135 ConditionSets.push_back(isl_set_coalesce(
1136 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
1137}
1138
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001139/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1140///
1141/// This will fill @p ConditionSets with the conditions under which control
1142/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1143/// have as many elements as @p TI has successors.
1144static void
1145buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1146 __isl_keep isl_set *Domain,
1147 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1148
1149 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1150 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1151
1152 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1153
1154 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001155 ConditionSets.push_back(isl_set_copy(Domain));
1156 return;
1157 }
1158
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001159 Value *Condition = getConditionFromTerminator(TI);
1160 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001161
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001162 return buildConditionSets(S, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001163}
1164
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001165void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +00001166 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +00001167
Tobias Grosser084d8f72012-05-29 09:29:44 +00001168 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1169
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001170 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001171 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001172}
1173
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001174void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001175 isl_ctx *Ctx = Parent.getIslCtx();
1176 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1177 Type *Ty = GEP->getPointerOperandType();
1178 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001179 ScopDetection &SD = Parent.getSD();
1180
1181 // The set of loads that are required to be invariant.
1182 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001183
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001184 std::vector<const SCEV *> Subscripts;
1185 std::vector<int> Sizes;
1186
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001187 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001188
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001189 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001190 Ty = PtrTy->getElementType();
1191 }
1192
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001193 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001194
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001195 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001196
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001197 for (size_t i = 0; i < Sizes.size(); i++) {
1198 auto Expr = Subscripts[i + IndexOffset];
1199 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001200
Johannes Doerfert09e36972015-10-07 20:17:36 +00001201 InvariantLoadsSetTy AccessILS;
1202 if (!isAffineExpr(&Parent.getRegion(), Expr, SE, nullptr, &AccessILS))
1203 continue;
1204
1205 bool NonAffine = false;
1206 for (LoadInst *LInst : AccessILS)
1207 if (!ScopRIL.count(LInst))
1208 NonAffine = true;
1209
1210 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001211 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001212
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001213 isl_pw_aff *AccessOffset = getPwAff(Expr);
1214 AccessOffset =
1215 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001216
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001217 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1218 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001219
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001220 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1221 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1222 OutOfBound = isl_set_params(OutOfBound);
1223 isl_set *InBound = isl_set_complement(OutOfBound);
1224 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001225
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001226 // A => B == !A or B
1227 isl_set *InBoundIfExecuted =
1228 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001229
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001230 Parent.addAssumption(INBOUNDS, InBoundIfExecuted, GEP->getDebugLoc());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001231 }
1232
1233 isl_local_space_free(LSpace);
1234}
1235
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001236void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1237 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001238 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1239 deriveAssumptionsFromGEP(GEP);
1240}
1241
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001242void ScopStmt::collectSurroundingLoops() {
1243 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1244 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1245 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1246 isl_id_free(DimId);
1247 }
1248}
1249
Michael Kruse9d080092015-09-11 21:41:48 +00001250ScopStmt::ScopStmt(Scop &parent, Region &R)
Michael Krusecac948e2015-10-02 13:53:07 +00001251 : Parent(parent), Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001252
Tobias Grosser16c44032015-07-09 07:31:45 +00001253 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001254}
1255
Michael Kruse9d080092015-09-11 21:41:48 +00001256ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Michael Krusecac948e2015-10-02 13:53:07 +00001257 : Parent(parent), Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001258
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001259 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001260}
1261
1262void ScopStmt::init() {
1263 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001264
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001265 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001266 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001267 buildAccessRelations();
1268
1269 if (BB) {
1270 deriveAssumptions(BB);
1271 } else {
1272 for (BasicBlock *Block : R->blocks()) {
1273 deriveAssumptions(Block);
1274 }
1275 }
1276
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001277 if (DetectReductions)
1278 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001279}
1280
Johannes Doerferte58a0122014-06-27 20:31:28 +00001281/// @brief Collect loads which might form a reduction chain with @p StoreMA
1282///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001283/// Check if the stored value for @p StoreMA is a binary operator with one or
1284/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001285/// used only once (by @p StoreMA) and its load operands are also used only
1286/// once, we have found a possible reduction chain. It starts at an operand
1287/// load and includes the binary operator and @p StoreMA.
1288///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001289/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001290/// escape this block or into any other store except @p StoreMA.
1291void ScopStmt::collectCandiateReductionLoads(
1292 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1293 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1294 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001295 return;
1296
1297 // Skip if there is not one binary operator between the load and the store
1298 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001299 if (!BinOp)
1300 return;
1301
1302 // Skip if the binary operators has multiple uses
1303 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001304 return;
1305
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001306 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001307 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1308 return;
1309
Johannes Doerfert9890a052014-07-01 00:32:29 +00001310 // Skip if the binary operator is outside the current SCoP
1311 if (BinOp->getParent() != Store->getParent())
1312 return;
1313
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001314 // Skip if it is a multiplicative reduction and we disabled them
1315 if (DisableMultiplicativeReductions &&
1316 (BinOp->getOpcode() == Instruction::Mul ||
1317 BinOp->getOpcode() == Instruction::FMul))
1318 return;
1319
Johannes Doerferte58a0122014-06-27 20:31:28 +00001320 // Check the binary operator operands for a candidate load
1321 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1322 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1323 if (!PossibleLoad0 && !PossibleLoad1)
1324 return;
1325
1326 // A load is only a candidate if it cannot escape (thus has only this use)
1327 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001328 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001329 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001330 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001331 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001332 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001333}
1334
1335/// @brief Check for reductions in this ScopStmt
1336///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001337/// Iterate over all store memory accesses and check for valid binary reduction
1338/// like chains. For all candidates we check if they have the same base address
1339/// and there are no other accesses which overlap with them. The base address
1340/// check rules out impossible reductions candidates early. The overlap check,
1341/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001342/// guarantees that none of the intermediate results will escape during
1343/// execution of the loop nest. We basically check here that no other memory
1344/// access can access the same memory as the potential reduction.
1345void ScopStmt::checkForReductions() {
1346 SmallVector<MemoryAccess *, 2> Loads;
1347 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1348
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001349 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001350 // stores and collecting possible reduction loads.
1351 for (MemoryAccess *StoreMA : MemAccs) {
1352 if (StoreMA->isRead())
1353 continue;
1354
1355 Loads.clear();
1356 collectCandiateReductionLoads(StoreMA, Loads);
1357 for (MemoryAccess *LoadMA : Loads)
1358 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1359 }
1360
1361 // Then check each possible candidate pair.
1362 for (const auto &CandidatePair : Candidates) {
1363 bool Valid = true;
1364 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1365 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1366
1367 // Skip those with obviously unequal base addresses.
1368 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1369 isl_map_free(LoadAccs);
1370 isl_map_free(StoreAccs);
1371 continue;
1372 }
1373
1374 // And check if the remaining for overlap with other memory accesses.
1375 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1376 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1377 isl_set *AllAccs = isl_map_range(AllAccsRel);
1378
1379 for (MemoryAccess *MA : MemAccs) {
1380 if (MA == CandidatePair.first || MA == CandidatePair.second)
1381 continue;
1382
1383 isl_map *AccRel =
1384 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1385 isl_set *Accs = isl_map_range(AccRel);
1386
1387 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1388 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1389 Valid = Valid && isl_set_is_empty(OverlapAccs);
1390 isl_set_free(OverlapAccs);
1391 }
1392 }
1393
1394 isl_set_free(AllAccs);
1395 if (!Valid)
1396 continue;
1397
Johannes Doerfertf6183392014-07-01 20:52:51 +00001398 const LoadInst *Load =
1399 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1400 MemoryAccess::ReductionType RT =
1401 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1402
Johannes Doerferte58a0122014-06-27 20:31:28 +00001403 // If no overlapping access was found we mark the load and store as
1404 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001405 CandidatePair.first->markAsReductionLike(RT);
1406 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001407 }
Tobias Grosser75805372011-04-29 06:27:02 +00001408}
1409
Tobias Grosser74394f02013-01-14 22:40:23 +00001410std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001411
Tobias Grosser54839312015-04-21 11:37:25 +00001412std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001413 auto *S = getSchedule();
1414 auto Str = stringFromIslObj(S);
1415 isl_map_free(S);
1416 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001417}
1418
Tobias Grosser74394f02013-01-14 22:40:23 +00001419unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001420
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001421unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001422
Tobias Grosser75805372011-04-29 06:27:02 +00001423const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1424
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001425const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001426 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001427}
1428
Tobias Grosser74394f02013-01-14 22:40:23 +00001429isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001430
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001431__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001432
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001433__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001434 return isl_set_get_space(Domain);
1435}
1436
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001437__isl_give isl_id *ScopStmt::getDomainId() const {
1438 return isl_set_get_tuple_id(Domain);
1439}
Tobias Grossercd95b772012-08-30 11:49:38 +00001440
Tobias Grosser10120182015-12-16 16:14:03 +00001441ScopStmt::~ScopStmt() { isl_set_free(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001442
1443void ScopStmt::print(raw_ostream &OS) const {
1444 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001445 OS.indent(12) << "Domain :=\n";
1446
1447 if (Domain) {
1448 OS.indent(16) << getDomainStr() << ";\n";
1449 } else
1450 OS.indent(16) << "n/a\n";
1451
Tobias Grosser54839312015-04-21 11:37:25 +00001452 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001453
1454 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001455 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001456 } else
1457 OS.indent(16) << "n/a\n";
1458
Tobias Grosser083d3d32014-06-28 08:59:45 +00001459 for (MemoryAccess *Access : MemAccs)
1460 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001461}
1462
1463void ScopStmt::dump() const { print(dbgs()); }
1464
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001465void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001466 // Remove all memory accesses in @p InvMAs from this statement
1467 // together with all scalar accesses that were caused by them.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001468 for (MemoryAccess *MA : InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001469 auto Predicate = [&](MemoryAccess *Acc) {
Tobias Grosser3a6ac9f2015-11-30 21:13:43 +00001470 return Acc->getAccessInstruction() == MA->getAccessInstruction();
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001471 };
1472 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1473 MemAccs.end());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001474 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001475 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001476}
1477
Tobias Grosser75805372011-04-29 06:27:02 +00001478//===----------------------------------------------------------------------===//
1479/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001480
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001481void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001482 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1483 isl_set_free(Context);
1484 Context = NewContext;
1485}
1486
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001487/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1488struct SCEVSensitiveParameterRewriter
1489 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1490 ValueToValueMap &VMap;
1491 ScalarEvolution &SE;
1492
1493public:
1494 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1495 : VMap(VMap), SE(SE) {}
1496
1497 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1498 ValueToValueMap &VMap) {
1499 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1500 return SSPR.visit(E);
1501 }
1502
1503 const SCEV *visit(const SCEV *E) {
1504 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1505 }
1506
1507 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1508
1509 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1510 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1511 }
1512
1513 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1514 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1515 }
1516
1517 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1518 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1519 }
1520
1521 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1522 SmallVector<const SCEV *, 4> Operands;
1523 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1524 Operands.push_back(visit(E->getOperand(i)));
1525 return SE.getAddExpr(Operands);
1526 }
1527
1528 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1529 SmallVector<const SCEV *, 4> Operands;
1530 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1531 Operands.push_back(visit(E->getOperand(i)));
1532 return SE.getMulExpr(Operands);
1533 }
1534
1535 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1536 SmallVector<const SCEV *, 4> Operands;
1537 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1538 Operands.push_back(visit(E->getOperand(i)));
1539 return SE.getSMaxExpr(Operands);
1540 }
1541
1542 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1543 SmallVector<const SCEV *, 4> Operands;
1544 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1545 Operands.push_back(visit(E->getOperand(i)));
1546 return SE.getUMaxExpr(Operands);
1547 }
1548
1549 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1550 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1551 }
1552
1553 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1554 auto *Start = visit(E->getStart());
1555 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1556 visit(E->getStepRecurrence(SE)),
1557 E->getLoop(), SCEV::FlagAnyWrap);
1558 return SE.getAddExpr(Start, AddRec);
1559 }
1560
1561 const SCEV *visitUnknown(const SCEVUnknown *E) {
1562 if (auto *NewValue = VMap.lookup(E->getValue()))
1563 return SE.getUnknown(NewValue);
1564 return E;
1565 }
1566};
1567
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001568const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001569 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001570}
1571
Tobias Grosserabfbe632013-02-05 12:09:06 +00001572void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001573 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001574 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001575
1576 // Normalize the SCEV to get the representing element for an invariant load.
1577 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1578
Tobias Grosser60b54f12011-11-08 15:41:28 +00001579 if (ParameterIds.find(Parameter) != ParameterIds.end())
1580 continue;
1581
1582 int dimension = Parameters.size();
1583
1584 Parameters.push_back(Parameter);
1585 ParameterIds[Parameter] = dimension;
1586 }
1587}
1588
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001589__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001590 // Normalize the SCEV to get the representing element for an invariant load.
1591 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1592
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001593 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001594
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001595 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001596 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001597
Tobias Grosser8f99c162011-11-15 11:38:55 +00001598 std::string ParameterName;
1599
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001600 ParameterName = "p_" + utostr_32(IdIter->second);
1601
Tobias Grosser8f99c162011-11-15 11:38:55 +00001602 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1603 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001604
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001605 // If this parameter references a specific Value and this value has a name
1606 // we use this name as it is likely to be unique and more useful than just
1607 // a number.
1608 if (Val->hasName())
1609 ParameterName = Val->getName();
1610 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
1611 auto LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
1612 if (LoadOrigin->hasName()) {
1613 ParameterName += "_loaded_from_";
1614 ParameterName +=
1615 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1616 }
1617 }
1618 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001619
Tobias Grosser20532b82014-04-11 17:56:49 +00001620 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1621 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001622}
Tobias Grosser75805372011-04-29 06:27:02 +00001623
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001624isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1625 isl_set *DomainContext = isl_union_set_params(getDomains());
1626 return isl_set_intersect_params(C, DomainContext);
1627}
1628
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001629void Scop::buildBoundaryContext() {
Tobias Grosser4927c8e2015-11-24 12:50:02 +00001630 if (IgnoreIntegerWrapping) {
1631 BoundaryContext = isl_set_universe(getParamSpace());
1632 return;
1633 }
1634
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001635 BoundaryContext = Affinator.getWrappingContext();
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001636
1637 // The isl_set_complement operation used to create the boundary context
1638 // can possibly become very expensive. We bound the compile time of
1639 // this operation by setting a compute out.
1640 //
1641 // TODO: We can probably get around using isl_set_complement and directly
1642 // AST generate BoundaryContext.
1643 long MaxOpsOld = isl_ctx_get_max_operations(getIslCtx());
Tobias Grosserf920fb12015-11-13 16:56:13 +00001644 isl_ctx_reset_operations(getIslCtx());
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001645 isl_ctx_set_max_operations(getIslCtx(), 300000);
1646 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_CONTINUE);
1647
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001648 BoundaryContext = isl_set_complement(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001649
Tobias Grossera52b4da2015-11-11 17:59:53 +00001650 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
1651 isl_set_free(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001652 BoundaryContext = isl_set_empty(getParamSpace());
Tobias Grossera52b4da2015-11-11 17:59:53 +00001653 }
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001654
1655 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
1656 isl_ctx_reset_operations(getIslCtx());
1657 isl_ctx_set_max_operations(getIslCtx(), MaxOpsOld);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001658 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001659 trackAssumption(WRAPPING, BoundaryContext, DebugLoc());
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001660}
1661
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001662void Scop::addUserAssumptions(AssumptionCache &AC) {
1663 auto *R = &getRegion();
1664 auto &F = *R->getEntry()->getParent();
1665 for (auto &Assumption : AC.assumptions()) {
1666 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1667 if (!CI || CI->getNumArgOperands() != 1)
1668 continue;
1669 if (!DT.dominates(CI->getParent(), R->getEntry()))
1670 continue;
1671
1672 auto *Val = CI->getArgOperand(0);
1673 std::vector<const SCEV *> Params;
1674 if (!isAffineParamConstraint(Val, R, *SE, Params)) {
1675 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1676 CI->getDebugLoc(),
1677 "Non-affine user assumption ignored.");
1678 continue;
1679 }
1680
1681 addParams(Params);
1682
1683 auto *L = LI.getLoopFor(CI->getParent());
1684 SmallVector<isl_set *, 2> ConditionSets;
1685 buildConditionSets(*this, Val, nullptr, L, Context, ConditionSets);
1686 assert(ConditionSets.size() == 2);
1687 isl_set_free(ConditionSets[1]);
1688
1689 auto *AssumptionCtx = ConditionSets[0];
1690 emitOptimizationRemarkAnalysis(
1691 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1692 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1693 Context = isl_set_intersect(Context, AssumptionCtx);
1694 }
1695}
1696
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001697void Scop::addUserContext() {
1698 if (UserContextStr.empty())
1699 return;
1700
1701 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1702 isl_space *Space = getParamSpace();
1703 if (isl_space_dim(Space, isl_dim_param) !=
1704 isl_set_dim(UserContext, isl_dim_param)) {
1705 auto SpaceStr = isl_space_to_str(Space);
1706 errs() << "Error: the context provided in -polly-context has not the same "
1707 << "number of dimensions than the computed context. Due to this "
1708 << "mismatch, the -polly-context option is ignored. Please provide "
1709 << "the context in the parameter space: " << SpaceStr << ".\n";
1710 free(SpaceStr);
1711 isl_set_free(UserContext);
1712 isl_space_free(Space);
1713 return;
1714 }
1715
1716 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1717 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1718 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1719
1720 if (strcmp(NameContext, NameUserContext) != 0) {
1721 auto SpaceStr = isl_space_to_str(Space);
1722 errs() << "Error: the name of dimension " << i
1723 << " provided in -polly-context "
1724 << "is '" << NameUserContext << "', but the name in the computed "
1725 << "context is '" << NameContext
1726 << "'. Due to this name mismatch, "
1727 << "the -polly-context option is ignored. Please provide "
1728 << "the context in the parameter space: " << SpaceStr << ".\n";
1729 free(SpaceStr);
1730 isl_set_free(UserContext);
1731 isl_space_free(Space);
1732 return;
1733 }
1734
1735 UserContext =
1736 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1737 isl_space_get_dim_id(Space, isl_dim_param, i));
1738 }
1739
1740 Context = isl_set_intersect(Context, UserContext);
1741 isl_space_free(Space);
1742}
1743
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001744void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001745 DenseMap<const SCEV *, LoadInst *> EquivClasses;
1746
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001747 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001748 for (LoadInst *LInst : RIL) {
1749 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1750
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001751 LoadInst *&ClassRep = EquivClasses[PointerSCEV];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001752 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001753 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001754 continue;
1755 }
1756
1757 ClassRep = LInst;
1758 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(),
1759 nullptr);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001760 }
1761}
1762
Tobias Grosser6be480c2011-11-08 15:41:13 +00001763void Scop::buildContext() {
1764 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001765 Context = isl_set_universe(isl_space_copy(Space));
1766 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001767}
1768
Tobias Grosser18daaca2012-05-22 10:47:27 +00001769void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001770 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001771 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001772
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001773 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001774
Johannes Doerferte7044942015-02-24 11:58:30 +00001775 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001776 }
1777}
1778
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001779void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001780 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001781 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001782
Tobias Grosser083d3d32014-06-28 08:59:45 +00001783 for (const auto &ParamID : ParameterIds) {
1784 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001785 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001786 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001787 }
1788
1789 // Align the parameters of all data structures to the model.
1790 Context = isl_set_align_params(Context, Space);
1791
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001792 for (ScopStmt &Stmt : *this)
1793 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001794}
1795
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001796static __isl_give isl_set *
1797simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1798 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001799 // If we modelt all blocks in the SCoP that have side effects we can simplify
1800 // the context with the constraints that are needed for anything to be
1801 // executed at all. However, if we have error blocks in the SCoP we already
1802 // assumed some parameter combinations cannot occure and removed them from the
1803 // domains, thus we cannot use the remaining domain to simplify the
1804 // assumptions.
1805 if (!S.hasErrorBlock()) {
1806 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1807 AssumptionContext =
1808 isl_set_gist_params(AssumptionContext, DomainParameters);
1809 }
1810
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001811 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1812 return AssumptionContext;
1813}
1814
1815void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001816 // The parameter constraints of the iteration domains give us a set of
1817 // constraints that need to hold for all cases where at least a single
1818 // statement iteration is executed in the whole scop. We now simplify the
1819 // assumed context under the assumption that such constraints hold and at
1820 // least a single statement iteration is executed. For cases where no
1821 // statement instances are executed, the assumptions we have taken about
1822 // the executed code do not matter and can be changed.
1823 //
1824 // WARNING: This only holds if the assumptions we have taken do not reduce
1825 // the set of statement instances that are executed. Otherwise we
1826 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001827 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001828 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001829 // performed. In such a case, modifying the run-time conditions and
1830 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001831 // to not be executed.
1832 //
1833 // Example:
1834 //
1835 // When delinearizing the following code:
1836 //
1837 // for (long i = 0; i < 100; i++)
1838 // for (long j = 0; j < m; j++)
1839 // A[i+p][j] = 1.0;
1840 //
1841 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001842 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001843 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001844 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1845 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001846}
1847
Johannes Doerfertb164c792014-09-18 11:17:17 +00001848/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001849static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001850 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1851 isl_pw_multi_aff *MinPMA, *MaxPMA;
1852 isl_pw_aff *LastDimAff;
1853 isl_aff *OneAff;
1854 unsigned Pos;
1855
Johannes Doerfert9143d672014-09-27 11:02:39 +00001856 // Restrict the number of parameters involved in the access as the lexmin/
1857 // lexmax computation will take too long if this number is high.
1858 //
1859 // Experiments with a simple test case using an i7 4800MQ:
1860 //
1861 // #Parameters involved | Time (in sec)
1862 // 6 | 0.01
1863 // 7 | 0.04
1864 // 8 | 0.12
1865 // 9 | 0.40
1866 // 10 | 1.54
1867 // 11 | 6.78
1868 // 12 | 30.38
1869 //
1870 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1871 unsigned InvolvedParams = 0;
1872 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1873 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1874 InvolvedParams++;
1875
1876 if (InvolvedParams > RunTimeChecksMaxParameters) {
1877 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001878 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001879 }
1880 }
1881
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001882 Set = isl_set_remove_divs(Set);
1883
Johannes Doerfertb164c792014-09-18 11:17:17 +00001884 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1885 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1886
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001887 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1888 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1889
Johannes Doerfertb164c792014-09-18 11:17:17 +00001890 // Adjust the last dimension of the maximal access by one as we want to
1891 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1892 // we test during code generation might now point after the end of the
1893 // allocated array but we will never dereference it anyway.
1894 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1895 "Assumed at least one output dimension");
1896 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1897 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1898 OneAff = isl_aff_zero_on_domain(
1899 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1900 OneAff = isl_aff_add_constant_si(OneAff, 1);
1901 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1902 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1903
1904 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1905
1906 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001907 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001908}
1909
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001910static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1911 isl_set *Domain = MA->getStatement()->getDomain();
1912 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1913 return isl_set_reset_tuple_id(Domain);
1914}
1915
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001916/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1917static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001918 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001919 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001920
1921 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1922 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001923 Locations = isl_union_set_coalesce(Locations);
1924 Locations = isl_union_set_detect_equalities(Locations);
1925 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001926 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001927 isl_union_set_free(Locations);
1928 return Valid;
1929}
1930
Johannes Doerfert96425c22015-08-30 21:13:53 +00001931/// @brief Helper to treat non-affine regions and basic blocks the same.
1932///
1933///{
1934
1935/// @brief Return the block that is the representing block for @p RN.
1936static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1937 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1938 : RN->getNodeAs<BasicBlock>();
1939}
1940
1941/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001942static inline BasicBlock *
1943getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001944 if (RN->isSubRegion()) {
1945 assert(idx == 0);
1946 return RN->getNodeAs<Region>()->getExit();
1947 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001948 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001949}
1950
1951/// @brief Return the smallest loop surrounding @p RN.
1952static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1953 if (!RN->isSubRegion())
1954 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1955
1956 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1957 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1958 while (L && NonAffineSubRegion->contains(L))
1959 L = L->getParentLoop();
1960 return L;
1961}
1962
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001963static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1964 if (!RN->isSubRegion())
1965 return 1;
1966
1967 unsigned NumBlocks = 0;
1968 Region *R = RN->getNodeAs<Region>();
1969 for (auto BB : R->blocks()) {
1970 (void)BB;
1971 NumBlocks++;
1972 }
1973 return NumBlocks;
1974}
1975
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001976static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
1977 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00001978 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001979 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00001980 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001981 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00001982 return true;
1983 return false;
1984}
1985
Johannes Doerfert96425c22015-08-30 21:13:53 +00001986///}
1987
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001988static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1989 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001990 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001991 isl_id *DimId =
1992 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
1993 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
1994}
1995
Johannes Doerfert96425c22015-08-30 21:13:53 +00001996isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1997 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1998 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00001999 return getDomainConditions(BB);
2000}
2001
2002isl_set *Scop::getDomainConditions(BasicBlock *BB) {
2003 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002004 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002005}
2006
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002007void Scop::removeErrorBlockDomains() {
2008 auto removeDomains = [this](BasicBlock *Start) {
2009 auto BBNode = DT.getNode(Start);
2010 for (auto ErrorChild : depth_first(BBNode)) {
2011 auto ErrorChildBlock = ErrorChild->getBlock();
2012 auto CurrentDomain = DomainMap[ErrorChildBlock];
2013 auto Empty = isl_set_empty(isl_set_get_space(CurrentDomain));
2014 DomainMap[ErrorChildBlock] = Empty;
2015 isl_set_free(CurrentDomain);
2016 }
2017 };
2018
Tobias Grosser5ef2bc32015-11-23 10:18:23 +00002019 SmallVector<Region *, 4> Todo = {&R};
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002020
2021 while (!Todo.empty()) {
2022 auto SubRegion = Todo.back();
2023 Todo.pop_back();
2024
2025 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
2026 for (auto &Child : *SubRegion)
2027 Todo.push_back(Child.get());
2028 continue;
2029 }
2030 if (containsErrorBlock(SubRegion->getNode(), getRegion(), LI, DT))
2031 removeDomains(SubRegion->getEntry());
2032 }
2033
2034 for (auto BB : R.blocks())
2035 if (isErrorBlock(*BB, R, LI, DT))
2036 removeDomains(BB);
2037}
2038
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002039void Scop::buildDomains(Region *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002040
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002041 auto *EntryBB = R->getEntry();
2042 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
2043 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002044
2045 Loop *L = LI.getLoopFor(EntryBB);
2046 while (LD-- >= 0) {
2047 S = addDomainDimId(S, LD + 1, L);
2048 L = L->getParentLoop();
2049 }
2050
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002051 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002052
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002053 if (SD.isNonAffineSubRegion(R, R))
2054 return;
2055
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002056 buildDomainsWithBranchConstraints(R);
2057 propagateDomainConstraints(R);
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002058
2059 // Error blocks and blocks dominated by them have been assumed to never be
2060 // executed. Representing them in the Scop does not add any value. In fact,
2061 // it is likely to cause issues during construction of the ScopStmts. The
2062 // contents of error blocks have not been verfied to be expressible and
2063 // will cause problems when building up a ScopStmt for them.
2064 // Furthermore, basic blocks dominated by error blocks may reference
2065 // instructions in the error block which, if the error block is not modeled,
2066 // can themselves not be constructed properly.
2067 removeErrorBlockDomains();
Johannes Doerfert96425c22015-08-30 21:13:53 +00002068}
2069
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002070void Scop::buildDomainsWithBranchConstraints(Region *R) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002071 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00002072
2073 // To create the domain for each block in R we iterate over all blocks and
2074 // subregions in R and propagate the conditions under which the current region
2075 // element is executed. To this end we iterate in reverse post order over R as
2076 // it ensures that we first visit all predecessors of a region node (either a
2077 // basic block or a subregion) before we visit the region node itself.
2078 // Initially, only the domain for the SCoP region entry block is set and from
2079 // there we propagate the current domain to all successors, however we add the
2080 // condition that the successor is actually executed next.
2081 // As we are only interested in non-loop carried constraints here we can
2082 // simply skip loop back edges.
2083
2084 ReversePostOrderTraversal<Region *> RTraversal(R);
2085 for (auto *RN : RTraversal) {
2086
2087 // Recurse for affine subregions but go on for basic blocks and non-affine
2088 // subregions.
2089 if (RN->isSubRegion()) {
2090 Region *SubRegion = RN->getNodeAs<Region>();
2091 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002092 buildDomainsWithBranchConstraints(SubRegion);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002093 continue;
2094 }
2095 }
2096
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002097 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002098 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002099
Johannes Doerfert96425c22015-08-30 21:13:53 +00002100 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002101 TerminatorInst *TI = BB->getTerminator();
2102
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002103 if (isa<UnreachableInst>(TI))
2104 continue;
2105
Johannes Doerfertf5673802015-10-01 23:48:18 +00002106 isl_set *Domain = DomainMap.lookup(BB);
2107 if (!Domain) {
2108 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2109 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002110 continue;
2111 }
2112
Johannes Doerfert96425c22015-08-30 21:13:53 +00002113 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002114
2115 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2116 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2117
2118 // Build the condition sets for the successor nodes of the current region
2119 // node. If it is a non-affine subregion we will always execute the single
2120 // exit node, hence the single entry node domain is the condition set. For
2121 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002122 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002123 if (RN->isSubRegion())
2124 ConditionSets.push_back(isl_set_copy(Domain));
2125 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002126 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002127
2128 // Now iterate over the successors and set their initial domain based on
2129 // their condition set. We skip back edges here and have to be careful when
2130 // we leave a loop not to keep constraints over a dimension that doesn't
2131 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002132 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002133 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002134 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002135 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002136
2137 // Skip back edges.
2138 if (DT.dominates(SuccBB, BB)) {
2139 isl_set_free(CondSet);
2140 continue;
2141 }
2142
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002143 // Do not adjust the number of dimensions if we enter a boxed loop or are
2144 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002145 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002146 Region *SuccRegion = RI.getRegionFor(SuccBB);
Johannes Doerfert634909c2015-10-04 14:57:41 +00002147 if (SD.isNonAffineSubRegion(SuccRegion, &getRegion()))
2148 while (SuccBBLoop && SuccRegion->contains(SuccBBLoop))
2149 SuccBBLoop = SuccBBLoop->getParentLoop();
2150
2151 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002152
2153 // Check if the edge to SuccBB is a loop entry or exit edge. If so
2154 // adjust the dimensionality accordingly. Lastly, if we leave a loop
2155 // and enter a new one we need to drop the old constraints.
2156 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002157 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002158 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002159 CondSet = isl_set_project_out(CondSet, isl_dim_set,
2160 isl_set_n_dim(CondSet) - LoopDepthDiff,
2161 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002162 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002163 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002164 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002165 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002166 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002167 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002168 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
2169 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002170 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002171 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002172 }
2173
2174 // Set the domain for the successor or merge it with an existing domain in
2175 // case there are multiple paths (without loop back edges) to the
2176 // successor block.
2177 isl_set *&SuccDomain = DomainMap[SuccBB];
2178 if (!SuccDomain)
2179 SuccDomain = CondSet;
2180 else
2181 SuccDomain = isl_set_union(SuccDomain, CondSet);
2182
2183 SuccDomain = isl_set_coalesce(SuccDomain);
Tobias Grosser75dc40c2015-12-20 13:31:48 +00002184 if (isl_set_n_basic_set(SuccDomain) > MaxConjunctsInDomain) {
2185 auto *Empty = isl_set_empty(isl_set_get_space(SuccDomain));
2186 isl_set_free(SuccDomain);
2187 SuccDomain = Empty;
2188 invalidate(ERROR_DOMAINCONJUNCTS, DebugLoc());
2189 }
Johannes Doerfert634909c2015-10-04 14:57:41 +00002190 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
2191 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002192 }
2193 }
2194}
2195
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002196/// @brief Return the domain for @p BB wrt @p DomainMap.
2197///
2198/// This helper function will lookup @p BB in @p DomainMap but also handle the
2199/// case where @p BB is contained in a non-affine subregion using the region
2200/// tree obtained by @p RI.
2201static __isl_give isl_set *
2202getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
2203 RegionInfo &RI) {
2204 auto DIt = DomainMap.find(BB);
2205 if (DIt != DomainMap.end())
2206 return isl_set_copy(DIt->getSecond());
2207
2208 Region *R = RI.getRegionFor(BB);
2209 while (R->getEntry() == BB)
2210 R = R->getParent();
2211 return getDomainForBlock(R->getEntry(), DomainMap, RI);
2212}
2213
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002214void Scop::propagateDomainConstraints(Region *R) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002215 // Iterate over the region R and propagate the domain constrains from the
2216 // predecessors to the current node. In contrast to the
2217 // buildDomainsWithBranchConstraints function, this one will pull the domain
2218 // information from the predecessors instead of pushing it to the successors.
2219 // Additionally, we assume the domains to be already present in the domain
2220 // map here. However, we iterate again in reverse post order so we know all
2221 // predecessors have been visited before a block or non-affine subregion is
2222 // visited.
2223
2224 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2225 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2226
2227 ReversePostOrderTraversal<Region *> RTraversal(R);
2228 for (auto *RN : RTraversal) {
2229
2230 // Recurse for affine subregions but go on for basic blocks and non-affine
2231 // subregions.
2232 if (RN->isSubRegion()) {
2233 Region *SubRegion = RN->getNodeAs<Region>();
2234 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002235 propagateDomainConstraints(SubRegion);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002236 continue;
2237 }
2238 }
2239
Johannes Doerfertf5673802015-10-01 23:48:18 +00002240 // Get the domain for the current block and check if it was initialized or
2241 // not. The only way it was not is if this block is only reachable via error
2242 // blocks, thus will not be executed under the assumptions we make. Such
2243 // blocks have to be skipped as their predecessors might not have domains
2244 // either. It would not benefit us to compute the domain anyway, only the
2245 // domains of the error blocks that are reachable from non-error blocks
2246 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002247 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002248 isl_set *&Domain = DomainMap[BB];
2249 if (!Domain) {
2250 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2251 << ", it is only reachable from error blocks.\n");
2252 DomainMap.erase(BB);
2253 continue;
2254 }
2255 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
2256
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002257 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2258 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2259
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002260 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2261 for (auto *PredBB : predecessors(BB)) {
2262
2263 // Skip backedges
2264 if (DT.dominates(BB, PredBB))
2265 continue;
2266
2267 isl_set *PredBBDom = nullptr;
2268
2269 // Handle the SCoP entry block with its outside predecessors.
2270 if (!getRegion().contains(PredBB))
2271 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
2272
2273 if (!PredBBDom) {
2274 // Determine the loop depth of the predecessor and adjust its domain to
2275 // the domain of the current block. This can mean we have to:
2276 // o) Drop a dimension if this block is the exit of a loop, not the
2277 // header of a new loop and the predecessor was part of the loop.
2278 // o) Add an unconstrainted new dimension if this block is the header
2279 // of a loop and the predecessor is not part of it.
2280 // o) Drop the information about the innermost loop dimension when the
2281 // predecessor and the current block are surrounded by different
2282 // loops in the same depth.
2283 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2284 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2285 while (BoxedLoops.count(PredBBLoop))
2286 PredBBLoop = PredBBLoop->getParentLoop();
2287
2288 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002289 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002290 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002291 PredBBDom = isl_set_project_out(
2292 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2293 LoopDepthDiff);
2294 else if (PredBBLoopDepth < BBLoopDepth) {
2295 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002296 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002297 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2298 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002299 PredBBDom = isl_set_drop_constraints_involving_dims(
2300 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002301 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002302 }
2303
2304 PredDom = isl_set_union(PredDom, PredBBDom);
2305 }
2306
2307 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002308 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002309
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002310 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002311 addLoopBoundsToHeaderDomain(BBLoop);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002312
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002313 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002314 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002315 IsOptimized = true;
2316 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002317 addAssumption(ERRORBLOCK, isl_set_complement(DomPar),
2318 BB->getTerminator()->getDebugLoc());
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002319 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002320 }
2321}
2322
2323/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2324/// is incremented by one and all other dimensions are equal, e.g.,
2325/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2326/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2327static __isl_give isl_map *
2328createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2329 auto *MapSpace = isl_space_map_from_set(SetSpace);
2330 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2331 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2332 if (u != Dim)
2333 NextIterationMap =
2334 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2335 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2336 C = isl_constraint_set_constant_si(C, 1);
2337 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2338 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2339 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2340 return NextIterationMap;
2341}
2342
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002343void Scop::addLoopBoundsToHeaderDomain(Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002344 int LoopDepth = getRelativeLoopDepth(L);
2345 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002346
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002347 BasicBlock *HeaderBB = L->getHeader();
2348 assert(DomainMap.count(HeaderBB));
2349 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002350
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002351 isl_map *NextIterationMap =
2352 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002353
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002354 isl_set *UnionBackedgeCondition =
2355 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002356
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002357 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2358 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002359
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002360 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002361
2362 // If the latch is only reachable via error statements we skip it.
2363 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2364 if (!LatchBBDom)
2365 continue;
2366
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002367 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002368
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002369 TerminatorInst *TI = LatchBB->getTerminator();
2370 BranchInst *BI = dyn_cast<BranchInst>(TI);
2371 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002372 BackedgeCondition = isl_set_copy(LatchBBDom);
2373 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002374 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002375 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002376 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002377
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002378 // Free the non back edge condition set as we do not need it.
2379 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002380
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002381 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002382 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002383
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002384 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2385 assert(LatchLoopDepth >= LoopDepth);
2386 BackedgeCondition =
2387 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2388 LatchLoopDepth - LoopDepth);
2389 UnionBackedgeCondition =
2390 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002391 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002392
2393 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2394 for (int i = 0; i < LoopDepth; i++)
2395 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2396
2397 isl_set *UnionBackedgeConditionComplement =
2398 isl_set_complement(UnionBackedgeCondition);
2399 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2400 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2401 UnionBackedgeConditionComplement =
2402 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2403 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2404 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2405
2406 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2407 HeaderBBDom = Parts.second;
2408
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002409 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2410 // the bounded assumptions to the context as they are already implied by the
2411 // <nsw> tag.
2412 if (Affinator.hasNSWAddRecForLoop(L)) {
2413 isl_set_free(Parts.first);
2414 return;
2415 }
2416
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002417 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2418 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002419 addAssumption(INFINITELOOP, BoundedCtx,
2420 HeaderBB->getTerminator()->getDebugLoc());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002421}
2422
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002423void Scop::buildAliasChecks(AliasAnalysis &AA) {
2424 if (!PollyUseRuntimeAliasChecks)
2425 return;
2426
2427 if (buildAliasGroups(AA))
2428 return;
2429
2430 // If a problem occurs while building the alias groups we need to delete
2431 // this SCoP and pretend it wasn't valid in the first place. To this end
2432 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002433 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002434
2435 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2436 << " could not be created as the number of parameters involved "
2437 "is too high. The SCoP will be "
2438 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2439 "the maximal number of parameters but be advised that the "
2440 "compile time might increase exponentially.\n\n");
2441}
2442
Johannes Doerfert9143d672014-09-27 11:02:39 +00002443bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002444 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002445 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002446 // for all memory accesses inside the SCoP.
2447 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002448 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002449 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002450 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002451 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002452 // if their access domains intersect, otherwise they are in different
2453 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002454 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002455 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002456 // and maximal accesses to each array of a group in read only and non
2457 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002458 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2459
2460 AliasSetTracker AST(AA);
2461
2462 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002463 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002464 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002465
2466 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002467 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002468 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2469 isl_set_free(StmtDomain);
2470 if (StmtDomainEmpty)
2471 continue;
2472
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002473 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002474 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002475 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002476 if (!MA->isRead())
2477 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002478 Instruction *Acc = MA->getAccessInstruction();
2479 PtrToAcc[getPointerOperand(*Acc)] = MA;
2480 AST.add(Acc);
2481 }
2482 }
2483
2484 SmallVector<AliasGroupTy, 4> AliasGroups;
2485 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002486 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002487 continue;
2488 AliasGroupTy AG;
2489 for (auto PR : AS)
2490 AG.push_back(PtrToAcc[PR.getValue()]);
2491 assert(AG.size() > 1 &&
2492 "Alias groups should contain at least two accesses");
2493 AliasGroups.push_back(std::move(AG));
2494 }
2495
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002496 // Split the alias groups based on their domain.
2497 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2498 AliasGroupTy NewAG;
2499 AliasGroupTy &AG = AliasGroups[u];
2500 AliasGroupTy::iterator AGI = AG.begin();
2501 isl_set *AGDomain = getAccessDomain(*AGI);
2502 while (AGI != AG.end()) {
2503 MemoryAccess *MA = *AGI;
2504 isl_set *MADomain = getAccessDomain(MA);
2505 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2506 NewAG.push_back(MA);
2507 AGI = AG.erase(AGI);
2508 isl_set_free(MADomain);
2509 } else {
2510 AGDomain = isl_set_union(AGDomain, MADomain);
2511 AGI++;
2512 }
2513 }
2514 if (NewAG.size() > 1)
2515 AliasGroups.push_back(std::move(NewAG));
2516 isl_set_free(AGDomain);
2517 }
2518
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002519 auto &F = *getRegion().getEntry()->getParent();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002520 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002521 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2522 for (AliasGroupTy &AG : AliasGroups) {
2523 NonReadOnlyBaseValues.clear();
2524 ReadOnlyPairs.clear();
2525
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002526 if (AG.size() < 2) {
2527 AG.clear();
2528 continue;
2529 }
2530
Johannes Doerfert13771732014-10-01 12:40:46 +00002531 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002532 emitOptimizationRemarkAnalysis(
2533 F.getContext(), DEBUG_TYPE, F,
2534 (*II)->getAccessInstruction()->getDebugLoc(),
2535 "Possibly aliasing pointer, use restrict keyword.");
2536
Johannes Doerfert13771732014-10-01 12:40:46 +00002537 Value *BaseAddr = (*II)->getBaseAddr();
2538 if (HasWriteAccess.count(BaseAddr)) {
2539 NonReadOnlyBaseValues.insert(BaseAddr);
2540 II++;
2541 } else {
2542 ReadOnlyPairs[BaseAddr].insert(*II);
2543 II = AG.erase(II);
2544 }
2545 }
2546
2547 // If we don't have read only pointers check if there are at least two
2548 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002549 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002550 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002551 continue;
2552 }
2553
2554 // If we don't have non read only pointers clear the alias group.
2555 if (NonReadOnlyBaseValues.empty()) {
2556 AG.clear();
2557 continue;
2558 }
2559
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002560 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002561 MinMaxAliasGroups.emplace_back();
2562 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2563 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2564 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2565 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002566
2567 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002568
2569 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002570 for (MemoryAccess *MA : AG)
2571 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002572
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002573 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2574 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002575
2576 // Bail out if the number of values we need to compare is too large.
2577 // This is important as the number of comparisions grows quadratically with
2578 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002579 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2580 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002581 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002582
2583 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002584 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002585 Accesses = isl_union_map_empty(getParamSpace());
2586
2587 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2588 for (MemoryAccess *MA : ReadOnlyPair.second)
2589 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2590
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002591 Valid =
2592 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002593
2594 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002595 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002596 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002597
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002598 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002599}
2600
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002601/// @brief Get the smallest loop that contains @p R but is not in @p R.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002602static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002603 // Start with the smallest loop containing the entry and expand that
2604 // loop until it contains all blocks in the region. If there is a loop
2605 // containing all blocks in the region check if it is itself contained
2606 // and if so take the parent loop as it will be the smallest containing
2607 // the region but not contained by it.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002608 Loop *L = LI.getLoopFor(R.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002609 while (L) {
2610 bool AllContained = true;
2611 for (auto *BB : R.blocks())
2612 AllContained &= L->contains(BB);
2613 if (AllContained)
2614 break;
2615 L = L->getParentLoop();
2616 }
2617
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002618 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2619}
2620
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002621static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2622 ScopDetection &SD) {
2623
2624 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2625
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002626 unsigned MinLD = INT_MAX, MaxLD = 0;
2627 for (BasicBlock *BB : R.blocks()) {
2628 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002629 if (!R.contains(L))
2630 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002631 if (BoxedLoops && BoxedLoops->count(L))
2632 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002633 unsigned LD = L->getLoopDepth();
2634 MinLD = std::min(MinLD, LD);
2635 MaxLD = std::max(MaxLD, LD);
2636 }
2637 }
2638
2639 // Handle the case that there is no loop in the SCoP first.
2640 if (MaxLD == 0)
2641 return 1;
2642
2643 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2644 assert(MaxLD >= MinLD &&
2645 "Maximal loop depth was smaller than mininaml loop depth?");
2646 return MaxLD - MinLD + 1;
2647}
2648
Johannes Doerfert478a7de2015-10-02 13:09:31 +00002649Scop::Scop(Region &R, AccFuncMapType &AccFuncMap, ScopDetection &SD,
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002650 ScalarEvolution &ScalarEvolution, DominatorTree &DT, LoopInfo &LI,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002651 isl_ctx *Context, unsigned MaxLoopDepth)
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002652 : LI(LI), DT(DT), SE(&ScalarEvolution), SD(SD), R(R),
2653 AccFuncMap(AccFuncMap), IsOptimized(false),
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002654 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
2655 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Context(nullptr),
2656 Affinator(this), AssumedContext(nullptr), BoundaryContext(nullptr),
2657 Schedule(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002658
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002659void Scop::init(AliasAnalysis &AA, AssumptionCache &AC) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002660 buildContext();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002661 addUserAssumptions(AC);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002662 buildInvariantEquivalenceClasses();
2663
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002664 buildDomains(&R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002665
Michael Krusecac948e2015-10-02 13:53:07 +00002666 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002667 // Exit early in case there are no executable statements left in this scop.
Michael Krusecac948e2015-10-02 13:53:07 +00002668 simplifySCoP(true);
Michael Kruseafe06702015-10-02 16:33:27 +00002669 if (Stmts.empty())
2670 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002671
Michael Krusecac948e2015-10-02 13:53:07 +00002672 // The ScopStmts now have enough information to initialize themselves.
2673 for (ScopStmt &Stmt : Stmts)
2674 Stmt.init();
2675
2676 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002677 Loop *L = getLoopSurroundingRegion(R, LI);
2678 LoopSchedules[L];
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002679 buildSchedule(&R, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002680 Schedule = LoopSchedules[L].first;
Tobias Grosser75805372011-04-29 06:27:02 +00002681
Tobias Grosser8286b832015-11-02 11:29:32 +00002682 if (isl_set_is_empty(AssumedContext))
2683 return;
2684
2685 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002686 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002687 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002688 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002689 buildBoundaryContext();
2690 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002691 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002692
2693 hoistInvariantLoads();
Michael Krusecac948e2015-10-02 13:53:07 +00002694 simplifySCoP(false);
Tobias Grosser75805372011-04-29 06:27:02 +00002695}
2696
2697Scop::~Scop() {
2698 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002699 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002700 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002701 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002702
Johannes Doerfert96425c22015-08-30 21:13:53 +00002703 for (auto It : DomainMap)
2704 isl_set_free(It.second);
2705
Johannes Doerfertb164c792014-09-18 11:17:17 +00002706 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002707 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002708 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002709 isl_pw_multi_aff_free(MMA.first);
2710 isl_pw_multi_aff_free(MMA.second);
2711 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002712 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002713 isl_pw_multi_aff_free(MMA.first);
2714 isl_pw_multi_aff_free(MMA.second);
2715 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002716 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002717
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002718 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002719 isl_set_free(std::get<2>(IAClass));
Tobias Grosser75805372011-04-29 06:27:02 +00002720}
2721
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002722void Scop::updateAccessDimensionality() {
2723 for (auto &Stmt : *this)
2724 for (auto &Access : Stmt)
2725 Access->updateDimensionality();
2726}
2727
Michael Krusecac948e2015-10-02 13:53:07 +00002728void Scop::simplifySCoP(bool RemoveIgnoredStmts) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002729 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2730 ScopStmt &Stmt = *StmtIt;
Michael Krusecac948e2015-10-02 13:53:07 +00002731 RegionNode *RN = Stmt.isRegionStmt()
2732 ? Stmt.getRegion()->getNode()
2733 : getRegion().getBBNode(Stmt.getBasicBlock());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002734
Johannes Doerferteca9e892015-11-03 16:54:49 +00002735 bool RemoveStmt = StmtIt->isEmpty();
2736 if (!RemoveStmt)
2737 RemoveStmt = isl_set_is_empty(DomainMap[getRegionNodeBasicBlock(RN)]);
2738 if (!RemoveStmt)
2739 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002740
Johannes Doerferteca9e892015-11-03 16:54:49 +00002741 // Remove read only statements only after invariant loop hoisting.
2742 if (!RemoveStmt && !RemoveIgnoredStmts) {
2743 bool OnlyRead = true;
2744 for (MemoryAccess *MA : Stmt) {
2745 if (MA->isRead())
2746 continue;
2747
2748 OnlyRead = false;
2749 break;
2750 }
2751
2752 RemoveStmt = OnlyRead;
2753 }
2754
2755 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00002756 // Remove the statement because it is unnecessary.
2757 if (Stmt.isRegionStmt())
2758 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2759 StmtMap.erase(BB);
2760 else
2761 StmtMap.erase(Stmt.getBasicBlock());
2762
2763 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002764 continue;
2765 }
2766
Michael Krusecac948e2015-10-02 13:53:07 +00002767 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002768 }
2769}
2770
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002771const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2772 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2773 if (!LInst)
2774 return nullptr;
2775
2776 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2777 LInst = cast<LoadInst>(Rep);
2778
2779 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2780 for (auto &IAClass : InvariantEquivClasses)
2781 if (PointerSCEV == std::get<0>(IAClass))
2782 return &IAClass;
2783
2784 return nullptr;
2785}
2786
2787void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2788
2789 // Get the context under which the statement is executed.
2790 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2791 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2792 DomainCtx = isl_set_detect_equalities(DomainCtx);
2793 DomainCtx = isl_set_coalesce(DomainCtx);
2794
2795 // Project out all parameters that relate to loads in the statement. Otherwise
2796 // we could have cyclic dependences on the constraints under which the
2797 // hoisted loads are executed and we could not determine an order in which to
2798 // pre-load them. This happens because not only lower bounds are part of the
2799 // domain but also upper bounds.
2800 for (MemoryAccess *MA : InvMAs) {
2801 Instruction *AccInst = MA->getAccessInstruction();
2802 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00002803 SetVector<Value *> Values;
2804 for (const SCEV *Parameter : Parameters) {
2805 Values.clear();
2806 findValues(Parameter, Values);
2807 if (!Values.count(AccInst))
2808 continue;
2809
2810 if (isl_id *ParamId = getIdForParam(Parameter)) {
2811 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2812 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2813 isl_id_free(ParamId);
2814 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002815 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002816 }
2817 }
2818
2819 for (MemoryAccess *MA : InvMAs) {
2820 // Check for another invariant access that accesses the same location as
2821 // MA and if found consolidate them. Otherwise create a new equivalence
2822 // class at the end of InvariantEquivClasses.
2823 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
2824 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2825
2826 bool Consolidated = false;
2827 for (auto &IAClass : InvariantEquivClasses) {
2828 if (PointerSCEV != std::get<0>(IAClass))
2829 continue;
2830
2831 Consolidated = true;
2832
2833 // Add MA to the list of accesses that are in this class.
2834 auto &MAs = std::get<1>(IAClass);
2835 MAs.push_front(MA);
2836
2837 // Unify the execution context of the class and this statement.
2838 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002839 if (IAClassDomainCtx)
2840 IAClassDomainCtx = isl_set_coalesce(
2841 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
2842 else
2843 IAClassDomainCtx = isl_set_copy(DomainCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002844 break;
2845 }
2846
2847 if (Consolidated)
2848 continue;
2849
2850 // If we did not consolidate MA, thus did not find an equivalence class
2851 // for it, we create a new one.
2852 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
2853 isl_set_copy(DomainCtx));
2854 }
2855
2856 isl_set_free(DomainCtx);
2857}
2858
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002859bool Scop::isHoistableAccess(MemoryAccess *Access,
2860 __isl_keep isl_union_map *Writes) {
2861 // TODO: Loads that are not loop carried, hence are in a statement with
2862 // zero iterators, are by construction invariant, though we
2863 // currently "hoist" them anyway. This is necessary because we allow
2864 // them to be treated as parameters (e.g., in conditions) and our code
2865 // generation would otherwise use the old value.
2866
2867 auto &Stmt = *Access->getStatement();
2868 BasicBlock *BB =
2869 Stmt.isBlockStmt() ? Stmt.getBasicBlock() : Stmt.getRegion()->getEntry();
2870
2871 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
2872 return false;
2873
2874 // Skip accesses that have an invariant base pointer which is defined but
2875 // not loaded inside the SCoP. This can happened e.g., if a readnone call
2876 // returns a pointer that is used as a base address. However, as we want
2877 // to hoist indirect pointers, we allow the base pointer to be defined in
2878 // the region if it is also a memory access. Each ScopArrayInfo object
2879 // that has a base pointer origin has a base pointer that is loaded and
2880 // that it is invariant, thus it will be hoisted too. However, if there is
2881 // no base pointer origin we check that the base pointer is defined
2882 // outside the region.
2883 const ScopArrayInfo *SAI = Access->getScopArrayInfo();
2884 while (auto *BasePtrOriginSAI = SAI->getBasePtrOriginSAI())
2885 SAI = BasePtrOriginSAI;
2886
2887 if (auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr()))
2888 if (R.contains(BasePtrInst))
2889 return false;
2890
2891 // Skip accesses in non-affine subregions as they might not be executed
2892 // under the same condition as the entry of the non-affine subregion.
2893 if (BB != Access->getAccessInstruction()->getParent())
2894 return false;
2895
2896 isl_map *AccessRelation = Access->getAccessRelation();
2897
2898 // Skip accesses that have an empty access relation. These can be caused
2899 // by multiple offsets with a type cast in-between that cause the overall
2900 // byte offset to be not divisible by the new types sizes.
2901 if (isl_map_is_empty(AccessRelation)) {
2902 isl_map_free(AccessRelation);
2903 return false;
2904 }
2905
2906 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
2907 Stmt.getNumIterators())) {
2908 isl_map_free(AccessRelation);
2909 return false;
2910 }
2911
2912 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
2913 isl_set *AccessRange = isl_map_range(AccessRelation);
2914
2915 isl_union_map *Written = isl_union_map_intersect_range(
2916 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
2917 bool IsWritten = !isl_union_map_is_empty(Written);
2918 isl_union_map_free(Written);
2919
2920 if (IsWritten)
2921 return false;
2922
2923 return true;
2924}
2925
2926void Scop::verifyInvariantLoads() {
2927 auto &RIL = *SD.getRequiredInvariantLoads(&getRegion());
2928 for (LoadInst *LI : RIL) {
2929 assert(LI && getRegion().contains(LI));
2930 ScopStmt *Stmt = getStmtForBasicBlock(LI->getParent());
Tobias Grosser949e8c62015-12-21 07:10:39 +00002931 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002932 invalidate(INVARIANTLOAD, LI->getDebugLoc());
2933 return;
2934 }
2935 }
2936}
2937
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002938void Scop::hoistInvariantLoads() {
2939 isl_union_map *Writes = getWrites();
2940 for (ScopStmt &Stmt : *this) {
2941
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002942 MemoryAccessList InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002943
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002944 for (MemoryAccess *Access : Stmt)
2945 if (isHoistableAccess(Access, Writes))
2946 InvariantAccesses.push_front(Access);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002947
2948 // We inserted invariant accesses always in the front but need them to be
2949 // sorted in a "natural order". The statements are already sorted in reverse
2950 // post order and that suffices for the accesses too. The reason we require
2951 // an order in the first place is the dependences between invariant loads
2952 // that can be caused by indirect loads.
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002953 InvariantAccesses.reverse();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002954
2955 // Transfer the memory access from the statement to the SCoP.
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002956 Stmt.removeMemoryAccesses(InvariantAccesses);
2957 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002958 }
2959 isl_union_map_free(Writes);
2960
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002961 verifyInvariantLoads();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002962}
2963
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002964const ScopArrayInfo *
2965Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002966 ArrayRef<const SCEV *> Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00002967 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002968 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002969 if (!SAI) {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00002970 auto &DL = getRegion().getEntry()->getModule()->getDataLayout();
2971 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, Kind,
2972 DL, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002973 } else {
Tobias Grosser8286b832015-11-02 11:29:32 +00002974 // In case of mismatching array sizes, we bail out by setting the run-time
2975 // context to false.
2976 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002977 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002978 }
Tobias Grosserab671442015-05-23 05:58:27 +00002979 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002980}
2981
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002982const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00002983 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002984 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002985 assert(SAI && "No ScopArrayInfo available for this base pointer");
2986 return SAI;
2987}
2988
Tobias Grosser74394f02013-01-14 22:40:23 +00002989std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002990std::string Scop::getAssumedContextStr() const {
2991 return stringFromIslObj(AssumedContext);
2992}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002993std::string Scop::getBoundaryContextStr() const {
2994 return stringFromIslObj(BoundaryContext);
2995}
Tobias Grosser75805372011-04-29 06:27:02 +00002996
2997std::string Scop::getNameStr() const {
2998 std::string ExitName, EntryName;
2999 raw_string_ostream ExitStr(ExitName);
3000 raw_string_ostream EntryStr(EntryName);
3001
Tobias Grosserf240b482014-01-09 10:42:15 +00003002 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003003 EntryStr.str();
3004
3005 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003006 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003007 ExitStr.str();
3008 } else
3009 ExitName = "FunctionExit";
3010
3011 return EntryName + "---" + ExitName;
3012}
3013
Tobias Grosser74394f02013-01-14 22:40:23 +00003014__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003015__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003016 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003017}
3018
Tobias Grossere86109f2013-10-29 21:05:49 +00003019__isl_give isl_set *Scop::getAssumedContext() const {
3020 return isl_set_copy(AssumedContext);
3021}
3022
Johannes Doerfert43788c52015-08-20 05:58:56 +00003023__isl_give isl_set *Scop::getRuntimeCheckContext() const {
3024 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003025 RuntimeCheckContext =
3026 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
3027 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00003028 return RuntimeCheckContext;
3029}
3030
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003031bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003032 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003033 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00003034 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
3035 isl_set_free(RuntimeCheckContext);
3036 return IsFeasible;
3037}
3038
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003039static std::string toString(AssumptionKind Kind) {
3040 switch (Kind) {
3041 case ALIASING:
3042 return "No-aliasing";
3043 case INBOUNDS:
3044 return "Inbounds";
3045 case WRAPPING:
3046 return "No-overflows";
Johannes Doerferta4b77c02015-11-12 20:15:32 +00003047 case ALIGNMENT:
3048 return "Alignment";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003049 case ERRORBLOCK:
3050 return "No-error";
3051 case INFINITELOOP:
3052 return "Finite loop";
3053 case INVARIANTLOAD:
3054 return "Invariant load";
3055 case DELINEARIZATION:
3056 return "Delinearization";
Tobias Grosser75dc40c2015-12-20 13:31:48 +00003057 case ERROR_DOMAINCONJUNCTS:
3058 return "Low number of domain conjuncts";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003059 }
3060 llvm_unreachable("Unknown AssumptionKind!");
3061}
3062
3063void Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3064 DebugLoc Loc) {
3065 if (isl_set_is_subset(Context, Set))
3066 return;
3067
3068 if (isl_set_is_subset(AssumedContext, Set))
3069 return;
3070
3071 auto &F = *getRegion().getEntry()->getParent();
3072 std::string Msg = toString(Kind) + " assumption:\t" + stringFromIslObj(Set);
3073 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
3074}
3075
3076void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
3077 DebugLoc Loc) {
3078 trackAssumption(Kind, Set, Loc);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003079 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003080
Johannes Doerfert9d7899e2015-11-11 20:01:31 +00003081 int NSets = isl_set_n_basic_set(AssumedContext);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003082 if (NSets >= MaxDisjunctsAssumed) {
3083 isl_space *Space = isl_set_get_space(AssumedContext);
3084 isl_set_free(AssumedContext);
Tobias Grossere19fca42015-11-11 20:21:39 +00003085 AssumedContext = isl_set_empty(Space);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003086 }
3087
Tobias Grosser7b50bee2014-11-25 10:51:12 +00003088 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003089}
3090
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003091void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
3092 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc);
3093}
3094
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003095__isl_give isl_set *Scop::getBoundaryContext() const {
3096 return isl_set_copy(BoundaryContext);
3097}
3098
Tobias Grosser75805372011-04-29 06:27:02 +00003099void Scop::printContext(raw_ostream &OS) const {
3100 OS << "Context:\n";
3101
3102 if (!Context) {
3103 OS.indent(4) << "n/a\n\n";
3104 return;
3105 }
3106
3107 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003108
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003109 OS.indent(4) << "Assumed Context:\n";
3110 if (!AssumedContext) {
3111 OS.indent(4) << "n/a\n\n";
3112 return;
3113 }
3114
3115 OS.indent(4) << getAssumedContextStr() << "\n";
3116
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003117 OS.indent(4) << "Boundary Context:\n";
3118 if (!BoundaryContext) {
3119 OS.indent(4) << "n/a\n\n";
3120 return;
3121 }
3122
3123 OS.indent(4) << getBoundaryContextStr() << "\n";
3124
Tobias Grosser083d3d32014-06-28 08:59:45 +00003125 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00003126 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00003127 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
3128 }
Tobias Grosser75805372011-04-29 06:27:02 +00003129}
3130
Johannes Doerfertb164c792014-09-18 11:17:17 +00003131void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003132 int noOfGroups = 0;
3133 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003134 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003135 noOfGroups += 1;
3136 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003137 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003138 }
3139
Tobias Grosserbb853c22015-07-25 12:31:03 +00003140 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003141 if (MinMaxAliasGroups.empty()) {
3142 OS.indent(8) << "n/a\n";
3143 return;
3144 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003145
Tobias Grosserbb853c22015-07-25 12:31:03 +00003146 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003147
3148 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003149 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003150 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003151 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003152 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3153 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003154 }
3155 OS << " ]]\n";
3156 }
3157
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003158 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003159 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003160 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003161 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003162 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3163 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003164 }
3165 OS << " ]]\n";
3166 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003167 }
3168}
3169
Tobias Grosser75805372011-04-29 06:27:02 +00003170void Scop::printStatements(raw_ostream &OS) const {
3171 OS << "Statements {\n";
3172
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003173 for (const ScopStmt &Stmt : *this)
3174 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003175
3176 OS.indent(4) << "}\n";
3177}
3178
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003179void Scop::printArrayInfo(raw_ostream &OS) const {
3180 OS << "Arrays {\n";
3181
Tobias Grosserab671442015-05-23 05:58:27 +00003182 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003183 Array.second->print(OS);
3184
3185 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003186
3187 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3188
3189 for (auto &Array : arrays())
3190 Array.second->print(OS, /* SizeAsPwAff */ true);
3191
3192 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003193}
3194
Tobias Grosser75805372011-04-29 06:27:02 +00003195void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00003196 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
3197 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003198 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003199 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003200 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003201 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003202 const auto &MAs = std::get<1>(IAClass);
3203 if (MAs.empty()) {
3204 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003205 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003206 MAs.front()->print(OS);
3207 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003208 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003209 }
3210 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003211 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003212 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003213 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003214 printStatements(OS.indent(4));
3215}
3216
3217void Scop::dump() const { print(dbgs()); }
3218
Tobias Grosser9a38ab82011-11-08 15:41:03 +00003219isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00003220
Johannes Doerfertcef616f2015-09-15 22:49:04 +00003221__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
3222 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003223}
3224
Tobias Grosser808cd692015-07-14 09:33:13 +00003225__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003226 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003227
Tobias Grosser808cd692015-07-14 09:33:13 +00003228 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003229 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003230
3231 return Domain;
3232}
3233
Tobias Grossere5a35142015-11-12 14:07:09 +00003234__isl_give isl_union_map *
3235Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3236 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003237
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003238 for (ScopStmt &Stmt : *this) {
3239 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003240 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003241 continue;
3242
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003243 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003244 isl_map *AccessDomain = MA->getAccessRelation();
3245 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003246 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003247 }
3248 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003249 return isl_union_map_coalesce(Accesses);
3250}
3251
3252__isl_give isl_union_map *Scop::getMustWrites() {
3253 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003254}
3255
3256__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003257 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003258}
3259
Tobias Grosser37eb4222014-02-20 21:43:54 +00003260__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003261 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003262}
3263
3264__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003265 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003266}
3267
Tobias Grosser2ac23382015-11-12 14:07:13 +00003268__isl_give isl_union_map *Scop::getAccesses() {
3269 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3270}
3271
Tobias Grosser808cd692015-07-14 09:33:13 +00003272__isl_give isl_union_map *Scop::getSchedule() const {
3273 auto Tree = getScheduleTree();
3274 auto S = isl_schedule_get_map(Tree);
3275 isl_schedule_free(Tree);
3276 return S;
3277}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003278
Tobias Grosser808cd692015-07-14 09:33:13 +00003279__isl_give isl_schedule *Scop::getScheduleTree() const {
3280 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3281 getDomains());
3282}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003283
Tobias Grosser808cd692015-07-14 09:33:13 +00003284void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3285 auto *S = isl_schedule_from_domain(getDomains());
3286 S = isl_schedule_insert_partial_schedule(
3287 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3288 isl_schedule_free(Schedule);
3289 Schedule = S;
3290}
3291
3292void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3293 isl_schedule_free(Schedule);
3294 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003295}
3296
3297bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3298 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003299 for (ScopStmt &Stmt : *this) {
3300 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003301 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3302 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3303
3304 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3305 isl_union_set_free(StmtDomain);
3306 isl_union_set_free(NewStmtDomain);
3307 continue;
3308 }
3309
3310 Changed = true;
3311
3312 isl_union_set_free(StmtDomain);
3313 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3314
3315 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003316 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003317 isl_union_set_free(NewStmtDomain);
3318 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003319 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003320 }
3321 isl_union_set_free(Domain);
3322 return Changed;
3323}
3324
Tobias Grosser75805372011-04-29 06:27:02 +00003325ScalarEvolution *Scop::getSE() const { return SE; }
3326
Johannes Doerfertf5673802015-10-01 23:48:18 +00003327bool Scop::isIgnored(RegionNode *RN) {
3328 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Michael Krusea902ba62015-12-13 19:21:45 +00003329 ScopStmt *Stmt = getStmtForRegionNode(RN);
3330
3331 // If there is no stmt, then it already has been removed.
3332 if (!Stmt)
3333 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00003334
Johannes Doerfertf5673802015-10-01 23:48:18 +00003335 // Check if there are accesses contained.
Michael Krusea902ba62015-12-13 19:21:45 +00003336 if (Stmt->isEmpty())
Johannes Doerfertf5673802015-10-01 23:48:18 +00003337 return true;
3338
3339 // Check for reachability via non-error blocks.
3340 if (!DomainMap.count(BB))
3341 return true;
3342
3343 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003344 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003345 return true;
3346
3347 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003348}
3349
Tobias Grosser808cd692015-07-14 09:33:13 +00003350struct MapToDimensionDataTy {
3351 int N;
3352 isl_union_pw_multi_aff *Res;
3353};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003354
Tobias Grosser808cd692015-07-14 09:33:13 +00003355// @brief Create a function that maps the elements of 'Set' to its N-th
3356// dimension.
3357//
3358// The result is added to 'User->Res'.
3359//
3360// @param Set The input set.
3361// @param N The dimension to map to.
3362//
3363// @returns Zero if no error occurred, non-zero otherwise.
3364static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3365 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3366 int Dim;
3367 isl_space *Space;
3368 isl_pw_multi_aff *PMA;
3369
3370 Dim = isl_set_dim(Set, isl_dim_set);
3371 Space = isl_set_get_space(Set);
3372 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3373 Dim - Data->N);
3374 if (Data->N > 1)
3375 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3376 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3377
3378 isl_set_free(Set);
3379
3380 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003381}
3382
Tobias Grosser808cd692015-07-14 09:33:13 +00003383// @brief Create a function that maps the elements of Domain to their Nth
3384// dimension.
3385//
3386// @param Domain The set of elements to map.
3387// @param N The dimension to map to.
3388static __isl_give isl_multi_union_pw_aff *
3389mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003390 if (N <= 0 || isl_union_set_is_empty(Domain)) {
3391 isl_union_set_free(Domain);
3392 return nullptr;
3393 }
3394
Tobias Grosser808cd692015-07-14 09:33:13 +00003395 struct MapToDimensionDataTy Data;
3396 isl_space *Space;
3397
3398 Space = isl_union_set_get_space(Domain);
3399 Data.N = N;
3400 Data.Res = isl_union_pw_multi_aff_empty(Space);
3401 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
3402 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
3403
3404 isl_union_set_free(Domain);
3405 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3406}
3407
Tobias Grosser316b5b22015-11-11 19:28:14 +00003408void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003409 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003410 Stmts.emplace_back(*this, *BB);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003411 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003412 StmtMap[BB] = Stmt;
3413 } else {
3414 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003415 Stmts.emplace_back(*this, *R);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003416 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003417 for (BasicBlock *BB : R->blocks())
3418 StmtMap[BB] = Stmt;
3419 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003420}
3421
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003422void Scop::buildSchedule(
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003423 Region *R,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003424 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00003425
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003426 if (SD.isNonAffineSubRegion(R, &getRegion())) {
Johannes Doerfertc6987c12015-09-26 13:41:43 +00003427 Loop *L = getLoopSurroundingRegion(*R, LI);
3428 auto &LSchedulePair = LoopSchedules[L];
Michael Krusecac948e2015-10-02 13:53:07 +00003429 ScopStmt *Stmt = getStmtForBasicBlock(R->getEntry());
Michael Kruseafe06702015-10-02 16:33:27 +00003430 isl_set *Domain = Stmt->getDomain();
Michael Krusecac948e2015-10-02 13:53:07 +00003431 auto *UDomain = isl_union_set_from_set(Domain);
3432 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003433 LSchedulePair.first = StmtSchedule;
3434 return;
3435 }
3436
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003437 ReversePostOrderTraversal<Region *> RTraversal(R);
3438 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00003439
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003440 if (RN->isSubRegion()) {
3441 Region *SubRegion = RN->getNodeAs<Region>();
3442 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003443 buildSchedule(SubRegion, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003444 continue;
3445 }
Tobias Grosser75805372011-04-29 06:27:02 +00003446 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003447
3448 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert30c22652015-10-18 21:17:11 +00003449 if (!getRegion().contains(L))
3450 L = getLoopSurroundingRegion(getRegion(), LI);
3451
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003452 int LD = getRelativeLoopDepth(L);
3453 auto &LSchedulePair = LoopSchedules[L];
3454 LSchedulePair.second += getNumBlocksInRegionNode(RN);
3455
Michael Krusecac948e2015-10-02 13:53:07 +00003456 BasicBlock *BB = getRegionNodeBasicBlock(RN);
3457 ScopStmt *Stmt = getStmtForBasicBlock(BB);
3458 if (Stmt) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003459 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3460 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
3461 LSchedulePair.first =
3462 combineInSequence(LSchedulePair.first, StmtSchedule);
3463 }
3464
Johannes Doerfert30e23072015-12-20 17:12:22 +00003465 isl_schedule *LSchedule = LSchedulePair.first;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003466 unsigned NumVisited = LSchedulePair.second;
3467 while (L && NumVisited == L->getNumBlocks()) {
Johannes Doerfert30e23072015-12-20 17:12:22 +00003468 auto *LDomain = isl_schedule_get_domain(LSchedule);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003469 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
Johannes Doerfert30e23072015-12-20 17:12:22 +00003470 LSchedule = isl_schedule_insert_partial_schedule(LSchedule, MUPA);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003471
3472 auto *PL = L->getParentLoop();
Johannes Doerfertdca28372015-11-03 00:28:07 +00003473
3474 // Either we have a proper loop and we also build a schedule for the
3475 // parent loop or we have a infinite loop that does not have a proper
3476 // parent loop. In the former case this conditional will be skipped, in
3477 // the latter case however we will break here as we do not build a domain
3478 // nor a schedule for a infinite loop.
Johannes Doerfert30e23072015-12-20 17:12:22 +00003479 assert(LoopSchedules.count(PL) || LSchedule == nullptr);
Johannes Doerfertdca28372015-11-03 00:28:07 +00003480 if (!LoopSchedules.count(PL))
3481 break;
3482
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003483 auto &PSchedulePair = LoopSchedules[PL];
Johannes Doerfert30e23072015-12-20 17:12:22 +00003484 PSchedulePair.first = combineInSequence(PSchedulePair.first, LSchedule);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003485 PSchedulePair.second += NumVisited;
3486
3487 L = PL;
Johannes Doerfert30e23072015-12-20 17:12:22 +00003488 LD--;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003489 NumVisited = PSchedulePair.second;
Johannes Doerfert30e23072015-12-20 17:12:22 +00003490 LSchedule = PSchedulePair.first;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003491 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003492 }
Tobias Grosser75805372011-04-29 06:27:02 +00003493}
3494
Johannes Doerfert7c494212014-10-31 23:13:39 +00003495ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003496 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003497 if (StmtMapIt == StmtMap.end())
3498 return nullptr;
3499 return StmtMapIt->second;
3500}
3501
Michael Krusea902ba62015-12-13 19:21:45 +00003502ScopStmt *Scop::getStmtForRegionNode(RegionNode *RN) const {
3503 return getStmtForBasicBlock(getRegionNodeBasicBlock(RN));
3504}
3505
Johannes Doerfert96425c22015-08-30 21:13:53 +00003506int Scop::getRelativeLoopDepth(const Loop *L) const {
3507 Loop *OuterLoop =
3508 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3509 if (!OuterLoop)
3510 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003511 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3512}
3513
Michael Krused868b5d2015-09-10 15:25:24 +00003514void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003515 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003516
3517 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3518 // true, are not modeled as ordinary PHI nodes as they are not part of the
3519 // region. However, we model the operands in the predecessor blocks that are
3520 // part of the region as regular scalar accesses.
3521
3522 // If we can synthesize a PHI we can skip it, however only if it is in
3523 // the region. If it is not it can only be in the exit block of the region.
3524 // In this case we model the operands but not the PHI itself.
3525 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3526 return;
3527
3528 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3529 // detection. Hence, the PHI is a load of a new memory location in which the
3530 // incoming value was written at the end of the incoming basic block.
3531 bool OnlyNonAffineSubRegionOperands = true;
3532 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3533 Value *Op = PHI->getIncomingValue(u);
3534 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3535
3536 // Do not build scalar dependences inside a non-affine subregion.
3537 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3538 continue;
3539
3540 OnlyNonAffineSubRegionOperands = false;
3541
3542 if (!R.contains(OpBB))
3543 continue;
3544
3545 Instruction *OpI = dyn_cast<Instruction>(Op);
3546 if (OpI) {
3547 BasicBlock *OpIBB = OpI->getParent();
3548 // As we pretend there is a use (or more precise a write) of OpI in OpBB
3549 // we have to insert a scalar dependence from the definition of OpI to
3550 // OpBB if the definition is not in OpBB.
Michael Kruse668af712015-10-15 14:45:48 +00003551 if (scop->getStmtForBasicBlock(OpIBB) !=
3552 scop->getStmtForBasicBlock(OpBB)) {
Michael Kruse34e11222015-12-13 22:47:43 +00003553 addValueReadAccess(OpI, PHI, OpBB);
3554 addValueWriteAccess(OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003555 }
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003556 } else if (ModelReadOnlyScalars && !isa<Constant>(Op)) {
Michael Kruse34e11222015-12-13 22:47:43 +00003557 addValueReadAccess(Op, PHI, OpBB);
Michael Kruse7bf39442015-09-10 12:46:52 +00003558 }
3559
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003560 addPHIWriteAccess(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003561 }
3562
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003563 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3564 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003565 }
3566}
3567
Michael Krused868b5d2015-09-10 15:25:24 +00003568bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
3569 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003570 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
3571 if (isIgnoredIntrinsic(Inst))
3572 return false;
3573
3574 bool AnyCrossStmtUse = false;
3575 BasicBlock *ParentBB = Inst->getParent();
3576
3577 for (User *U : Inst->users()) {
3578 Instruction *UI = dyn_cast<Instruction>(U);
3579
3580 // Ignore the strange user
3581 if (UI == 0)
3582 continue;
3583
3584 BasicBlock *UseParent = UI->getParent();
3585
Tobias Grosserbaffa092015-10-24 20:55:27 +00003586 // Ignore basic block local uses. A value that is defined in a scop, but
3587 // used in a PHI node in the same basic block does not count as basic block
3588 // local, as for such cases a control flow edge is passed between definition
3589 // and use.
3590 if (UseParent == ParentBB && !isa<PHINode>(UI))
Michael Kruse7bf39442015-09-10 12:46:52 +00003591 continue;
3592
Michael Krusef714d472015-11-05 13:18:43 +00003593 // Uses by PHI nodes in the entry node count as external uses in case the
3594 // use is through an incoming block that is itself not contained in the
3595 // region.
3596 if (R->getEntry() == UseParent) {
3597 if (auto *PHI = dyn_cast<PHINode>(UI)) {
3598 bool ExternalUse = false;
3599 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
3600 if (PHI->getIncomingValue(i) == Inst &&
3601 !R->contains(PHI->getIncomingBlock(i))) {
3602 ExternalUse = true;
3603 break;
3604 }
3605 }
3606
3607 if (ExternalUse) {
3608 AnyCrossStmtUse = true;
3609 continue;
3610 }
3611 }
3612 }
3613
Michael Kruse7bf39442015-09-10 12:46:52 +00003614 // Do not build scalar dependences inside a non-affine subregion.
3615 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
3616 continue;
3617
Michael Kruse01cb3792015-10-17 21:07:08 +00003618 // Check for PHI nodes in the region exit and skip them, if they will be
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003619 // modeled as PHI nodes.
Michael Kruse01cb3792015-10-17 21:07:08 +00003620 //
3621 // PHI nodes in the region exit that have more than two incoming edges need
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003622 // to be modeled as PHI-Nodes to correctly model the fact that depending on
3623 // the control flow a different value will be assigned to the PHI node. In
3624 // case this is the case, there is no need to create an additional normal
3625 // scalar dependence. Hence, bail out before we register an "out-of-region"
3626 // use for this definition.
Michael Kruse01cb3792015-10-17 21:07:08 +00003627 if (isa<PHINode>(UI) && UI->getParent() == R->getExit() &&
3628 !R->getExitingBlock())
3629 continue;
3630
Michael Kruse7bf39442015-09-10 12:46:52 +00003631 // Check whether or not the use is in the SCoP.
Tobias Grosserc73d8b02015-10-23 22:36:22 +00003632 if (!R->contains(UseParent)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003633 AnyCrossStmtUse = true;
3634 continue;
3635 }
3636
3637 // If the instruction can be synthesized and the user is in the region
3638 // we do not need to add scalar dependences.
3639 if (canSynthesizeInst)
3640 continue;
3641
3642 // No need to translate these scalar dependences into polyhedral form,
3643 // because synthesizable scalars can be generated by the code generator.
3644 if (canSynthesize(UI, LI, SE, R))
3645 continue;
3646
3647 // Skip PHI nodes in the region as they handle their operands on their own.
3648 if (isa<PHINode>(UI))
3649 continue;
3650
3651 // Now U is used in another statement.
3652 AnyCrossStmtUse = true;
3653
3654 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00003655 // Use the def instruction as base address of the MemoryAccess, so that it
3656 // will become the name of the scalar access in the polyhedral form.
Michael Kruse34e11222015-12-13 22:47:43 +00003657 addValueReadAccess(Inst, UI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003658 }
3659
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003660 if (ModelReadOnlyScalars && !isa<PHINode>(Inst)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003661 for (Value *Op : Inst->operands()) {
3662 if (canSynthesize(Op, LI, SE, R))
3663 continue;
3664
3665 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
3666 if (R->contains(OpInst))
3667 continue;
3668
3669 if (isa<Constant>(Op))
3670 continue;
3671
Michael Kruse34e11222015-12-13 22:47:43 +00003672 addValueReadAccess(Op, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003673 }
3674 }
3675
3676 return AnyCrossStmtUse;
3677}
3678
3679extern MapInsnToMemAcc InsnToMemAcc;
3680
Michael Krusee2bccbb2015-09-18 19:59:43 +00003681void ScopInfo::buildMemoryAccess(
3682 Instruction *Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003683 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3684 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003685 unsigned Size;
3686 Type *SizeType;
3687 Value *Val;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003688 enum MemoryAccess::AccessType Type;
Michael Kruse7bf39442015-09-10 12:46:52 +00003689
3690 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
3691 SizeType = Load->getType();
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003692 Size = TD->getTypeAllocSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003693 Type = MemoryAccess::READ;
Michael Kruse7bf39442015-09-10 12:46:52 +00003694 Val = Load;
3695 } else {
3696 StoreInst *Store = cast<StoreInst>(Inst);
3697 SizeType = Store->getValueOperand()->getType();
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003698 Size = TD->getTypeAllocSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003699 Type = MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003700 Val = Store->getValueOperand();
3701 }
3702
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003703 auto Address = getPointerOperand(*Inst);
3704
3705 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003706 const SCEVUnknown *BasePointer =
3707 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3708
3709 assert(BasePointer && "Could not find base pointer");
3710 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
3711
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003712 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3713 auto NewAddress = Address;
3714 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3715 auto Src = BitCast->getOperand(0);
3716 auto SrcTy = Src->getType();
3717 auto DstTy = BitCast->getType();
3718 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3719 NewAddress = Src;
3720 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003721
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003722 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3723 std::vector<const SCEV *> Subscripts;
3724 std::vector<int> Sizes;
3725 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3726 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003727
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003728 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003729
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003730 bool AllAffineSubcripts = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003731 for (auto Subscript : Subscripts) {
3732 InvariantLoadsSetTy AccessILS;
3733 AllAffineSubcripts =
3734 isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS);
3735
3736 for (LoadInst *LInst : AccessILS)
3737 if (!ScopRIL.count(LInst))
3738 AllAffineSubcripts = false;
3739
3740 if (!AllAffineSubcripts)
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003741 break;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003742 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003743
3744 if (AllAffineSubcripts && Sizes.size() > 0) {
3745 for (auto V : Sizes)
3746 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3747 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003748 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003749 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003750
Tobias Grossera535dff2015-12-13 19:59:01 +00003751 addArrayAccess(Inst, Type, BasePointer->getValue(), Size, true,
3752 Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00003753 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003754 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003755 }
3756 }
3757
Michael Kruse7bf39442015-09-10 12:46:52 +00003758 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003759 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003760 addArrayAccess(Inst, Type, BasePointer->getValue(), Size, true,
3761 AccItr->second.DelinearizedSubscripts,
3762 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003763 return;
3764 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003765
3766 // Check if the access depends on a loop contained in a non-affine subregion.
3767 bool isVariantInNonAffineLoop = false;
3768 if (BoxedLoops) {
3769 SetVector<const Loop *> Loops;
3770 findLoops(AccessFunction, Loops);
3771 for (const Loop *L : Loops)
3772 if (BoxedLoops->count(L))
3773 isVariantInNonAffineLoop = true;
3774 }
3775
Johannes Doerfert09e36972015-10-07 20:17:36 +00003776 InvariantLoadsSetTy AccessILS;
3777 bool IsAffine =
3778 !isVariantInNonAffineLoop &&
3779 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3780
3781 for (LoadInst *LInst : AccessILS)
3782 if (!ScopRIL.count(LInst))
3783 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003784
Michael Krusecaac2b62015-09-26 15:51:44 +00003785 // FIXME: Size of the number of bytes of an array element, not the number of
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003786 // elements as probably intended here.
Tobias Grossera43b6e92015-09-27 17:54:50 +00003787 const SCEV *SizeSCEV =
3788 SE->getConstant(TD->getIntPtrType(Inst->getContext()), Size);
Michael Kruse7bf39442015-09-10 12:46:52 +00003789
Michael Krusee2bccbb2015-09-18 19:59:43 +00003790 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3791 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003792
Tobias Grossera535dff2015-12-13 19:59:01 +00003793 addArrayAccess(Inst, Type, BasePointer->getValue(), Size, IsAffine,
3794 ArrayRef<const SCEV *>(AccessFunction),
3795 ArrayRef<const SCEV *>(SizeSCEV), Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003796}
3797
Michael Krused868b5d2015-09-10 15:25:24 +00003798void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003799
3800 if (SD->isNonAffineSubRegion(&SR, &R)) {
3801 for (BasicBlock *BB : SR.blocks())
3802 buildAccessFunctions(R, *BB, &SR);
3803 return;
3804 }
3805
3806 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3807 if (I->isSubRegion())
3808 buildAccessFunctions(R, *I->getNodeAs<Region>());
3809 else
3810 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
3811}
3812
Michael Krusecac948e2015-10-02 13:53:07 +00003813void ScopInfo::buildStmts(Region &SR) {
3814 Region *R = getRegion();
3815
3816 if (SD->isNonAffineSubRegion(&SR, R)) {
3817 scop->addScopStmt(nullptr, &SR);
3818 return;
3819 }
3820
3821 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3822 if (I->isSubRegion())
3823 buildStmts(*I->getNodeAs<Region>());
3824 else
3825 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
3826}
3827
Michael Krused868b5d2015-09-10 15:25:24 +00003828void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
3829 Region *NonAffineSubRegion,
3830 bool IsExitBlock) {
Tobias Grosser910cf262015-11-11 20:15:49 +00003831 // We do not build access functions for error blocks, as they may contain
3832 // instructions we can not model.
3833 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3834 if (isErrorBlock(BB, R, *LI, DT) && !IsExitBlock)
3835 return;
3836
Michael Kruse7bf39442015-09-10 12:46:52 +00003837 Loop *L = LI->getLoopFor(&BB);
3838
3839 // The set of loops contained in non-affine subregions that are part of R.
3840 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3841
Johannes Doerfert09e36972015-10-07 20:17:36 +00003842 // The set of loads that are required to be invariant.
3843 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
3844
Michael Kruse7bf39442015-09-10 12:46:52 +00003845 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00003846 Instruction *Inst = &*I;
Michael Kruse7bf39442015-09-10 12:46:52 +00003847
3848 PHINode *PHI = dyn_cast<PHINode>(Inst);
3849 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003850 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003851
3852 // For the exit block we stop modeling after the last PHI node.
3853 if (!PHI && IsExitBlock)
3854 break;
3855
Johannes Doerfert09e36972015-10-07 20:17:36 +00003856 // TODO: At this point we only know that elements of ScopRIL have to be
3857 // invariant and will be hoisted for the SCoP to be processed. Though,
3858 // there might be other invariant accesses that will be hoisted and
3859 // that would allow to make a non-affine access affine.
Michael Kruse7bf39442015-09-10 12:46:52 +00003860 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
Johannes Doerfert09e36972015-10-07 20:17:36 +00003861 buildMemoryAccess(Inst, L, &R, BoxedLoops, ScopRIL);
Michael Kruse7bf39442015-09-10 12:46:52 +00003862
3863 if (isIgnoredIntrinsic(Inst))
3864 continue;
3865
Johannes Doerfert09e36972015-10-07 20:17:36 +00003866 // Do not build scalar dependences for required invariant loads as we will
3867 // hoist them later on anyway or drop the SCoP if we cannot.
3868 if (ScopRIL.count(dyn_cast<LoadInst>(Inst)))
3869 continue;
3870
Michael Kruse7bf39442015-09-10 12:46:52 +00003871 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00003872 if (!isa<StoreInst>(Inst))
Michael Kruse34e11222015-12-13 22:47:43 +00003873 addValueWriteAccess(Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003874 }
3875 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003876}
Michael Kruse7bf39442015-09-10 12:46:52 +00003877
Michael Kruse2d0ece92015-09-24 11:41:21 +00003878void ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3879 MemoryAccess::AccessType Type,
3880 Value *BaseAddress, unsigned ElemBytes,
3881 bool Affine, Value *AccessValue,
3882 ArrayRef<const SCEV *> Subscripts,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003883 ArrayRef<const SCEV *> Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00003884 ScopArrayInfo::MemoryKind Kind) {
Michael Krusecac948e2015-10-02 13:53:07 +00003885 ScopStmt *Stmt = scop->getStmtForBasicBlock(BB);
3886
3887 // Do not create a memory access for anything not in the SCoP. It would be
3888 // ignored anyway.
3889 if (!Stmt)
3890 return;
3891
Michael Krusee2bccbb2015-09-18 19:59:43 +00003892 AccFuncSetType &AccList = AccFuncMap[BB];
Michael Krusee2bccbb2015-09-18 19:59:43 +00003893 Value *BaseAddr = BaseAddress;
3894 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3895
Tobias Grosserf4f68702015-12-14 15:05:37 +00003896 bool isKnownMustAccess = false;
3897
3898 // Accesses in single-basic block statements are always excuted.
3899 if (Stmt->isBlockStmt())
3900 isKnownMustAccess = true;
3901
3902 if (Stmt->isRegionStmt()) {
3903 // Accesses that dominate the exit block of a non-affine region are always
3904 // executed. In non-affine regions there may exist MK_Values that do not
3905 // dominate the exit. MK_Values will always dominate the exit and MK_PHIs
3906 // only if there is at most one PHI_WRITE in the non-affine region.
3907 if (DT->dominates(BB, Stmt->getRegion()->getExit()))
3908 isKnownMustAccess = true;
3909 }
3910
3911 if (!isKnownMustAccess && Type == MemoryAccess::MUST_WRITE)
Michael Krusecac948e2015-10-02 13:53:07 +00003912 Type = MemoryAccess::MAY_WRITE;
3913
Tobias Grosserf1bfd752015-11-05 20:15:37 +00003914 AccList.emplace_back(Stmt, Inst, Type, BaseAddress, ElemBytes, Affine,
Tobias Grossera535dff2015-12-13 19:59:01 +00003915 Subscripts, Sizes, AccessValue, Kind, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00003916 Stmt->addAccess(&AccList.back());
Michael Kruse7bf39442015-09-10 12:46:52 +00003917}
3918
Tobias Grossera535dff2015-12-13 19:59:01 +00003919void ScopInfo::addArrayAccess(Instruction *MemAccInst,
3920 MemoryAccess::AccessType Type, Value *BaseAddress,
3921 unsigned ElemBytes, bool IsAffine,
3922 ArrayRef<const SCEV *> Subscripts,
3923 ArrayRef<const SCEV *> Sizes,
3924 Value *AccessValue) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003925 assert(isa<LoadInst>(MemAccInst) || isa<StoreInst>(MemAccInst));
3926 assert(isa<LoadInst>(MemAccInst) == (Type == MemoryAccess::READ));
3927 addMemoryAccess(MemAccInst->getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003928 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00003929 ScopArrayInfo::MK_Array);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003930}
Michael Kruse34e11222015-12-13 22:47:43 +00003931void ScopInfo::addValueWriteAccess(Instruction *Value) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003932 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
3933 true, Value, ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00003934 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003935}
Michael Kruse34e11222015-12-13 22:47:43 +00003936void ScopInfo::addValueReadAccess(Value *Value, Instruction *User) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003937 assert(!isa<PHINode>(User));
3938 addMemoryAccess(User->getParent(), User, MemoryAccess::READ, Value, 1, true,
3939 Value, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00003940 ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003941}
Michael Kruse34e11222015-12-13 22:47:43 +00003942void ScopInfo::addValueReadAccess(Value *Value, PHINode *User,
3943 BasicBlock *UserBB) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003944 addMemoryAccess(UserBB, User, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003945 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00003946 ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003947}
3948void ScopInfo::addPHIWriteAccess(PHINode *PHI, BasicBlock *IncomingBlock,
3949 Value *IncomingValue, bool IsExitBlock) {
3950 addMemoryAccess(IncomingBlock, IncomingBlock->getTerminator(),
3951 MemoryAccess::MUST_WRITE, PHI, 1, true, IncomingValue,
3952 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00003953 IsExitBlock ? ScopArrayInfo::MK_ExitPHI
3954 : ScopArrayInfo::MK_PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003955}
3956void ScopInfo::addPHIReadAccess(PHINode *PHI) {
3957 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003958 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00003959 ScopArrayInfo::MK_PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003960}
3961
Michael Krusedaf66942015-12-13 22:10:37 +00003962void ScopInfo::buildScop(Region &R, AssumptionCache &AC) {
Michael Kruse9d080092015-09-11 21:41:48 +00003963 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Michael Krusedaf66942015-12-13 22:10:37 +00003964 scop = new Scop(R, AccFuncMap, *SD, *SE, *DT, *LI, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00003965
Michael Krusecac948e2015-10-02 13:53:07 +00003966 buildStmts(R);
Michael Kruse7bf39442015-09-10 12:46:52 +00003967 buildAccessFunctions(R, R);
3968
3969 // In case the region does not have an exiting block we will later (during
3970 // code generation) split the exit block. This will move potential PHI nodes
3971 // from the current exit block into the new region exiting block. Hence, PHI
3972 // nodes that are at this point not part of the region will be.
3973 // To handle these PHI nodes later we will now model their operands as scalar
3974 // accesses. Note that we do not model anything in the exit block if we have
3975 // an exiting block in the region, as there will not be any splitting later.
3976 if (!R.getExitingBlock())
3977 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
3978
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003979 scop->init(*AA, AC);
Michael Kruse7bf39442015-09-10 12:46:52 +00003980}
3981
Michael Krused868b5d2015-09-10 15:25:24 +00003982void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00003983 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00003984 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00003985 return;
3986 }
3987
Michael Kruse9d080092015-09-11 21:41:48 +00003988 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00003989}
3990
Michael Krused868b5d2015-09-10 15:25:24 +00003991void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00003992 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00003993 if (scop) {
3994 delete scop;
3995 scop = 0;
3996 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003997}
3998
3999//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00004000ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00004001 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00004002 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00004003}
4004
4005ScopInfo::~ScopInfo() {
4006 clear();
4007 isl_ctx_free(ctx);
4008}
4009
Tobias Grosser75805372011-04-29 06:27:02 +00004010void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00004011 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00004012 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00004013 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00004014 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4015 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004016 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004017 AU.addRequired<AssumptionCacheTracker>();
Tobias Grosser75805372011-04-29 06:27:02 +00004018 AU.setPreservesAll();
4019}
4020
4021bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00004022 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00004023
Michael Krused868b5d2015-09-10 15:25:24 +00004024 if (!SD->isMaxRegionInScop(*R))
4025 return false;
4026
4027 Function *F = R->getEntry()->getParent();
4028 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4029 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4030 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
4031 TD = &F->getParent()->getDataLayout();
Michael Krusedaf66942015-12-13 22:10:37 +00004032 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004033 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krused868b5d2015-09-10 15:25:24 +00004034
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004035 DebugLoc Beg, End;
4036 getDebugLocations(R, Beg, End);
4037 std::string Msg = "SCoP begins here.";
4038 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg);
4039
Michael Krusedaf66942015-12-13 22:10:37 +00004040 buildScop(*R, AC);
Tobias Grosser75805372011-04-29 06:27:02 +00004041
Tobias Grosserd6a50b32015-05-30 06:26:21 +00004042 DEBUG(scop->print(dbgs()));
4043
Michael Kruseafe06702015-10-02 16:33:27 +00004044 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004045 Msg = "SCoP ends here but was dismissed.";
Johannes Doerfert43788c52015-08-20 05:58:56 +00004046 delete scop;
4047 scop = nullptr;
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004048 } else {
4049 Msg = "SCoP ends here.";
4050 ++ScopFound;
4051 if (scop->getMaxLoopDepth() > 0)
4052 ++RichScopFound;
Johannes Doerfert43788c52015-08-20 05:58:56 +00004053 }
4054
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004055 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg);
4056
Tobias Grosser75805372011-04-29 06:27:02 +00004057 return false;
4058}
4059
4060char ScopInfo::ID = 0;
4061
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004062Pass *polly::createScopInfoPass() { return new ScopInfo(); }
4063
Tobias Grosser73600b82011-10-08 00:30:40 +00004064INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
4065 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004066 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004067INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004068INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004069INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004070INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004071INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004072INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004073INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00004074INITIALIZE_PASS_END(ScopInfo, "polly-scops",
4075 "Polly - Create polyhedral description of Scops", false,
4076 false)