blob: d329cad807b9741fc58692631b8ef25dea1bcb9b [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
Michael Kruse58fa3bb2015-12-22 23:25:11 +0000907 if (Access->isArrayKind()) {
908 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
909 MAL.emplace_front(Access);
910 }
911
912 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +0000913}
914
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000915void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000916 for (MemoryAccess *MA : *this)
917 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000918
919 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000920}
921
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000922/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
923static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
924 void *User) {
925 isl_set **BoundedParts = static_cast<isl_set **>(User);
926 if (isl_basic_set_is_bounded(BSet))
927 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
928 else
929 isl_basic_set_free(BSet);
930 return isl_stat_ok;
931}
932
933/// @brief Return the bounded parts of @p S.
934static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
935 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
936 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
937 isl_set_free(S);
938 return BoundedParts;
939}
940
941/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
942///
943/// @returns A separation of @p S into first an unbounded then a bounded subset,
944/// both with regards to the dimension @p Dim.
945static std::pair<__isl_give isl_set *, __isl_give isl_set *>
946partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
947
948 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000949 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000950
951 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000952 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000953
954 // Remove dimensions that are greater than Dim as they are not interesting.
955 assert(NumDimsS >= Dim + 1);
956 OnlyDimS =
957 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
958
959 // Create artificial parametric upper bounds for dimensions smaller than Dim
960 // as we are not interested in them.
961 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
962 for (unsigned u = 0; u < Dim; u++) {
963 isl_constraint *C = isl_inequality_alloc(
964 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
965 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
966 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
967 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
968 }
969
970 // Collect all bounded parts of OnlyDimS.
971 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
972
973 // Create the dimensions greater than Dim again.
974 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
975 NumDimsS - Dim - 1);
976
977 // Remove the artificial upper bound parameters again.
978 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
979
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000980 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000981 return std::make_pair(UnboundedParts, BoundedParts);
982}
983
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000984/// @brief Set the dimension Ids from @p From in @p To.
985static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
986 __isl_take isl_set *To) {
987 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
988 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
989 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
990 }
991 return To;
992}
993
994/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000995static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000996 __isl_take isl_pw_aff *L,
997 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +0000998 switch (Pred) {
999 case ICmpInst::ICMP_EQ:
1000 return isl_pw_aff_eq_set(L, R);
1001 case ICmpInst::ICMP_NE:
1002 return isl_pw_aff_ne_set(L, R);
1003 case ICmpInst::ICMP_SLT:
1004 return isl_pw_aff_lt_set(L, R);
1005 case ICmpInst::ICMP_SLE:
1006 return isl_pw_aff_le_set(L, R);
1007 case ICmpInst::ICMP_SGT:
1008 return isl_pw_aff_gt_set(L, R);
1009 case ICmpInst::ICMP_SGE:
1010 return isl_pw_aff_ge_set(L, R);
1011 case ICmpInst::ICMP_ULT:
1012 return isl_pw_aff_lt_set(L, R);
1013 case ICmpInst::ICMP_UGT:
1014 return isl_pw_aff_gt_set(L, R);
1015 case ICmpInst::ICMP_ULE:
1016 return isl_pw_aff_le_set(L, R);
1017 case ICmpInst::ICMP_UGE:
1018 return isl_pw_aff_ge_set(L, R);
1019 default:
1020 llvm_unreachable("Non integer predicate not supported");
1021 }
1022}
1023
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001024/// @brief Create the conditions under which @p L @p Pred @p R is true.
1025///
1026/// Helper function that will make sure the dimensions of the result have the
1027/// same isl_id's as the @p Domain.
1028static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1029 __isl_take isl_pw_aff *L,
1030 __isl_take isl_pw_aff *R,
1031 __isl_keep isl_set *Domain) {
1032 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1033 return setDimensionIds(Domain, ConsequenceCondSet);
1034}
1035
1036/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001037///
1038/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001039/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1040/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001041static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001042buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001043 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1044
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001045 Value *Condition = getConditionFromTerminator(SI);
1046 assert(Condition && "No condition for switch");
1047
1048 ScalarEvolution &SE = *S.getSE();
1049 BasicBlock *BB = SI->getParent();
1050 isl_pw_aff *LHS, *RHS;
1051 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
1052
1053 unsigned NumSuccessors = SI->getNumSuccessors();
1054 ConditionSets.resize(NumSuccessors);
1055 for (auto &Case : SI->cases()) {
1056 unsigned Idx = Case.getSuccessorIndex();
1057 ConstantInt *CaseValue = Case.getCaseValue();
1058
1059 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
1060 isl_set *CaseConditionSet =
1061 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1062 ConditionSets[Idx] = isl_set_coalesce(
1063 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1064 }
1065
1066 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1067 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1068 for (unsigned u = 2; u < NumSuccessors; u++)
1069 ConditionSetUnion =
1070 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1071 ConditionSets[0] = setDimensionIds(
1072 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1073
1074 S.markAsOptimized();
1075 isl_pw_aff_free(LHS);
1076}
1077
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001078/// @brief Build the conditions sets for the branch condition @p Condition in
1079/// the @p Domain.
1080///
1081/// This will fill @p ConditionSets with the conditions under which control
1082/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001083/// have as many elements as @p TI has successors. If @p TI is nullptr the
1084/// context under which @p Condition is true/false will be returned as the
1085/// new elements of @p ConditionSets.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001086static void
1087buildConditionSets(Scop &S, Value *Condition, TerminatorInst *TI, Loop *L,
1088 __isl_keep isl_set *Domain,
1089 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1090
1091 isl_set *ConsequenceCondSet = nullptr;
1092 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1093 if (CCond->isZero())
1094 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1095 else
1096 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1097 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1098 auto Opcode = BinOp->getOpcode();
1099 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1100
1101 buildConditionSets(S, BinOp->getOperand(0), TI, L, Domain, ConditionSets);
1102 buildConditionSets(S, BinOp->getOperand(1), TI, L, Domain, ConditionSets);
1103
1104 isl_set_free(ConditionSets.pop_back_val());
1105 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1106 isl_set_free(ConditionSets.pop_back_val());
1107 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1108
1109 if (Opcode == Instruction::And)
1110 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1111 else
1112 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1113 } else {
1114 auto *ICond = dyn_cast<ICmpInst>(Condition);
1115 assert(ICond &&
1116 "Condition of exiting branch was neither constant nor ICmp!");
1117
1118 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001119 BasicBlock *BB = TI ? TI->getParent() : nullptr;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001120 isl_pw_aff *LHS, *RHS;
1121 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1122 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
1123 ConsequenceCondSet =
1124 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1125 }
1126
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001127 // If no terminator was given we are only looking for parameter constraints
1128 // under which @p Condition is true/false.
1129 if (!TI)
1130 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
1131
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001132 assert(ConsequenceCondSet);
1133 isl_set *AlternativeCondSet =
1134 isl_set_complement(isl_set_copy(ConsequenceCondSet));
1135
1136 ConditionSets.push_back(isl_set_coalesce(
1137 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
1138 ConditionSets.push_back(isl_set_coalesce(
1139 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
1140}
1141
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001142/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1143///
1144/// This will fill @p ConditionSets with the conditions under which control
1145/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1146/// have as many elements as @p TI has successors.
1147static void
1148buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1149 __isl_keep isl_set *Domain,
1150 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1151
1152 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1153 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1154
1155 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1156
1157 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001158 ConditionSets.push_back(isl_set_copy(Domain));
1159 return;
1160 }
1161
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001162 Value *Condition = getConditionFromTerminator(TI);
1163 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001164
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001165 return buildConditionSets(S, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001166}
1167
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001168void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +00001169 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +00001170
Tobias Grosser084d8f72012-05-29 09:29:44 +00001171 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1172
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001173 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001174 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001175}
1176
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001177void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001178 isl_ctx *Ctx = Parent.getIslCtx();
1179 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1180 Type *Ty = GEP->getPointerOperandType();
1181 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001182 ScopDetection &SD = Parent.getSD();
1183
1184 // The set of loads that are required to be invariant.
1185 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001186
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001187 std::vector<const SCEV *> Subscripts;
1188 std::vector<int> Sizes;
1189
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001190 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001191
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001192 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001193 Ty = PtrTy->getElementType();
1194 }
1195
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001196 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001197
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001198 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001199
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001200 for (size_t i = 0; i < Sizes.size(); i++) {
1201 auto Expr = Subscripts[i + IndexOffset];
1202 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001203
Johannes Doerfert09e36972015-10-07 20:17:36 +00001204 InvariantLoadsSetTy AccessILS;
1205 if (!isAffineExpr(&Parent.getRegion(), Expr, SE, nullptr, &AccessILS))
1206 continue;
1207
1208 bool NonAffine = false;
1209 for (LoadInst *LInst : AccessILS)
1210 if (!ScopRIL.count(LInst))
1211 NonAffine = true;
1212
1213 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001214 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001215
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001216 isl_pw_aff *AccessOffset = getPwAff(Expr);
1217 AccessOffset =
1218 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001219
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001220 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1221 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001222
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001223 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1224 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1225 OutOfBound = isl_set_params(OutOfBound);
1226 isl_set *InBound = isl_set_complement(OutOfBound);
1227 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001228
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001229 // A => B == !A or B
1230 isl_set *InBoundIfExecuted =
1231 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001232
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001233 Parent.addAssumption(INBOUNDS, InBoundIfExecuted, GEP->getDebugLoc());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001234 }
1235
1236 isl_local_space_free(LSpace);
1237}
1238
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001239void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1240 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001241 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1242 deriveAssumptionsFromGEP(GEP);
1243}
1244
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001245void ScopStmt::collectSurroundingLoops() {
1246 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1247 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1248 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1249 isl_id_free(DimId);
1250 }
1251}
1252
Michael Kruse9d080092015-09-11 21:41:48 +00001253ScopStmt::ScopStmt(Scop &parent, Region &R)
Michael Krusecac948e2015-10-02 13:53:07 +00001254 : Parent(parent), Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001255
Tobias Grosser16c44032015-07-09 07:31:45 +00001256 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001257}
1258
Michael Kruse9d080092015-09-11 21:41:48 +00001259ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Michael Krusecac948e2015-10-02 13:53:07 +00001260 : Parent(parent), Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001261
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001262 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001263}
1264
1265void ScopStmt::init() {
1266 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001267
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001268 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001269 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001270 buildAccessRelations();
1271
1272 if (BB) {
1273 deriveAssumptions(BB);
1274 } else {
1275 for (BasicBlock *Block : R->blocks()) {
1276 deriveAssumptions(Block);
1277 }
1278 }
1279
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001280 if (DetectReductions)
1281 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001282}
1283
Johannes Doerferte58a0122014-06-27 20:31:28 +00001284/// @brief Collect loads which might form a reduction chain with @p StoreMA
1285///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001286/// Check if the stored value for @p StoreMA is a binary operator with one or
1287/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001288/// used only once (by @p StoreMA) and its load operands are also used only
1289/// once, we have found a possible reduction chain. It starts at an operand
1290/// load and includes the binary operator and @p StoreMA.
1291///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001292/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001293/// escape this block or into any other store except @p StoreMA.
1294void ScopStmt::collectCandiateReductionLoads(
1295 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1296 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1297 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001298 return;
1299
1300 // Skip if there is not one binary operator between the load and the store
1301 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001302 if (!BinOp)
1303 return;
1304
1305 // Skip if the binary operators has multiple uses
1306 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001307 return;
1308
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001309 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001310 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1311 return;
1312
Johannes Doerfert9890a052014-07-01 00:32:29 +00001313 // Skip if the binary operator is outside the current SCoP
1314 if (BinOp->getParent() != Store->getParent())
1315 return;
1316
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001317 // Skip if it is a multiplicative reduction and we disabled them
1318 if (DisableMultiplicativeReductions &&
1319 (BinOp->getOpcode() == Instruction::Mul ||
1320 BinOp->getOpcode() == Instruction::FMul))
1321 return;
1322
Johannes Doerferte58a0122014-06-27 20:31:28 +00001323 // Check the binary operator operands for a candidate load
1324 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1325 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1326 if (!PossibleLoad0 && !PossibleLoad1)
1327 return;
1328
1329 // A load is only a candidate if it cannot escape (thus has only this use)
1330 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001331 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001332 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001333 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001334 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001335 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001336}
1337
1338/// @brief Check for reductions in this ScopStmt
1339///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001340/// Iterate over all store memory accesses and check for valid binary reduction
1341/// like chains. For all candidates we check if they have the same base address
1342/// and there are no other accesses which overlap with them. The base address
1343/// check rules out impossible reductions candidates early. The overlap check,
1344/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001345/// guarantees that none of the intermediate results will escape during
1346/// execution of the loop nest. We basically check here that no other memory
1347/// access can access the same memory as the potential reduction.
1348void ScopStmt::checkForReductions() {
1349 SmallVector<MemoryAccess *, 2> Loads;
1350 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1351
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001352 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001353 // stores and collecting possible reduction loads.
1354 for (MemoryAccess *StoreMA : MemAccs) {
1355 if (StoreMA->isRead())
1356 continue;
1357
1358 Loads.clear();
1359 collectCandiateReductionLoads(StoreMA, Loads);
1360 for (MemoryAccess *LoadMA : Loads)
1361 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1362 }
1363
1364 // Then check each possible candidate pair.
1365 for (const auto &CandidatePair : Candidates) {
1366 bool Valid = true;
1367 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1368 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1369
1370 // Skip those with obviously unequal base addresses.
1371 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1372 isl_map_free(LoadAccs);
1373 isl_map_free(StoreAccs);
1374 continue;
1375 }
1376
1377 // And check if the remaining for overlap with other memory accesses.
1378 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1379 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1380 isl_set *AllAccs = isl_map_range(AllAccsRel);
1381
1382 for (MemoryAccess *MA : MemAccs) {
1383 if (MA == CandidatePair.first || MA == CandidatePair.second)
1384 continue;
1385
1386 isl_map *AccRel =
1387 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1388 isl_set *Accs = isl_map_range(AccRel);
1389
1390 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1391 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1392 Valid = Valid && isl_set_is_empty(OverlapAccs);
1393 isl_set_free(OverlapAccs);
1394 }
1395 }
1396
1397 isl_set_free(AllAccs);
1398 if (!Valid)
1399 continue;
1400
Johannes Doerfertf6183392014-07-01 20:52:51 +00001401 const LoadInst *Load =
1402 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1403 MemoryAccess::ReductionType RT =
1404 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1405
Johannes Doerferte58a0122014-06-27 20:31:28 +00001406 // If no overlapping access was found we mark the load and store as
1407 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001408 CandidatePair.first->markAsReductionLike(RT);
1409 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001410 }
Tobias Grosser75805372011-04-29 06:27:02 +00001411}
1412
Tobias Grosser74394f02013-01-14 22:40:23 +00001413std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001414
Tobias Grosser54839312015-04-21 11:37:25 +00001415std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001416 auto *S = getSchedule();
1417 auto Str = stringFromIslObj(S);
1418 isl_map_free(S);
1419 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001420}
1421
Tobias Grosser74394f02013-01-14 22:40:23 +00001422unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001423
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001424unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001425
Tobias Grosser75805372011-04-29 06:27:02 +00001426const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1427
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001428const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001429 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001430}
1431
Tobias Grosser74394f02013-01-14 22:40:23 +00001432isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001433
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001434__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001435
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001436__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001437 return isl_set_get_space(Domain);
1438}
1439
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001440__isl_give isl_id *ScopStmt::getDomainId() const {
1441 return isl_set_get_tuple_id(Domain);
1442}
Tobias Grossercd95b772012-08-30 11:49:38 +00001443
Tobias Grosser10120182015-12-16 16:14:03 +00001444ScopStmt::~ScopStmt() { isl_set_free(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001445
1446void ScopStmt::print(raw_ostream &OS) const {
1447 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001448 OS.indent(12) << "Domain :=\n";
1449
1450 if (Domain) {
1451 OS.indent(16) << getDomainStr() << ";\n";
1452 } else
1453 OS.indent(16) << "n/a\n";
1454
Tobias Grosser54839312015-04-21 11:37:25 +00001455 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001456
1457 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001458 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001459 } else
1460 OS.indent(16) << "n/a\n";
1461
Tobias Grosser083d3d32014-06-28 08:59:45 +00001462 for (MemoryAccess *Access : MemAccs)
1463 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001464}
1465
1466void ScopStmt::dump() const { print(dbgs()); }
1467
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001468void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001469 // Remove all memory accesses in @p InvMAs from this statement
1470 // together with all scalar accesses that were caused by them.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001471 for (MemoryAccess *MA : InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001472 auto Predicate = [&](MemoryAccess *Acc) {
Tobias Grosser3a6ac9f2015-11-30 21:13:43 +00001473 return Acc->getAccessInstruction() == MA->getAccessInstruction();
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001474 };
1475 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1476 MemAccs.end());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001477 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001478 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001479}
1480
Tobias Grosser75805372011-04-29 06:27:02 +00001481//===----------------------------------------------------------------------===//
1482/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001483
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001484void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001485 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1486 isl_set_free(Context);
1487 Context = NewContext;
1488}
1489
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001490/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1491struct SCEVSensitiveParameterRewriter
1492 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1493 ValueToValueMap &VMap;
1494 ScalarEvolution &SE;
1495
1496public:
1497 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1498 : VMap(VMap), SE(SE) {}
1499
1500 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1501 ValueToValueMap &VMap) {
1502 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1503 return SSPR.visit(E);
1504 }
1505
1506 const SCEV *visit(const SCEV *E) {
1507 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1508 }
1509
1510 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1511
1512 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1513 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1514 }
1515
1516 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1517 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1518 }
1519
1520 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1521 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1522 }
1523
1524 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1525 SmallVector<const SCEV *, 4> Operands;
1526 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1527 Operands.push_back(visit(E->getOperand(i)));
1528 return SE.getAddExpr(Operands);
1529 }
1530
1531 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1532 SmallVector<const SCEV *, 4> Operands;
1533 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1534 Operands.push_back(visit(E->getOperand(i)));
1535 return SE.getMulExpr(Operands);
1536 }
1537
1538 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1539 SmallVector<const SCEV *, 4> Operands;
1540 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1541 Operands.push_back(visit(E->getOperand(i)));
1542 return SE.getSMaxExpr(Operands);
1543 }
1544
1545 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1546 SmallVector<const SCEV *, 4> Operands;
1547 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1548 Operands.push_back(visit(E->getOperand(i)));
1549 return SE.getUMaxExpr(Operands);
1550 }
1551
1552 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1553 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1554 }
1555
1556 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1557 auto *Start = visit(E->getStart());
1558 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1559 visit(E->getStepRecurrence(SE)),
1560 E->getLoop(), SCEV::FlagAnyWrap);
1561 return SE.getAddExpr(Start, AddRec);
1562 }
1563
1564 const SCEV *visitUnknown(const SCEVUnknown *E) {
1565 if (auto *NewValue = VMap.lookup(E->getValue()))
1566 return SE.getUnknown(NewValue);
1567 return E;
1568 }
1569};
1570
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001571const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001572 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001573}
1574
Tobias Grosserabfbe632013-02-05 12:09:06 +00001575void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001576 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001577 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001578
1579 // Normalize the SCEV to get the representing element for an invariant load.
1580 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1581
Tobias Grosser60b54f12011-11-08 15:41:28 +00001582 if (ParameterIds.find(Parameter) != ParameterIds.end())
1583 continue;
1584
1585 int dimension = Parameters.size();
1586
1587 Parameters.push_back(Parameter);
1588 ParameterIds[Parameter] = dimension;
1589 }
1590}
1591
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001592__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001593 // Normalize the SCEV to get the representing element for an invariant load.
1594 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1595
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001596 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001597
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001598 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001599 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001600
Tobias Grosser8f99c162011-11-15 11:38:55 +00001601 std::string ParameterName;
1602
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001603 ParameterName = "p_" + utostr_32(IdIter->second);
1604
Tobias Grosser8f99c162011-11-15 11:38:55 +00001605 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1606 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001607
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001608 // If this parameter references a specific Value and this value has a name
1609 // we use this name as it is likely to be unique and more useful than just
1610 // a number.
1611 if (Val->hasName())
1612 ParameterName = Val->getName();
1613 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
1614 auto LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
1615 if (LoadOrigin->hasName()) {
1616 ParameterName += "_loaded_from_";
1617 ParameterName +=
1618 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1619 }
1620 }
1621 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001622
Tobias Grosser20532b82014-04-11 17:56:49 +00001623 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1624 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001625}
Tobias Grosser75805372011-04-29 06:27:02 +00001626
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001627isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1628 isl_set *DomainContext = isl_union_set_params(getDomains());
1629 return isl_set_intersect_params(C, DomainContext);
1630}
1631
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001632void Scop::buildBoundaryContext() {
Tobias Grosser4927c8e2015-11-24 12:50:02 +00001633 if (IgnoreIntegerWrapping) {
1634 BoundaryContext = isl_set_universe(getParamSpace());
1635 return;
1636 }
1637
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001638 BoundaryContext = Affinator.getWrappingContext();
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001639
1640 // The isl_set_complement operation used to create the boundary context
1641 // can possibly become very expensive. We bound the compile time of
1642 // this operation by setting a compute out.
1643 //
1644 // TODO: We can probably get around using isl_set_complement and directly
1645 // AST generate BoundaryContext.
1646 long MaxOpsOld = isl_ctx_get_max_operations(getIslCtx());
Tobias Grosserf920fb12015-11-13 16:56:13 +00001647 isl_ctx_reset_operations(getIslCtx());
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001648 isl_ctx_set_max_operations(getIslCtx(), 300000);
1649 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_CONTINUE);
1650
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001651 BoundaryContext = isl_set_complement(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001652
Tobias Grossera52b4da2015-11-11 17:59:53 +00001653 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
1654 isl_set_free(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001655 BoundaryContext = isl_set_empty(getParamSpace());
Tobias Grossera52b4da2015-11-11 17:59:53 +00001656 }
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001657
1658 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
1659 isl_ctx_reset_operations(getIslCtx());
1660 isl_ctx_set_max_operations(getIslCtx(), MaxOpsOld);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001661 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001662 trackAssumption(WRAPPING, BoundaryContext, DebugLoc());
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001663}
1664
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001665void Scop::addUserAssumptions(AssumptionCache &AC) {
1666 auto *R = &getRegion();
1667 auto &F = *R->getEntry()->getParent();
1668 for (auto &Assumption : AC.assumptions()) {
1669 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1670 if (!CI || CI->getNumArgOperands() != 1)
1671 continue;
1672 if (!DT.dominates(CI->getParent(), R->getEntry()))
1673 continue;
1674
1675 auto *Val = CI->getArgOperand(0);
1676 std::vector<const SCEV *> Params;
1677 if (!isAffineParamConstraint(Val, R, *SE, Params)) {
1678 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1679 CI->getDebugLoc(),
1680 "Non-affine user assumption ignored.");
1681 continue;
1682 }
1683
1684 addParams(Params);
1685
1686 auto *L = LI.getLoopFor(CI->getParent());
1687 SmallVector<isl_set *, 2> ConditionSets;
1688 buildConditionSets(*this, Val, nullptr, L, Context, ConditionSets);
1689 assert(ConditionSets.size() == 2);
1690 isl_set_free(ConditionSets[1]);
1691
1692 auto *AssumptionCtx = ConditionSets[0];
1693 emitOptimizationRemarkAnalysis(
1694 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1695 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1696 Context = isl_set_intersect(Context, AssumptionCtx);
1697 }
1698}
1699
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001700void Scop::addUserContext() {
1701 if (UserContextStr.empty())
1702 return;
1703
1704 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1705 isl_space *Space = getParamSpace();
1706 if (isl_space_dim(Space, isl_dim_param) !=
1707 isl_set_dim(UserContext, isl_dim_param)) {
1708 auto SpaceStr = isl_space_to_str(Space);
1709 errs() << "Error: the context provided in -polly-context has not the same "
1710 << "number of dimensions than the computed context. Due to this "
1711 << "mismatch, the -polly-context option is ignored. Please provide "
1712 << "the context in the parameter space: " << SpaceStr << ".\n";
1713 free(SpaceStr);
1714 isl_set_free(UserContext);
1715 isl_space_free(Space);
1716 return;
1717 }
1718
1719 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1720 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1721 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1722
1723 if (strcmp(NameContext, NameUserContext) != 0) {
1724 auto SpaceStr = isl_space_to_str(Space);
1725 errs() << "Error: the name of dimension " << i
1726 << " provided in -polly-context "
1727 << "is '" << NameUserContext << "', but the name in the computed "
1728 << "context is '" << NameContext
1729 << "'. Due to this name mismatch, "
1730 << "the -polly-context option is ignored. Please provide "
1731 << "the context in the parameter space: " << SpaceStr << ".\n";
1732 free(SpaceStr);
1733 isl_set_free(UserContext);
1734 isl_space_free(Space);
1735 return;
1736 }
1737
1738 UserContext =
1739 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1740 isl_space_get_dim_id(Space, isl_dim_param, i));
1741 }
1742
1743 Context = isl_set_intersect(Context, UserContext);
1744 isl_space_free(Space);
1745}
1746
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001747void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001748 DenseMap<const SCEV *, LoadInst *> EquivClasses;
1749
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001750 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001751 for (LoadInst *LInst : RIL) {
1752 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1753
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001754 LoadInst *&ClassRep = EquivClasses[PointerSCEV];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001755 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001756 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001757 continue;
1758 }
1759
1760 ClassRep = LInst;
1761 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(),
1762 nullptr);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001763 }
1764}
1765
Tobias Grosser6be480c2011-11-08 15:41:13 +00001766void Scop::buildContext() {
1767 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001768 Context = isl_set_universe(isl_space_copy(Space));
1769 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001770}
1771
Tobias Grosser18daaca2012-05-22 10:47:27 +00001772void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001773 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001774 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001775
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001776 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001777
Johannes Doerferte7044942015-02-24 11:58:30 +00001778 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001779 }
1780}
1781
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001782void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001783 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001784 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001785
Tobias Grosser083d3d32014-06-28 08:59:45 +00001786 for (const auto &ParamID : ParameterIds) {
1787 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001788 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001789 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001790 }
1791
1792 // Align the parameters of all data structures to the model.
1793 Context = isl_set_align_params(Context, Space);
1794
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001795 for (ScopStmt &Stmt : *this)
1796 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001797}
1798
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001799static __isl_give isl_set *
1800simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1801 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001802 // If we modelt all blocks in the SCoP that have side effects we can simplify
1803 // the context with the constraints that are needed for anything to be
1804 // executed at all. However, if we have error blocks in the SCoP we already
1805 // assumed some parameter combinations cannot occure and removed them from the
1806 // domains, thus we cannot use the remaining domain to simplify the
1807 // assumptions.
1808 if (!S.hasErrorBlock()) {
1809 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1810 AssumptionContext =
1811 isl_set_gist_params(AssumptionContext, DomainParameters);
1812 }
1813
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001814 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1815 return AssumptionContext;
1816}
1817
1818void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001819 // The parameter constraints of the iteration domains give us a set of
1820 // constraints that need to hold for all cases where at least a single
1821 // statement iteration is executed in the whole scop. We now simplify the
1822 // assumed context under the assumption that such constraints hold and at
1823 // least a single statement iteration is executed. For cases where no
1824 // statement instances are executed, the assumptions we have taken about
1825 // the executed code do not matter and can be changed.
1826 //
1827 // WARNING: This only holds if the assumptions we have taken do not reduce
1828 // the set of statement instances that are executed. Otherwise we
1829 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001830 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001831 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001832 // performed. In such a case, modifying the run-time conditions and
1833 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001834 // to not be executed.
1835 //
1836 // Example:
1837 //
1838 // When delinearizing the following code:
1839 //
1840 // for (long i = 0; i < 100; i++)
1841 // for (long j = 0; j < m; j++)
1842 // A[i+p][j] = 1.0;
1843 //
1844 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001845 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001846 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001847 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1848 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001849}
1850
Johannes Doerfertb164c792014-09-18 11:17:17 +00001851/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001852static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001853 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1854 isl_pw_multi_aff *MinPMA, *MaxPMA;
1855 isl_pw_aff *LastDimAff;
1856 isl_aff *OneAff;
1857 unsigned Pos;
1858
Johannes Doerfert9143d672014-09-27 11:02:39 +00001859 // Restrict the number of parameters involved in the access as the lexmin/
1860 // lexmax computation will take too long if this number is high.
1861 //
1862 // Experiments with a simple test case using an i7 4800MQ:
1863 //
1864 // #Parameters involved | Time (in sec)
1865 // 6 | 0.01
1866 // 7 | 0.04
1867 // 8 | 0.12
1868 // 9 | 0.40
1869 // 10 | 1.54
1870 // 11 | 6.78
1871 // 12 | 30.38
1872 //
1873 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1874 unsigned InvolvedParams = 0;
1875 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1876 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1877 InvolvedParams++;
1878
1879 if (InvolvedParams > RunTimeChecksMaxParameters) {
1880 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001881 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001882 }
1883 }
1884
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001885 Set = isl_set_remove_divs(Set);
1886
Johannes Doerfertb164c792014-09-18 11:17:17 +00001887 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1888 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1889
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001890 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1891 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1892
Johannes Doerfertb164c792014-09-18 11:17:17 +00001893 // Adjust the last dimension of the maximal access by one as we want to
1894 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1895 // we test during code generation might now point after the end of the
1896 // allocated array but we will never dereference it anyway.
1897 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1898 "Assumed at least one output dimension");
1899 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1900 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1901 OneAff = isl_aff_zero_on_domain(
1902 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1903 OneAff = isl_aff_add_constant_si(OneAff, 1);
1904 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1905 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1906
1907 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1908
1909 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001910 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001911}
1912
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001913static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1914 isl_set *Domain = MA->getStatement()->getDomain();
1915 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1916 return isl_set_reset_tuple_id(Domain);
1917}
1918
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001919/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1920static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001921 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001922 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001923
1924 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1925 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001926 Locations = isl_union_set_coalesce(Locations);
1927 Locations = isl_union_set_detect_equalities(Locations);
1928 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001929 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001930 isl_union_set_free(Locations);
1931 return Valid;
1932}
1933
Johannes Doerfert96425c22015-08-30 21:13:53 +00001934/// @brief Helper to treat non-affine regions and basic blocks the same.
1935///
1936///{
1937
1938/// @brief Return the block that is the representing block for @p RN.
1939static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1940 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1941 : RN->getNodeAs<BasicBlock>();
1942}
1943
1944/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001945static inline BasicBlock *
1946getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001947 if (RN->isSubRegion()) {
1948 assert(idx == 0);
1949 return RN->getNodeAs<Region>()->getExit();
1950 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001951 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001952}
1953
1954/// @brief Return the smallest loop surrounding @p RN.
1955static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1956 if (!RN->isSubRegion())
1957 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1958
1959 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1960 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1961 while (L && NonAffineSubRegion->contains(L))
1962 L = L->getParentLoop();
1963 return L;
1964}
1965
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001966static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1967 if (!RN->isSubRegion())
1968 return 1;
1969
1970 unsigned NumBlocks = 0;
1971 Region *R = RN->getNodeAs<Region>();
1972 for (auto BB : R->blocks()) {
1973 (void)BB;
1974 NumBlocks++;
1975 }
1976 return NumBlocks;
1977}
1978
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001979static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
1980 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00001981 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001982 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00001983 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001984 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00001985 return true;
1986 return false;
1987}
1988
Johannes Doerfert96425c22015-08-30 21:13:53 +00001989///}
1990
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001991static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1992 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001993 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001994 isl_id *DimId =
1995 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
1996 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
1997}
1998
Johannes Doerfert96425c22015-08-30 21:13:53 +00001999isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
2000 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
2001 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002002 return getDomainConditions(BB);
2003}
2004
2005isl_set *Scop::getDomainConditions(BasicBlock *BB) {
2006 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002007 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002008}
2009
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002010void Scop::removeErrorBlockDomains() {
2011 auto removeDomains = [this](BasicBlock *Start) {
2012 auto BBNode = DT.getNode(Start);
2013 for (auto ErrorChild : depth_first(BBNode)) {
2014 auto ErrorChildBlock = ErrorChild->getBlock();
2015 auto CurrentDomain = DomainMap[ErrorChildBlock];
2016 auto Empty = isl_set_empty(isl_set_get_space(CurrentDomain));
2017 DomainMap[ErrorChildBlock] = Empty;
2018 isl_set_free(CurrentDomain);
2019 }
2020 };
2021
Tobias Grosser5ef2bc32015-11-23 10:18:23 +00002022 SmallVector<Region *, 4> Todo = {&R};
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002023
2024 while (!Todo.empty()) {
2025 auto SubRegion = Todo.back();
2026 Todo.pop_back();
2027
2028 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
2029 for (auto &Child : *SubRegion)
2030 Todo.push_back(Child.get());
2031 continue;
2032 }
2033 if (containsErrorBlock(SubRegion->getNode(), getRegion(), LI, DT))
2034 removeDomains(SubRegion->getEntry());
2035 }
2036
2037 for (auto BB : R.blocks())
2038 if (isErrorBlock(*BB, R, LI, DT))
2039 removeDomains(BB);
2040}
2041
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002042void Scop::buildDomains(Region *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002043
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002044 auto *EntryBB = R->getEntry();
2045 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
2046 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002047
2048 Loop *L = LI.getLoopFor(EntryBB);
2049 while (LD-- >= 0) {
2050 S = addDomainDimId(S, LD + 1, L);
2051 L = L->getParentLoop();
2052 }
2053
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002054 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002055
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002056 if (SD.isNonAffineSubRegion(R, R))
2057 return;
2058
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002059 buildDomainsWithBranchConstraints(R);
2060 propagateDomainConstraints(R);
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002061
2062 // Error blocks and blocks dominated by them have been assumed to never be
2063 // executed. Representing them in the Scop does not add any value. In fact,
2064 // it is likely to cause issues during construction of the ScopStmts. The
2065 // contents of error blocks have not been verfied to be expressible and
2066 // will cause problems when building up a ScopStmt for them.
2067 // Furthermore, basic blocks dominated by error blocks may reference
2068 // instructions in the error block which, if the error block is not modeled,
2069 // can themselves not be constructed properly.
2070 removeErrorBlockDomains();
Johannes Doerfert96425c22015-08-30 21:13:53 +00002071}
2072
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002073void Scop::buildDomainsWithBranchConstraints(Region *R) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002074 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00002075
2076 // To create the domain for each block in R we iterate over all blocks and
2077 // subregions in R and propagate the conditions under which the current region
2078 // element is executed. To this end we iterate in reverse post order over R as
2079 // it ensures that we first visit all predecessors of a region node (either a
2080 // basic block or a subregion) before we visit the region node itself.
2081 // Initially, only the domain for the SCoP region entry block is set and from
2082 // there we propagate the current domain to all successors, however we add the
2083 // condition that the successor is actually executed next.
2084 // As we are only interested in non-loop carried constraints here we can
2085 // simply skip loop back edges.
2086
2087 ReversePostOrderTraversal<Region *> RTraversal(R);
2088 for (auto *RN : RTraversal) {
2089
2090 // Recurse for affine subregions but go on for basic blocks and non-affine
2091 // subregions.
2092 if (RN->isSubRegion()) {
2093 Region *SubRegion = RN->getNodeAs<Region>();
2094 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002095 buildDomainsWithBranchConstraints(SubRegion);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002096 continue;
2097 }
2098 }
2099
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002100 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002101 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002102
Johannes Doerfert96425c22015-08-30 21:13:53 +00002103 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002104 TerminatorInst *TI = BB->getTerminator();
2105
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002106 if (isa<UnreachableInst>(TI))
2107 continue;
2108
Johannes Doerfertf5673802015-10-01 23:48:18 +00002109 isl_set *Domain = DomainMap.lookup(BB);
2110 if (!Domain) {
2111 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2112 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002113 continue;
2114 }
2115
Johannes Doerfert96425c22015-08-30 21:13:53 +00002116 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002117
2118 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2119 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2120
2121 // Build the condition sets for the successor nodes of the current region
2122 // node. If it is a non-affine subregion we will always execute the single
2123 // exit node, hence the single entry node domain is the condition set. For
2124 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002125 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002126 if (RN->isSubRegion())
2127 ConditionSets.push_back(isl_set_copy(Domain));
2128 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002129 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002130
2131 // Now iterate over the successors and set their initial domain based on
2132 // their condition set. We skip back edges here and have to be careful when
2133 // we leave a loop not to keep constraints over a dimension that doesn't
2134 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002135 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002136 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002137 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002138 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002139
2140 // Skip back edges.
2141 if (DT.dominates(SuccBB, BB)) {
2142 isl_set_free(CondSet);
2143 continue;
2144 }
2145
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002146 // Do not adjust the number of dimensions if we enter a boxed loop or are
2147 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002148 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002149 Region *SuccRegion = RI.getRegionFor(SuccBB);
Johannes Doerfert634909c2015-10-04 14:57:41 +00002150 if (SD.isNonAffineSubRegion(SuccRegion, &getRegion()))
2151 while (SuccBBLoop && SuccRegion->contains(SuccBBLoop))
2152 SuccBBLoop = SuccBBLoop->getParentLoop();
2153
2154 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002155
2156 // Check if the edge to SuccBB is a loop entry or exit edge. If so
2157 // adjust the dimensionality accordingly. Lastly, if we leave a loop
2158 // and enter a new one we need to drop the old constraints.
2159 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002160 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002161 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002162 CondSet = isl_set_project_out(CondSet, isl_dim_set,
2163 isl_set_n_dim(CondSet) - LoopDepthDiff,
2164 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002165 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002166 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002167 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002168 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002169 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002170 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002171 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
2172 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002173 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002174 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002175 }
2176
2177 // Set the domain for the successor or merge it with an existing domain in
2178 // case there are multiple paths (without loop back edges) to the
2179 // successor block.
2180 isl_set *&SuccDomain = DomainMap[SuccBB];
2181 if (!SuccDomain)
2182 SuccDomain = CondSet;
2183 else
2184 SuccDomain = isl_set_union(SuccDomain, CondSet);
2185
2186 SuccDomain = isl_set_coalesce(SuccDomain);
Tobias Grosser75dc40c2015-12-20 13:31:48 +00002187 if (isl_set_n_basic_set(SuccDomain) > MaxConjunctsInDomain) {
2188 auto *Empty = isl_set_empty(isl_set_get_space(SuccDomain));
2189 isl_set_free(SuccDomain);
2190 SuccDomain = Empty;
2191 invalidate(ERROR_DOMAINCONJUNCTS, DebugLoc());
2192 }
Johannes Doerfert634909c2015-10-04 14:57:41 +00002193 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
2194 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002195 }
2196 }
2197}
2198
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002199/// @brief Return the domain for @p BB wrt @p DomainMap.
2200///
2201/// This helper function will lookup @p BB in @p DomainMap but also handle the
2202/// case where @p BB is contained in a non-affine subregion using the region
2203/// tree obtained by @p RI.
2204static __isl_give isl_set *
2205getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
2206 RegionInfo &RI) {
2207 auto DIt = DomainMap.find(BB);
2208 if (DIt != DomainMap.end())
2209 return isl_set_copy(DIt->getSecond());
2210
2211 Region *R = RI.getRegionFor(BB);
2212 while (R->getEntry() == BB)
2213 R = R->getParent();
2214 return getDomainForBlock(R->getEntry(), DomainMap, RI);
2215}
2216
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002217void Scop::propagateDomainConstraints(Region *R) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002218 // Iterate over the region R and propagate the domain constrains from the
2219 // predecessors to the current node. In contrast to the
2220 // buildDomainsWithBranchConstraints function, this one will pull the domain
2221 // information from the predecessors instead of pushing it to the successors.
2222 // Additionally, we assume the domains to be already present in the domain
2223 // map here. However, we iterate again in reverse post order so we know all
2224 // predecessors have been visited before a block or non-affine subregion is
2225 // visited.
2226
2227 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2228 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2229
2230 ReversePostOrderTraversal<Region *> RTraversal(R);
2231 for (auto *RN : RTraversal) {
2232
2233 // Recurse for affine subregions but go on for basic blocks and non-affine
2234 // subregions.
2235 if (RN->isSubRegion()) {
2236 Region *SubRegion = RN->getNodeAs<Region>();
2237 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002238 propagateDomainConstraints(SubRegion);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002239 continue;
2240 }
2241 }
2242
Johannes Doerfertf5673802015-10-01 23:48:18 +00002243 // Get the domain for the current block and check if it was initialized or
2244 // not. The only way it was not is if this block is only reachable via error
2245 // blocks, thus will not be executed under the assumptions we make. Such
2246 // blocks have to be skipped as their predecessors might not have domains
2247 // either. It would not benefit us to compute the domain anyway, only the
2248 // domains of the error blocks that are reachable from non-error blocks
2249 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002250 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002251 isl_set *&Domain = DomainMap[BB];
2252 if (!Domain) {
2253 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2254 << ", it is only reachable from error blocks.\n");
2255 DomainMap.erase(BB);
2256 continue;
2257 }
2258 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
2259
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002260 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2261 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2262
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002263 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2264 for (auto *PredBB : predecessors(BB)) {
2265
2266 // Skip backedges
2267 if (DT.dominates(BB, PredBB))
2268 continue;
2269
2270 isl_set *PredBBDom = nullptr;
2271
2272 // Handle the SCoP entry block with its outside predecessors.
2273 if (!getRegion().contains(PredBB))
2274 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
2275
2276 if (!PredBBDom) {
2277 // Determine the loop depth of the predecessor and adjust its domain to
2278 // the domain of the current block. This can mean we have to:
2279 // o) Drop a dimension if this block is the exit of a loop, not the
2280 // header of a new loop and the predecessor was part of the loop.
2281 // o) Add an unconstrainted new dimension if this block is the header
2282 // of a loop and the predecessor is not part of it.
2283 // o) Drop the information about the innermost loop dimension when the
2284 // predecessor and the current block are surrounded by different
2285 // loops in the same depth.
2286 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2287 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2288 while (BoxedLoops.count(PredBBLoop))
2289 PredBBLoop = PredBBLoop->getParentLoop();
2290
2291 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002292 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002293 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002294 PredBBDom = isl_set_project_out(
2295 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2296 LoopDepthDiff);
2297 else if (PredBBLoopDepth < BBLoopDepth) {
2298 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002299 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002300 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2301 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002302 PredBBDom = isl_set_drop_constraints_involving_dims(
2303 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002304 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002305 }
2306
2307 PredDom = isl_set_union(PredDom, PredBBDom);
2308 }
2309
2310 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002311 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002312
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002313 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002314 addLoopBoundsToHeaderDomain(BBLoop);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002315
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002316 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002317 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002318 IsOptimized = true;
2319 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002320 addAssumption(ERRORBLOCK, isl_set_complement(DomPar),
2321 BB->getTerminator()->getDebugLoc());
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002322 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002323 }
2324}
2325
2326/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2327/// is incremented by one and all other dimensions are equal, e.g.,
2328/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2329/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2330static __isl_give isl_map *
2331createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2332 auto *MapSpace = isl_space_map_from_set(SetSpace);
2333 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2334 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2335 if (u != Dim)
2336 NextIterationMap =
2337 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2338 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2339 C = isl_constraint_set_constant_si(C, 1);
2340 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2341 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2342 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2343 return NextIterationMap;
2344}
2345
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002346void Scop::addLoopBoundsToHeaderDomain(Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002347 int LoopDepth = getRelativeLoopDepth(L);
2348 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002349
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002350 BasicBlock *HeaderBB = L->getHeader();
2351 assert(DomainMap.count(HeaderBB));
2352 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002353
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002354 isl_map *NextIterationMap =
2355 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002356
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002357 isl_set *UnionBackedgeCondition =
2358 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002359
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002360 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2361 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002362
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002363 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002364
2365 // If the latch is only reachable via error statements we skip it.
2366 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2367 if (!LatchBBDom)
2368 continue;
2369
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002370 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002371
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002372 TerminatorInst *TI = LatchBB->getTerminator();
2373 BranchInst *BI = dyn_cast<BranchInst>(TI);
2374 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002375 BackedgeCondition = isl_set_copy(LatchBBDom);
2376 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002377 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002378 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002379 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002380
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002381 // Free the non back edge condition set as we do not need it.
2382 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002383
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002384 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002385 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002386
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002387 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2388 assert(LatchLoopDepth >= LoopDepth);
2389 BackedgeCondition =
2390 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2391 LatchLoopDepth - LoopDepth);
2392 UnionBackedgeCondition =
2393 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002394 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002395
2396 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2397 for (int i = 0; i < LoopDepth; i++)
2398 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2399
2400 isl_set *UnionBackedgeConditionComplement =
2401 isl_set_complement(UnionBackedgeCondition);
2402 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2403 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2404 UnionBackedgeConditionComplement =
2405 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2406 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2407 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2408
2409 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2410 HeaderBBDom = Parts.second;
2411
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002412 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2413 // the bounded assumptions to the context as they are already implied by the
2414 // <nsw> tag.
2415 if (Affinator.hasNSWAddRecForLoop(L)) {
2416 isl_set_free(Parts.first);
2417 return;
2418 }
2419
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002420 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2421 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002422 addAssumption(INFINITELOOP, BoundedCtx,
2423 HeaderBB->getTerminator()->getDebugLoc());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002424}
2425
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002426void Scop::buildAliasChecks(AliasAnalysis &AA) {
2427 if (!PollyUseRuntimeAliasChecks)
2428 return;
2429
2430 if (buildAliasGroups(AA))
2431 return;
2432
2433 // If a problem occurs while building the alias groups we need to delete
2434 // this SCoP and pretend it wasn't valid in the first place. To this end
2435 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002436 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002437
2438 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2439 << " could not be created as the number of parameters involved "
2440 "is too high. The SCoP will be "
2441 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2442 "the maximal number of parameters but be advised that the "
2443 "compile time might increase exponentially.\n\n");
2444}
2445
Johannes Doerfert9143d672014-09-27 11:02:39 +00002446bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002447 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002448 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002449 // for all memory accesses inside the SCoP.
2450 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002451 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002452 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002453 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002454 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002455 // if their access domains intersect, otherwise they are in different
2456 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002457 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002458 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002459 // and maximal accesses to each array of a group in read only and non
2460 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002461 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2462
2463 AliasSetTracker AST(AA);
2464
2465 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002466 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002467 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002468
2469 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002470 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002471 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2472 isl_set_free(StmtDomain);
2473 if (StmtDomainEmpty)
2474 continue;
2475
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002476 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002477 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002478 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002479 if (!MA->isRead())
2480 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002481 Instruction *Acc = MA->getAccessInstruction();
2482 PtrToAcc[getPointerOperand(*Acc)] = MA;
2483 AST.add(Acc);
2484 }
2485 }
2486
2487 SmallVector<AliasGroupTy, 4> AliasGroups;
2488 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002489 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002490 continue;
2491 AliasGroupTy AG;
2492 for (auto PR : AS)
2493 AG.push_back(PtrToAcc[PR.getValue()]);
2494 assert(AG.size() > 1 &&
2495 "Alias groups should contain at least two accesses");
2496 AliasGroups.push_back(std::move(AG));
2497 }
2498
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002499 // Split the alias groups based on their domain.
2500 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2501 AliasGroupTy NewAG;
2502 AliasGroupTy &AG = AliasGroups[u];
2503 AliasGroupTy::iterator AGI = AG.begin();
2504 isl_set *AGDomain = getAccessDomain(*AGI);
2505 while (AGI != AG.end()) {
2506 MemoryAccess *MA = *AGI;
2507 isl_set *MADomain = getAccessDomain(MA);
2508 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2509 NewAG.push_back(MA);
2510 AGI = AG.erase(AGI);
2511 isl_set_free(MADomain);
2512 } else {
2513 AGDomain = isl_set_union(AGDomain, MADomain);
2514 AGI++;
2515 }
2516 }
2517 if (NewAG.size() > 1)
2518 AliasGroups.push_back(std::move(NewAG));
2519 isl_set_free(AGDomain);
2520 }
2521
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002522 auto &F = *getRegion().getEntry()->getParent();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002523 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002524 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2525 for (AliasGroupTy &AG : AliasGroups) {
2526 NonReadOnlyBaseValues.clear();
2527 ReadOnlyPairs.clear();
2528
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002529 if (AG.size() < 2) {
2530 AG.clear();
2531 continue;
2532 }
2533
Johannes Doerfert13771732014-10-01 12:40:46 +00002534 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002535 emitOptimizationRemarkAnalysis(
2536 F.getContext(), DEBUG_TYPE, F,
2537 (*II)->getAccessInstruction()->getDebugLoc(),
2538 "Possibly aliasing pointer, use restrict keyword.");
2539
Johannes Doerfert13771732014-10-01 12:40:46 +00002540 Value *BaseAddr = (*II)->getBaseAddr();
2541 if (HasWriteAccess.count(BaseAddr)) {
2542 NonReadOnlyBaseValues.insert(BaseAddr);
2543 II++;
2544 } else {
2545 ReadOnlyPairs[BaseAddr].insert(*II);
2546 II = AG.erase(II);
2547 }
2548 }
2549
2550 // If we don't have read only pointers check if there are at least two
2551 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002552 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002553 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002554 continue;
2555 }
2556
2557 // If we don't have non read only pointers clear the alias group.
2558 if (NonReadOnlyBaseValues.empty()) {
2559 AG.clear();
2560 continue;
2561 }
2562
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002563 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002564 MinMaxAliasGroups.emplace_back();
2565 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2566 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2567 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2568 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002569
2570 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002571
2572 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002573 for (MemoryAccess *MA : AG)
2574 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002575
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002576 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2577 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002578
2579 // Bail out if the number of values we need to compare is too large.
2580 // This is important as the number of comparisions grows quadratically with
2581 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002582 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2583 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002584 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002585
2586 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002587 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002588 Accesses = isl_union_map_empty(getParamSpace());
2589
2590 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2591 for (MemoryAccess *MA : ReadOnlyPair.second)
2592 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2593
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002594 Valid =
2595 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002596
2597 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002598 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002599 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002600
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002601 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002602}
2603
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002604/// @brief Get the smallest loop that contains @p R but is not in @p R.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002605static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002606 // Start with the smallest loop containing the entry and expand that
2607 // loop until it contains all blocks in the region. If there is a loop
2608 // containing all blocks in the region check if it is itself contained
2609 // and if so take the parent loop as it will be the smallest containing
2610 // the region but not contained by it.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002611 Loop *L = LI.getLoopFor(R.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002612 while (L) {
2613 bool AllContained = true;
2614 for (auto *BB : R.blocks())
2615 AllContained &= L->contains(BB);
2616 if (AllContained)
2617 break;
2618 L = L->getParentLoop();
2619 }
2620
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002621 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2622}
2623
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002624static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2625 ScopDetection &SD) {
2626
2627 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2628
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002629 unsigned MinLD = INT_MAX, MaxLD = 0;
2630 for (BasicBlock *BB : R.blocks()) {
2631 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002632 if (!R.contains(L))
2633 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002634 if (BoxedLoops && BoxedLoops->count(L))
2635 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002636 unsigned LD = L->getLoopDepth();
2637 MinLD = std::min(MinLD, LD);
2638 MaxLD = std::max(MaxLD, LD);
2639 }
2640 }
2641
2642 // Handle the case that there is no loop in the SCoP first.
2643 if (MaxLD == 0)
2644 return 1;
2645
2646 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2647 assert(MaxLD >= MinLD &&
2648 "Maximal loop depth was smaller than mininaml loop depth?");
2649 return MaxLD - MinLD + 1;
2650}
2651
Johannes Doerfert478a7de2015-10-02 13:09:31 +00002652Scop::Scop(Region &R, AccFuncMapType &AccFuncMap, ScopDetection &SD,
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002653 ScalarEvolution &ScalarEvolution, DominatorTree &DT, LoopInfo &LI,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002654 isl_ctx *Context, unsigned MaxLoopDepth)
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002655 : LI(LI), DT(DT), SE(&ScalarEvolution), SD(SD), R(R),
2656 AccFuncMap(AccFuncMap), IsOptimized(false),
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002657 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
2658 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Context(nullptr),
2659 Affinator(this), AssumedContext(nullptr), BoundaryContext(nullptr),
2660 Schedule(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002661
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002662void Scop::init(AliasAnalysis &AA, AssumptionCache &AC) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002663 buildContext();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002664 addUserAssumptions(AC);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002665 buildInvariantEquivalenceClasses();
2666
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002667 buildDomains(&R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002668
Michael Krusecac948e2015-10-02 13:53:07 +00002669 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002670 // Exit early in case there are no executable statements left in this scop.
Michael Krusecac948e2015-10-02 13:53:07 +00002671 simplifySCoP(true);
Michael Kruseafe06702015-10-02 16:33:27 +00002672 if (Stmts.empty())
2673 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002674
Michael Krusecac948e2015-10-02 13:53:07 +00002675 // The ScopStmts now have enough information to initialize themselves.
2676 for (ScopStmt &Stmt : Stmts)
2677 Stmt.init();
2678
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00002679 buildSchedule();
Tobias Grosser75805372011-04-29 06:27:02 +00002680
Tobias Grosser8286b832015-11-02 11:29:32 +00002681 if (isl_set_is_empty(AssumedContext))
2682 return;
2683
2684 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002685 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002686 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002687 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002688 buildBoundaryContext();
2689 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002690 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002691
2692 hoistInvariantLoads();
Michael Krusecac948e2015-10-02 13:53:07 +00002693 simplifySCoP(false);
Tobias Grosser75805372011-04-29 06:27:02 +00002694}
2695
2696Scop::~Scop() {
2697 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002698 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002699 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002700 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002701
Johannes Doerfert96425c22015-08-30 21:13:53 +00002702 for (auto It : DomainMap)
2703 isl_set_free(It.second);
2704
Johannes Doerfertb164c792014-09-18 11:17:17 +00002705 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002706 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002707 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002708 isl_pw_multi_aff_free(MMA.first);
2709 isl_pw_multi_aff_free(MMA.second);
2710 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002711 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002712 isl_pw_multi_aff_free(MMA.first);
2713 isl_pw_multi_aff_free(MMA.second);
2714 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002715 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002716
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002717 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002718 isl_set_free(std::get<2>(IAClass));
Tobias Grosser75805372011-04-29 06:27:02 +00002719}
2720
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002721void Scop::updateAccessDimensionality() {
2722 for (auto &Stmt : *this)
2723 for (auto &Access : Stmt)
2724 Access->updateDimensionality();
2725}
2726
Michael Krusecac948e2015-10-02 13:53:07 +00002727void Scop::simplifySCoP(bool RemoveIgnoredStmts) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002728 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2729 ScopStmt &Stmt = *StmtIt;
Michael Krusecac948e2015-10-02 13:53:07 +00002730 RegionNode *RN = Stmt.isRegionStmt()
2731 ? Stmt.getRegion()->getNode()
2732 : getRegion().getBBNode(Stmt.getBasicBlock());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002733
Johannes Doerferteca9e892015-11-03 16:54:49 +00002734 bool RemoveStmt = StmtIt->isEmpty();
2735 if (!RemoveStmt)
2736 RemoveStmt = isl_set_is_empty(DomainMap[getRegionNodeBasicBlock(RN)]);
2737 if (!RemoveStmt)
2738 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002739
Johannes Doerferteca9e892015-11-03 16:54:49 +00002740 // Remove read only statements only after invariant loop hoisting.
2741 if (!RemoveStmt && !RemoveIgnoredStmts) {
2742 bool OnlyRead = true;
2743 for (MemoryAccess *MA : Stmt) {
2744 if (MA->isRead())
2745 continue;
2746
2747 OnlyRead = false;
2748 break;
2749 }
2750
2751 RemoveStmt = OnlyRead;
2752 }
2753
2754 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00002755 // Remove the statement because it is unnecessary.
2756 if (Stmt.isRegionStmt())
2757 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2758 StmtMap.erase(BB);
2759 else
2760 StmtMap.erase(Stmt.getBasicBlock());
2761
2762 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002763 continue;
2764 }
2765
Michael Krusecac948e2015-10-02 13:53:07 +00002766 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002767 }
2768}
2769
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002770const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2771 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2772 if (!LInst)
2773 return nullptr;
2774
2775 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2776 LInst = cast<LoadInst>(Rep);
2777
2778 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2779 for (auto &IAClass : InvariantEquivClasses)
2780 if (PointerSCEV == std::get<0>(IAClass))
2781 return &IAClass;
2782
2783 return nullptr;
2784}
2785
2786void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2787
2788 // Get the context under which the statement is executed.
2789 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2790 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2791 DomainCtx = isl_set_detect_equalities(DomainCtx);
2792 DomainCtx = isl_set_coalesce(DomainCtx);
2793
2794 // Project out all parameters that relate to loads in the statement. Otherwise
2795 // we could have cyclic dependences on the constraints under which the
2796 // hoisted loads are executed and we could not determine an order in which to
2797 // pre-load them. This happens because not only lower bounds are part of the
2798 // domain but also upper bounds.
2799 for (MemoryAccess *MA : InvMAs) {
2800 Instruction *AccInst = MA->getAccessInstruction();
2801 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00002802 SetVector<Value *> Values;
2803 for (const SCEV *Parameter : Parameters) {
2804 Values.clear();
2805 findValues(Parameter, Values);
2806 if (!Values.count(AccInst))
2807 continue;
2808
2809 if (isl_id *ParamId = getIdForParam(Parameter)) {
2810 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2811 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2812 isl_id_free(ParamId);
2813 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002814 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002815 }
2816 }
2817
2818 for (MemoryAccess *MA : InvMAs) {
2819 // Check for another invariant access that accesses the same location as
2820 // MA and if found consolidate them. Otherwise create a new equivalence
2821 // class at the end of InvariantEquivClasses.
2822 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
2823 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2824
2825 bool Consolidated = false;
2826 for (auto &IAClass : InvariantEquivClasses) {
2827 if (PointerSCEV != std::get<0>(IAClass))
2828 continue;
2829
2830 Consolidated = true;
2831
2832 // Add MA to the list of accesses that are in this class.
2833 auto &MAs = std::get<1>(IAClass);
2834 MAs.push_front(MA);
2835
2836 // Unify the execution context of the class and this statement.
2837 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002838 if (IAClassDomainCtx)
2839 IAClassDomainCtx = isl_set_coalesce(
2840 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
2841 else
2842 IAClassDomainCtx = isl_set_copy(DomainCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002843 break;
2844 }
2845
2846 if (Consolidated)
2847 continue;
2848
2849 // If we did not consolidate MA, thus did not find an equivalence class
2850 // for it, we create a new one.
2851 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
2852 isl_set_copy(DomainCtx));
2853 }
2854
2855 isl_set_free(DomainCtx);
2856}
2857
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002858bool Scop::isHoistableAccess(MemoryAccess *Access,
2859 __isl_keep isl_union_map *Writes) {
2860 // TODO: Loads that are not loop carried, hence are in a statement with
2861 // zero iterators, are by construction invariant, though we
2862 // currently "hoist" them anyway. This is necessary because we allow
2863 // them to be treated as parameters (e.g., in conditions) and our code
2864 // generation would otherwise use the old value.
2865
2866 auto &Stmt = *Access->getStatement();
2867 BasicBlock *BB =
2868 Stmt.isBlockStmt() ? Stmt.getBasicBlock() : Stmt.getRegion()->getEntry();
2869
2870 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
2871 return false;
2872
2873 // Skip accesses that have an invariant base pointer which is defined but
2874 // not loaded inside the SCoP. This can happened e.g., if a readnone call
2875 // returns a pointer that is used as a base address. However, as we want
2876 // to hoist indirect pointers, we allow the base pointer to be defined in
2877 // the region if it is also a memory access. Each ScopArrayInfo object
2878 // that has a base pointer origin has a base pointer that is loaded and
2879 // that it is invariant, thus it will be hoisted too. However, if there is
2880 // no base pointer origin we check that the base pointer is defined
2881 // outside the region.
2882 const ScopArrayInfo *SAI = Access->getScopArrayInfo();
2883 while (auto *BasePtrOriginSAI = SAI->getBasePtrOriginSAI())
2884 SAI = BasePtrOriginSAI;
2885
2886 if (auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr()))
2887 if (R.contains(BasePtrInst))
2888 return false;
2889
2890 // Skip accesses in non-affine subregions as they might not be executed
2891 // under the same condition as the entry of the non-affine subregion.
2892 if (BB != Access->getAccessInstruction()->getParent())
2893 return false;
2894
2895 isl_map *AccessRelation = Access->getAccessRelation();
2896
2897 // Skip accesses that have an empty access relation. These can be caused
2898 // by multiple offsets with a type cast in-between that cause the overall
2899 // byte offset to be not divisible by the new types sizes.
2900 if (isl_map_is_empty(AccessRelation)) {
2901 isl_map_free(AccessRelation);
2902 return false;
2903 }
2904
2905 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
2906 Stmt.getNumIterators())) {
2907 isl_map_free(AccessRelation);
2908 return false;
2909 }
2910
2911 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
2912 isl_set *AccessRange = isl_map_range(AccessRelation);
2913
2914 isl_union_map *Written = isl_union_map_intersect_range(
2915 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
2916 bool IsWritten = !isl_union_map_is_empty(Written);
2917 isl_union_map_free(Written);
2918
2919 if (IsWritten)
2920 return false;
2921
2922 return true;
2923}
2924
2925void Scop::verifyInvariantLoads() {
2926 auto &RIL = *SD.getRequiredInvariantLoads(&getRegion());
2927 for (LoadInst *LI : RIL) {
2928 assert(LI && getRegion().contains(LI));
2929 ScopStmt *Stmt = getStmtForBasicBlock(LI->getParent());
Tobias Grosser949e8c62015-12-21 07:10:39 +00002930 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002931 invalidate(INVARIANTLOAD, LI->getDebugLoc());
2932 return;
2933 }
2934 }
2935}
2936
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002937void Scop::hoistInvariantLoads() {
2938 isl_union_map *Writes = getWrites();
2939 for (ScopStmt &Stmt : *this) {
2940
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002941 MemoryAccessList InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002942
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002943 for (MemoryAccess *Access : Stmt)
2944 if (isHoistableAccess(Access, Writes))
2945 InvariantAccesses.push_front(Access);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002946
2947 // We inserted invariant accesses always in the front but need them to be
2948 // sorted in a "natural order". The statements are already sorted in reverse
2949 // post order and that suffices for the accesses too. The reason we require
2950 // an order in the first place is the dependences between invariant loads
2951 // that can be caused by indirect loads.
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002952 InvariantAccesses.reverse();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002953
2954 // Transfer the memory access from the statement to the SCoP.
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002955 Stmt.removeMemoryAccesses(InvariantAccesses);
2956 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002957 }
2958 isl_union_map_free(Writes);
2959
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002960 verifyInvariantLoads();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002961}
2962
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002963const ScopArrayInfo *
2964Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002965 ArrayRef<const SCEV *> Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00002966 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002967 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002968 if (!SAI) {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00002969 auto &DL = getRegion().getEntry()->getModule()->getDataLayout();
2970 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, Kind,
2971 DL, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002972 } else {
Tobias Grosser8286b832015-11-02 11:29:32 +00002973 // In case of mismatching array sizes, we bail out by setting the run-time
2974 // context to false.
2975 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002976 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002977 }
Tobias Grosserab671442015-05-23 05:58:27 +00002978 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002979}
2980
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002981const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00002982 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002983 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002984 assert(SAI && "No ScopArrayInfo available for this base pointer");
2985 return SAI;
2986}
2987
Tobias Grosser74394f02013-01-14 22:40:23 +00002988std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002989std::string Scop::getAssumedContextStr() const {
2990 return stringFromIslObj(AssumedContext);
2991}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002992std::string Scop::getBoundaryContextStr() const {
2993 return stringFromIslObj(BoundaryContext);
2994}
Tobias Grosser75805372011-04-29 06:27:02 +00002995
2996std::string Scop::getNameStr() const {
2997 std::string ExitName, EntryName;
2998 raw_string_ostream ExitStr(ExitName);
2999 raw_string_ostream EntryStr(EntryName);
3000
Tobias Grosserf240b482014-01-09 10:42:15 +00003001 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003002 EntryStr.str();
3003
3004 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003005 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003006 ExitStr.str();
3007 } else
3008 ExitName = "FunctionExit";
3009
3010 return EntryName + "---" + ExitName;
3011}
3012
Tobias Grosser74394f02013-01-14 22:40:23 +00003013__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003014__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003015 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003016}
3017
Tobias Grossere86109f2013-10-29 21:05:49 +00003018__isl_give isl_set *Scop::getAssumedContext() const {
3019 return isl_set_copy(AssumedContext);
3020}
3021
Johannes Doerfert43788c52015-08-20 05:58:56 +00003022__isl_give isl_set *Scop::getRuntimeCheckContext() const {
3023 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003024 RuntimeCheckContext =
3025 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
3026 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00003027 return RuntimeCheckContext;
3028}
3029
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003030bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003031 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003032 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00003033 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
3034 isl_set_free(RuntimeCheckContext);
3035 return IsFeasible;
3036}
3037
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003038static std::string toString(AssumptionKind Kind) {
3039 switch (Kind) {
3040 case ALIASING:
3041 return "No-aliasing";
3042 case INBOUNDS:
3043 return "Inbounds";
3044 case WRAPPING:
3045 return "No-overflows";
Johannes Doerferta4b77c02015-11-12 20:15:32 +00003046 case ALIGNMENT:
3047 return "Alignment";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003048 case ERRORBLOCK:
3049 return "No-error";
3050 case INFINITELOOP:
3051 return "Finite loop";
3052 case INVARIANTLOAD:
3053 return "Invariant load";
3054 case DELINEARIZATION:
3055 return "Delinearization";
Tobias Grosser75dc40c2015-12-20 13:31:48 +00003056 case ERROR_DOMAINCONJUNCTS:
3057 return "Low number of domain conjuncts";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003058 }
3059 llvm_unreachable("Unknown AssumptionKind!");
3060}
3061
3062void Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3063 DebugLoc Loc) {
3064 if (isl_set_is_subset(Context, Set))
3065 return;
3066
3067 if (isl_set_is_subset(AssumedContext, Set))
3068 return;
3069
3070 auto &F = *getRegion().getEntry()->getParent();
3071 std::string Msg = toString(Kind) + " assumption:\t" + stringFromIslObj(Set);
3072 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
3073}
3074
3075void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
3076 DebugLoc Loc) {
3077 trackAssumption(Kind, Set, Loc);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003078 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003079
Johannes Doerfert9d7899e2015-11-11 20:01:31 +00003080 int NSets = isl_set_n_basic_set(AssumedContext);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003081 if (NSets >= MaxDisjunctsAssumed) {
3082 isl_space *Space = isl_set_get_space(AssumedContext);
3083 isl_set_free(AssumedContext);
Tobias Grossere19fca42015-11-11 20:21:39 +00003084 AssumedContext = isl_set_empty(Space);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003085 }
3086
Tobias Grosser7b50bee2014-11-25 10:51:12 +00003087 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003088}
3089
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003090void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
3091 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc);
3092}
3093
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003094__isl_give isl_set *Scop::getBoundaryContext() const {
3095 return isl_set_copy(BoundaryContext);
3096}
3097
Tobias Grosser75805372011-04-29 06:27:02 +00003098void Scop::printContext(raw_ostream &OS) const {
3099 OS << "Context:\n";
3100
3101 if (!Context) {
3102 OS.indent(4) << "n/a\n\n";
3103 return;
3104 }
3105
3106 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003107
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003108 OS.indent(4) << "Assumed Context:\n";
3109 if (!AssumedContext) {
3110 OS.indent(4) << "n/a\n\n";
3111 return;
3112 }
3113
3114 OS.indent(4) << getAssumedContextStr() << "\n";
3115
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003116 OS.indent(4) << "Boundary Context:\n";
3117 if (!BoundaryContext) {
3118 OS.indent(4) << "n/a\n\n";
3119 return;
3120 }
3121
3122 OS.indent(4) << getBoundaryContextStr() << "\n";
3123
Tobias Grosser083d3d32014-06-28 08:59:45 +00003124 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00003125 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00003126 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
3127 }
Tobias Grosser75805372011-04-29 06:27:02 +00003128}
3129
Johannes Doerfertb164c792014-09-18 11:17:17 +00003130void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003131 int noOfGroups = 0;
3132 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003133 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003134 noOfGroups += 1;
3135 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003136 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003137 }
3138
Tobias Grosserbb853c22015-07-25 12:31:03 +00003139 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003140 if (MinMaxAliasGroups.empty()) {
3141 OS.indent(8) << "n/a\n";
3142 return;
3143 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003144
Tobias Grosserbb853c22015-07-25 12:31:03 +00003145 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003146
3147 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003148 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003149 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003150 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003151 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3152 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003153 }
3154 OS << " ]]\n";
3155 }
3156
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003157 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003158 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003159 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003160 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003161 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3162 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003163 }
3164 OS << " ]]\n";
3165 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003166 }
3167}
3168
Tobias Grosser75805372011-04-29 06:27:02 +00003169void Scop::printStatements(raw_ostream &OS) const {
3170 OS << "Statements {\n";
3171
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003172 for (const ScopStmt &Stmt : *this)
3173 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003174
3175 OS.indent(4) << "}\n";
3176}
3177
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003178void Scop::printArrayInfo(raw_ostream &OS) const {
3179 OS << "Arrays {\n";
3180
Tobias Grosserab671442015-05-23 05:58:27 +00003181 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003182 Array.second->print(OS);
3183
3184 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003185
3186 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3187
3188 for (auto &Array : arrays())
3189 Array.second->print(OS, /* SizeAsPwAff */ true);
3190
3191 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003192}
3193
Tobias Grosser75805372011-04-29 06:27:02 +00003194void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00003195 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
3196 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003197 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003198 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003199 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003200 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003201 const auto &MAs = std::get<1>(IAClass);
3202 if (MAs.empty()) {
3203 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003204 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003205 MAs.front()->print(OS);
3206 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003207 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003208 }
3209 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003210 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003211 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003212 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003213 printStatements(OS.indent(4));
3214}
3215
3216void Scop::dump() const { print(dbgs()); }
3217
Tobias Grosser9a38ab82011-11-08 15:41:03 +00003218isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00003219
Johannes Doerfertcef616f2015-09-15 22:49:04 +00003220__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
3221 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003222}
3223
Tobias Grosser808cd692015-07-14 09:33:13 +00003224__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003225 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003226
Tobias Grosser808cd692015-07-14 09:33:13 +00003227 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003228 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003229
3230 return Domain;
3231}
3232
Tobias Grossere5a35142015-11-12 14:07:09 +00003233__isl_give isl_union_map *
3234Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3235 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003236
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003237 for (ScopStmt &Stmt : *this) {
3238 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003239 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003240 continue;
3241
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003242 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003243 isl_map *AccessDomain = MA->getAccessRelation();
3244 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003245 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003246 }
3247 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003248 return isl_union_map_coalesce(Accesses);
3249}
3250
3251__isl_give isl_union_map *Scop::getMustWrites() {
3252 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003253}
3254
3255__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003256 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003257}
3258
Tobias Grosser37eb4222014-02-20 21:43:54 +00003259__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003260 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003261}
3262
3263__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003264 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003265}
3266
Tobias Grosser2ac23382015-11-12 14:07:13 +00003267__isl_give isl_union_map *Scop::getAccesses() {
3268 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3269}
3270
Tobias Grosser808cd692015-07-14 09:33:13 +00003271__isl_give isl_union_map *Scop::getSchedule() const {
3272 auto Tree = getScheduleTree();
3273 auto S = isl_schedule_get_map(Tree);
3274 isl_schedule_free(Tree);
3275 return S;
3276}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003277
Tobias Grosser808cd692015-07-14 09:33:13 +00003278__isl_give isl_schedule *Scop::getScheduleTree() const {
3279 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3280 getDomains());
3281}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003282
Tobias Grosser808cd692015-07-14 09:33:13 +00003283void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3284 auto *S = isl_schedule_from_domain(getDomains());
3285 S = isl_schedule_insert_partial_schedule(
3286 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3287 isl_schedule_free(Schedule);
3288 Schedule = S;
3289}
3290
3291void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3292 isl_schedule_free(Schedule);
3293 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003294}
3295
3296bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3297 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003298 for (ScopStmt &Stmt : *this) {
3299 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003300 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3301 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3302
3303 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3304 isl_union_set_free(StmtDomain);
3305 isl_union_set_free(NewStmtDomain);
3306 continue;
3307 }
3308
3309 Changed = true;
3310
3311 isl_union_set_free(StmtDomain);
3312 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3313
3314 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003315 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003316 isl_union_set_free(NewStmtDomain);
3317 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003318 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003319 }
3320 isl_union_set_free(Domain);
3321 return Changed;
3322}
3323
Tobias Grosser75805372011-04-29 06:27:02 +00003324ScalarEvolution *Scop::getSE() const { return SE; }
3325
Johannes Doerfertf5673802015-10-01 23:48:18 +00003326bool Scop::isIgnored(RegionNode *RN) {
3327 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Michael Krusea902ba62015-12-13 19:21:45 +00003328 ScopStmt *Stmt = getStmtForRegionNode(RN);
3329
3330 // If there is no stmt, then it already has been removed.
3331 if (!Stmt)
3332 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00003333
Johannes Doerfertf5673802015-10-01 23:48:18 +00003334 // Check if there are accesses contained.
Michael Krusea902ba62015-12-13 19:21:45 +00003335 if (Stmt->isEmpty())
Johannes Doerfertf5673802015-10-01 23:48:18 +00003336 return true;
3337
3338 // Check for reachability via non-error blocks.
3339 if (!DomainMap.count(BB))
3340 return true;
3341
3342 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003343 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003344 return true;
3345
3346 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003347}
3348
Tobias Grosser808cd692015-07-14 09:33:13 +00003349struct MapToDimensionDataTy {
3350 int N;
3351 isl_union_pw_multi_aff *Res;
3352};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003353
Tobias Grosser808cd692015-07-14 09:33:13 +00003354// @brief Create a function that maps the elements of 'Set' to its N-th
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003355// dimension and add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00003356//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003357// @param Set The input set.
3358// @param User->N The dimension to map to.
3359// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00003360//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003361// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00003362static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3363 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3364 int Dim;
3365 isl_space *Space;
3366 isl_pw_multi_aff *PMA;
3367
3368 Dim = isl_set_dim(Set, isl_dim_set);
3369 Space = isl_set_get_space(Set);
3370 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3371 Dim - Data->N);
3372 if (Data->N > 1)
3373 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3374 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3375
3376 isl_set_free(Set);
3377
3378 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003379}
3380
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003381// @brief Create an isl_multi_union_aff that defines an identity mapping
3382// from the elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003383//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003384// # Example:
3385//
3386// Domain: { A[i,j]; B[i,j,k] }
3387// N: 1
3388//
3389// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
3390//
3391// @param USet A union set describing the elements for which to generate a
3392// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00003393// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003394// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003395static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003396mapToDimension(__isl_take isl_union_set *USet, int N) {
3397 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00003398 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003399 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003400
Tobias Grosser808cd692015-07-14 09:33:13 +00003401 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00003402
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003403 auto *Space = isl_union_set_get_space(USet);
3404 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00003405
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003406 Data = {N, PwAff};
3407
3408 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
3409
3410 assert(Res == isl_stat_ok);
3411
3412 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00003413 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3414}
3415
Tobias Grosser316b5b22015-11-11 19:28:14 +00003416void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003417 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003418 Stmts.emplace_back(*this, *BB);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003419 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003420 StmtMap[BB] = Stmt;
3421 } else {
3422 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003423 Stmts.emplace_back(*this, *R);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003424 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003425 for (BasicBlock *BB : R->blocks())
3426 StmtMap[BB] = Stmt;
3427 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003428}
3429
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003430void Scop::buildSchedule() {
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003431 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
3432 Loop *L = getLoopSurroundingRegion(getRegion(), LI);
3433 LoopSchedules[L];
Tobias Grosser8362c262016-01-06 15:30:06 +00003434 buildSchedule(getRegion().getNode(), LoopSchedules);
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003435 Schedule = LoopSchedules[L].first;
3436}
3437
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003438void Scop::buildSchedule(
Tobias Grosser8362c262016-01-06 15:30:06 +00003439 RegionNode *RN,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003440 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00003441
Tobias Grosser8362c262016-01-06 15:30:06 +00003442 if (RN->isSubRegion()) {
3443 auto *LocalRegion = RN->getNodeAs<Region>();
3444 if (!SD.isNonAffineSubRegion(LocalRegion, &getRegion())) {
3445 ReversePostOrderTraversal<Region *> RTraversal(LocalRegion);
3446 for (auto *Child : RTraversal)
3447 buildSchedule(Child, LoopSchedules);
3448 return;
3449 }
3450 }
Michael Kruse046dde42015-08-10 13:01:57 +00003451
Tobias Grosser8362c262016-01-06 15:30:06 +00003452 Loop *L = getRegionNodeLoop(RN, LI);
3453 if (!getRegion().contains(L))
3454 L = getLoopSurroundingRegion(getRegion(), LI);
3455
3456 int LD = getRelativeLoopDepth(L);
3457 auto &LSchedulePair = LoopSchedules[L];
3458 LSchedulePair.second += getNumBlocksInRegionNode(RN);
3459
3460 ScopStmt *Stmt = getStmtForRegionNode(RN);
3461 if (Stmt) {
3462 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3463 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
3464 LSchedulePair.first = combineInSequence(LSchedulePair.first, StmtSchedule);
3465 }
3466
3467 isl_schedule *LSchedule = LSchedulePair.first;
3468 unsigned NumVisited = LSchedulePair.second;
3469 while (L && NumVisited == L->getNumBlocks()) {
3470 auto *PL = L->getParentLoop();
3471
3472 // Either we have a proper loop and we also build a schedule for the
3473 // parent loop or we have a infinite loop that does not have a proper
3474 // parent loop. In the former case this conditional will be skipped, in
3475 // the latter case however we will break here as we do not build a domain
3476 // nor a schedule for a infinite loop.
3477 assert(LoopSchedules.count(PL) || LSchedule == nullptr);
3478 if (!LoopSchedules.count(PL))
3479 break;
3480
3481 auto &PSchedulePair = LoopSchedules[PL];
3482
3483 if (LSchedule) {
3484 auto *LDomain = isl_schedule_get_domain(LSchedule);
3485 auto *MUPA = mapToDimension(LDomain, LD + 1);
3486 LSchedule = isl_schedule_insert_partial_schedule(LSchedule, MUPA);
3487 PSchedulePair.first = combineInSequence(PSchedulePair.first, LSchedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003488 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003489
Tobias Grosser8362c262016-01-06 15:30:06 +00003490 PSchedulePair.second += NumVisited;
Johannes Doerfert30c22652015-10-18 21:17:11 +00003491
Tobias Grosser8362c262016-01-06 15:30:06 +00003492 L = PL;
3493 LD--;
3494 NumVisited = PSchedulePair.second;
3495 LSchedule = PSchedulePair.first;
Tobias Grosser808cd692015-07-14 09:33:13 +00003496 }
Tobias Grosser75805372011-04-29 06:27:02 +00003497}
3498
Johannes Doerfert7c494212014-10-31 23:13:39 +00003499ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003500 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003501 if (StmtMapIt == StmtMap.end())
3502 return nullptr;
3503 return StmtMapIt->second;
3504}
3505
Michael Krusea902ba62015-12-13 19:21:45 +00003506ScopStmt *Scop::getStmtForRegionNode(RegionNode *RN) const {
3507 return getStmtForBasicBlock(getRegionNodeBasicBlock(RN));
3508}
3509
Johannes Doerfert96425c22015-08-30 21:13:53 +00003510int Scop::getRelativeLoopDepth(const Loop *L) const {
3511 Loop *OuterLoop =
3512 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3513 if (!OuterLoop)
3514 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003515 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3516}
3517
Michael Krused868b5d2015-09-10 15:25:24 +00003518void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003519 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003520
3521 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3522 // true, are not modeled as ordinary PHI nodes as they are not part of the
3523 // region. However, we model the operands in the predecessor blocks that are
3524 // part of the region as regular scalar accesses.
3525
3526 // If we can synthesize a PHI we can skip it, however only if it is in
3527 // the region. If it is not it can only be in the exit block of the region.
3528 // In this case we model the operands but not the PHI itself.
3529 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3530 return;
3531
3532 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3533 // detection. Hence, the PHI is a load of a new memory location in which the
3534 // incoming value was written at the end of the incoming basic block.
3535 bool OnlyNonAffineSubRegionOperands = true;
3536 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3537 Value *Op = PHI->getIncomingValue(u);
3538 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3539
3540 // Do not build scalar dependences inside a non-affine subregion.
3541 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3542 continue;
3543
3544 OnlyNonAffineSubRegionOperands = false;
3545
3546 if (!R.contains(OpBB))
3547 continue;
3548
3549 Instruction *OpI = dyn_cast<Instruction>(Op);
3550 if (OpI) {
3551 BasicBlock *OpIBB = OpI->getParent();
3552 // As we pretend there is a use (or more precise a write) of OpI in OpBB
3553 // we have to insert a scalar dependence from the definition of OpI to
3554 // OpBB if the definition is not in OpBB.
Michael Kruse668af712015-10-15 14:45:48 +00003555 if (scop->getStmtForBasicBlock(OpIBB) !=
3556 scop->getStmtForBasicBlock(OpBB)) {
Michael Kruse34e11222015-12-13 22:47:43 +00003557 addValueReadAccess(OpI, PHI, OpBB);
3558 addValueWriteAccess(OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003559 }
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003560 } else if (ModelReadOnlyScalars && !isa<Constant>(Op)) {
Michael Kruse34e11222015-12-13 22:47:43 +00003561 addValueReadAccess(Op, PHI, OpBB);
Michael Kruse7bf39442015-09-10 12:46:52 +00003562 }
3563
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003564 addPHIWriteAccess(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003565 }
3566
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003567 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3568 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003569 }
3570}
3571
Michael Krused868b5d2015-09-10 15:25:24 +00003572bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
3573 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003574 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
3575 if (isIgnoredIntrinsic(Inst))
3576 return false;
3577
3578 bool AnyCrossStmtUse = false;
3579 BasicBlock *ParentBB = Inst->getParent();
3580
3581 for (User *U : Inst->users()) {
3582 Instruction *UI = dyn_cast<Instruction>(U);
3583
3584 // Ignore the strange user
3585 if (UI == 0)
3586 continue;
3587
3588 BasicBlock *UseParent = UI->getParent();
3589
Tobias Grosserbaffa092015-10-24 20:55:27 +00003590 // Ignore basic block local uses. A value that is defined in a scop, but
3591 // used in a PHI node in the same basic block does not count as basic block
3592 // local, as for such cases a control flow edge is passed between definition
3593 // and use.
3594 if (UseParent == ParentBB && !isa<PHINode>(UI))
Michael Kruse7bf39442015-09-10 12:46:52 +00003595 continue;
3596
Michael Krusef714d472015-11-05 13:18:43 +00003597 // Uses by PHI nodes in the entry node count as external uses in case the
3598 // use is through an incoming block that is itself not contained in the
3599 // region.
3600 if (R->getEntry() == UseParent) {
3601 if (auto *PHI = dyn_cast<PHINode>(UI)) {
3602 bool ExternalUse = false;
3603 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
3604 if (PHI->getIncomingValue(i) == Inst &&
3605 !R->contains(PHI->getIncomingBlock(i))) {
3606 ExternalUse = true;
3607 break;
3608 }
3609 }
3610
3611 if (ExternalUse) {
3612 AnyCrossStmtUse = true;
3613 continue;
3614 }
3615 }
3616 }
3617
Michael Kruse7bf39442015-09-10 12:46:52 +00003618 // Do not build scalar dependences inside a non-affine subregion.
3619 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
3620 continue;
3621
Michael Kruse01cb3792015-10-17 21:07:08 +00003622 // Check for PHI nodes in the region exit and skip them, if they will be
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003623 // modeled as PHI nodes.
Michael Kruse01cb3792015-10-17 21:07:08 +00003624 //
3625 // PHI nodes in the region exit that have more than two incoming edges need
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003626 // to be modeled as PHI-Nodes to correctly model the fact that depending on
3627 // the control flow a different value will be assigned to the PHI node. In
3628 // case this is the case, there is no need to create an additional normal
3629 // scalar dependence. Hence, bail out before we register an "out-of-region"
3630 // use for this definition.
Michael Kruse01cb3792015-10-17 21:07:08 +00003631 if (isa<PHINode>(UI) && UI->getParent() == R->getExit() &&
3632 !R->getExitingBlock())
3633 continue;
3634
Michael Kruse7bf39442015-09-10 12:46:52 +00003635 // Check whether or not the use is in the SCoP.
Tobias Grosserc73d8b02015-10-23 22:36:22 +00003636 if (!R->contains(UseParent)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003637 AnyCrossStmtUse = true;
3638 continue;
3639 }
3640
3641 // If the instruction can be synthesized and the user is in the region
3642 // we do not need to add scalar dependences.
3643 if (canSynthesizeInst)
3644 continue;
3645
3646 // No need to translate these scalar dependences into polyhedral form,
3647 // because synthesizable scalars can be generated by the code generator.
3648 if (canSynthesize(UI, LI, SE, R))
3649 continue;
3650
3651 // Skip PHI nodes in the region as they handle their operands on their own.
3652 if (isa<PHINode>(UI))
3653 continue;
3654
3655 // Now U is used in another statement.
3656 AnyCrossStmtUse = true;
3657
3658 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00003659 // Use the def instruction as base address of the MemoryAccess, so that it
3660 // will become the name of the scalar access in the polyhedral form.
Michael Kruse34e11222015-12-13 22:47:43 +00003661 addValueReadAccess(Inst, UI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003662 }
3663
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003664 if (ModelReadOnlyScalars && !isa<PHINode>(Inst)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003665 for (Value *Op : Inst->operands()) {
3666 if (canSynthesize(Op, LI, SE, R))
3667 continue;
3668
3669 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
3670 if (R->contains(OpInst))
3671 continue;
3672
3673 if (isa<Constant>(Op))
3674 continue;
3675
Michael Kruse34e11222015-12-13 22:47:43 +00003676 addValueReadAccess(Op, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003677 }
3678 }
3679
3680 return AnyCrossStmtUse;
3681}
3682
3683extern MapInsnToMemAcc InsnToMemAcc;
3684
Michael Krusee2bccbb2015-09-18 19:59:43 +00003685void ScopInfo::buildMemoryAccess(
3686 Instruction *Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003687 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3688 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003689 unsigned Size;
3690 Type *SizeType;
3691 Value *Val;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003692 enum MemoryAccess::AccessType Type;
Michael Kruse7bf39442015-09-10 12:46:52 +00003693
3694 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
3695 SizeType = Load->getType();
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003696 Size = TD->getTypeAllocSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003697 Type = MemoryAccess::READ;
Michael Kruse7bf39442015-09-10 12:46:52 +00003698 Val = Load;
3699 } else {
3700 StoreInst *Store = cast<StoreInst>(Inst);
3701 SizeType = Store->getValueOperand()->getType();
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003702 Size = TD->getTypeAllocSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003703 Type = MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003704 Val = Store->getValueOperand();
3705 }
3706
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003707 auto Address = getPointerOperand(*Inst);
3708
3709 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003710 const SCEVUnknown *BasePointer =
3711 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3712
3713 assert(BasePointer && "Could not find base pointer");
3714 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
3715
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003716 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3717 auto NewAddress = Address;
3718 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3719 auto Src = BitCast->getOperand(0);
3720 auto SrcTy = Src->getType();
3721 auto DstTy = BitCast->getType();
3722 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3723 NewAddress = Src;
3724 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003725
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003726 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3727 std::vector<const SCEV *> Subscripts;
3728 std::vector<int> Sizes;
3729 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3730 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003731
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003732 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003733
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003734 bool AllAffineSubcripts = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003735 for (auto Subscript : Subscripts) {
3736 InvariantLoadsSetTy AccessILS;
3737 AllAffineSubcripts =
3738 isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS);
3739
3740 for (LoadInst *LInst : AccessILS)
3741 if (!ScopRIL.count(LInst))
3742 AllAffineSubcripts = false;
3743
3744 if (!AllAffineSubcripts)
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003745 break;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003746 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003747
3748 if (AllAffineSubcripts && Sizes.size() > 0) {
3749 for (auto V : Sizes)
3750 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3751 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003752 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003753 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003754
Tobias Grossera535dff2015-12-13 19:59:01 +00003755 addArrayAccess(Inst, Type, BasePointer->getValue(), Size, true,
3756 Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00003757 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003758 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003759 }
3760 }
3761
Michael Kruse7bf39442015-09-10 12:46:52 +00003762 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003763 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003764 addArrayAccess(Inst, Type, BasePointer->getValue(), Size, true,
3765 AccItr->second.DelinearizedSubscripts,
3766 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003767 return;
3768 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003769
3770 // Check if the access depends on a loop contained in a non-affine subregion.
3771 bool isVariantInNonAffineLoop = false;
3772 if (BoxedLoops) {
3773 SetVector<const Loop *> Loops;
3774 findLoops(AccessFunction, Loops);
3775 for (const Loop *L : Loops)
3776 if (BoxedLoops->count(L))
3777 isVariantInNonAffineLoop = true;
3778 }
3779
Johannes Doerfert09e36972015-10-07 20:17:36 +00003780 InvariantLoadsSetTy AccessILS;
3781 bool IsAffine =
3782 !isVariantInNonAffineLoop &&
3783 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3784
3785 for (LoadInst *LInst : AccessILS)
3786 if (!ScopRIL.count(LInst))
3787 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003788
Michael Krusecaac2b62015-09-26 15:51:44 +00003789 // FIXME: Size of the number of bytes of an array element, not the number of
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003790 // elements as probably intended here.
Tobias Grossera43b6e92015-09-27 17:54:50 +00003791 const SCEV *SizeSCEV =
3792 SE->getConstant(TD->getIntPtrType(Inst->getContext()), Size);
Michael Kruse7bf39442015-09-10 12:46:52 +00003793
Michael Krusee2bccbb2015-09-18 19:59:43 +00003794 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3795 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003796
Tobias Grossera535dff2015-12-13 19:59:01 +00003797 addArrayAccess(Inst, Type, BasePointer->getValue(), Size, IsAffine,
3798 ArrayRef<const SCEV *>(AccessFunction),
3799 ArrayRef<const SCEV *>(SizeSCEV), Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003800}
3801
Michael Krused868b5d2015-09-10 15:25:24 +00003802void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003803
3804 if (SD->isNonAffineSubRegion(&SR, &R)) {
3805 for (BasicBlock *BB : SR.blocks())
3806 buildAccessFunctions(R, *BB, &SR);
3807 return;
3808 }
3809
3810 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3811 if (I->isSubRegion())
3812 buildAccessFunctions(R, *I->getNodeAs<Region>());
3813 else
3814 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
3815}
3816
Michael Krusecac948e2015-10-02 13:53:07 +00003817void ScopInfo::buildStmts(Region &SR) {
3818 Region *R = getRegion();
3819
3820 if (SD->isNonAffineSubRegion(&SR, R)) {
3821 scop->addScopStmt(nullptr, &SR);
3822 return;
3823 }
3824
3825 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3826 if (I->isSubRegion())
3827 buildStmts(*I->getNodeAs<Region>());
3828 else
3829 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
3830}
3831
Michael Krused868b5d2015-09-10 15:25:24 +00003832void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
3833 Region *NonAffineSubRegion,
3834 bool IsExitBlock) {
Tobias Grosser910cf262015-11-11 20:15:49 +00003835 // We do not build access functions for error blocks, as they may contain
3836 // instructions we can not model.
3837 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3838 if (isErrorBlock(BB, R, *LI, DT) && !IsExitBlock)
3839 return;
3840
Michael Kruse7bf39442015-09-10 12:46:52 +00003841 Loop *L = LI->getLoopFor(&BB);
3842
3843 // The set of loops contained in non-affine subregions that are part of R.
3844 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3845
Johannes Doerfert09e36972015-10-07 20:17:36 +00003846 // The set of loads that are required to be invariant.
3847 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
3848
Michael Kruse7bf39442015-09-10 12:46:52 +00003849 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00003850 Instruction *Inst = &*I;
Michael Kruse7bf39442015-09-10 12:46:52 +00003851
3852 PHINode *PHI = dyn_cast<PHINode>(Inst);
3853 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003854 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003855
3856 // For the exit block we stop modeling after the last PHI node.
3857 if (!PHI && IsExitBlock)
3858 break;
3859
Johannes Doerfert09e36972015-10-07 20:17:36 +00003860 // TODO: At this point we only know that elements of ScopRIL have to be
3861 // invariant and will be hoisted for the SCoP to be processed. Though,
3862 // there might be other invariant accesses that will be hoisted and
3863 // that would allow to make a non-affine access affine.
Michael Kruse7bf39442015-09-10 12:46:52 +00003864 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
Johannes Doerfert09e36972015-10-07 20:17:36 +00003865 buildMemoryAccess(Inst, L, &R, BoxedLoops, ScopRIL);
Michael Kruse7bf39442015-09-10 12:46:52 +00003866
3867 if (isIgnoredIntrinsic(Inst))
3868 continue;
3869
Johannes Doerfert09e36972015-10-07 20:17:36 +00003870 // Do not build scalar dependences for required invariant loads as we will
3871 // hoist them later on anyway or drop the SCoP if we cannot.
3872 if (ScopRIL.count(dyn_cast<LoadInst>(Inst)))
3873 continue;
3874
Michael Kruse7bf39442015-09-10 12:46:52 +00003875 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00003876 if (!isa<StoreInst>(Inst))
Michael Kruse34e11222015-12-13 22:47:43 +00003877 addValueWriteAccess(Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003878 }
3879 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003880}
Michael Kruse7bf39442015-09-10 12:46:52 +00003881
Michael Kruse2d0ece92015-09-24 11:41:21 +00003882void ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3883 MemoryAccess::AccessType Type,
3884 Value *BaseAddress, unsigned ElemBytes,
3885 bool Affine, Value *AccessValue,
3886 ArrayRef<const SCEV *> Subscripts,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003887 ArrayRef<const SCEV *> Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00003888 ScopArrayInfo::MemoryKind Kind) {
Michael Krusecac948e2015-10-02 13:53:07 +00003889 ScopStmt *Stmt = scop->getStmtForBasicBlock(BB);
3890
3891 // Do not create a memory access for anything not in the SCoP. It would be
3892 // ignored anyway.
3893 if (!Stmt)
3894 return;
3895
Michael Krusee2bccbb2015-09-18 19:59:43 +00003896 AccFuncSetType &AccList = AccFuncMap[BB];
Michael Krusee2bccbb2015-09-18 19:59:43 +00003897 Value *BaseAddr = BaseAddress;
3898 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3899
Tobias Grosserf4f68702015-12-14 15:05:37 +00003900 bool isKnownMustAccess = false;
3901
3902 // Accesses in single-basic block statements are always excuted.
3903 if (Stmt->isBlockStmt())
3904 isKnownMustAccess = true;
3905
3906 if (Stmt->isRegionStmt()) {
3907 // Accesses that dominate the exit block of a non-affine region are always
3908 // executed. In non-affine regions there may exist MK_Values that do not
3909 // dominate the exit. MK_Values will always dominate the exit and MK_PHIs
3910 // only if there is at most one PHI_WRITE in the non-affine region.
3911 if (DT->dominates(BB, Stmt->getRegion()->getExit()))
3912 isKnownMustAccess = true;
3913 }
3914
3915 if (!isKnownMustAccess && Type == MemoryAccess::MUST_WRITE)
Michael Krusecac948e2015-10-02 13:53:07 +00003916 Type = MemoryAccess::MAY_WRITE;
3917
Tobias Grosserf1bfd752015-11-05 20:15:37 +00003918 AccList.emplace_back(Stmt, Inst, Type, BaseAddress, ElemBytes, Affine,
Tobias Grossera535dff2015-12-13 19:59:01 +00003919 Subscripts, Sizes, AccessValue, Kind, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00003920 Stmt->addAccess(&AccList.back());
Michael Kruse7bf39442015-09-10 12:46:52 +00003921}
3922
Tobias Grossera535dff2015-12-13 19:59:01 +00003923void ScopInfo::addArrayAccess(Instruction *MemAccInst,
3924 MemoryAccess::AccessType Type, Value *BaseAddress,
3925 unsigned ElemBytes, bool IsAffine,
3926 ArrayRef<const SCEV *> Subscripts,
3927 ArrayRef<const SCEV *> Sizes,
3928 Value *AccessValue) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003929 assert(isa<LoadInst>(MemAccInst) || isa<StoreInst>(MemAccInst));
3930 assert(isa<LoadInst>(MemAccInst) == (Type == MemoryAccess::READ));
3931 addMemoryAccess(MemAccInst->getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003932 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00003933 ScopArrayInfo::MK_Array);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003934}
Michael Kruse34e11222015-12-13 22:47:43 +00003935void ScopInfo::addValueWriteAccess(Instruction *Value) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003936 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
3937 true, Value, ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00003938 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003939}
Michael Kruse34e11222015-12-13 22:47:43 +00003940void ScopInfo::addValueReadAccess(Value *Value, Instruction *User) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003941 assert(!isa<PHINode>(User));
3942 addMemoryAccess(User->getParent(), User, MemoryAccess::READ, Value, 1, true,
3943 Value, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00003944 ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003945}
Michael Kruse34e11222015-12-13 22:47:43 +00003946void ScopInfo::addValueReadAccess(Value *Value, PHINode *User,
3947 BasicBlock *UserBB) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003948 addMemoryAccess(UserBB, User, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003949 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00003950 ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003951}
3952void ScopInfo::addPHIWriteAccess(PHINode *PHI, BasicBlock *IncomingBlock,
3953 Value *IncomingValue, bool IsExitBlock) {
3954 addMemoryAccess(IncomingBlock, IncomingBlock->getTerminator(),
3955 MemoryAccess::MUST_WRITE, PHI, 1, true, IncomingValue,
3956 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00003957 IsExitBlock ? ScopArrayInfo::MK_ExitPHI
3958 : ScopArrayInfo::MK_PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003959}
3960void ScopInfo::addPHIReadAccess(PHINode *PHI) {
3961 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003962 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00003963 ScopArrayInfo::MK_PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003964}
3965
Michael Krusedaf66942015-12-13 22:10:37 +00003966void ScopInfo::buildScop(Region &R, AssumptionCache &AC) {
Michael Kruse9d080092015-09-11 21:41:48 +00003967 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Michael Krusedaf66942015-12-13 22:10:37 +00003968 scop = new Scop(R, AccFuncMap, *SD, *SE, *DT, *LI, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00003969
Michael Krusecac948e2015-10-02 13:53:07 +00003970 buildStmts(R);
Michael Kruse7bf39442015-09-10 12:46:52 +00003971 buildAccessFunctions(R, R);
3972
3973 // In case the region does not have an exiting block we will later (during
3974 // code generation) split the exit block. This will move potential PHI nodes
3975 // from the current exit block into the new region exiting block. Hence, PHI
3976 // nodes that are at this point not part of the region will be.
3977 // To handle these PHI nodes later we will now model their operands as scalar
3978 // accesses. Note that we do not model anything in the exit block if we have
3979 // an exiting block in the region, as there will not be any splitting later.
3980 if (!R.getExitingBlock())
3981 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
3982
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003983 scop->init(*AA, AC);
Michael Kruse7bf39442015-09-10 12:46:52 +00003984}
3985
Michael Krused868b5d2015-09-10 15:25:24 +00003986void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00003987 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00003988 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00003989 return;
3990 }
3991
Michael Kruse9d080092015-09-11 21:41:48 +00003992 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00003993}
3994
Michael Krused868b5d2015-09-10 15:25:24 +00003995void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00003996 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00003997 if (scop) {
3998 delete scop;
3999 scop = 0;
4000 }
Michael Kruse7bf39442015-09-10 12:46:52 +00004001}
4002
4003//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00004004ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00004005 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00004006 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00004007}
4008
4009ScopInfo::~ScopInfo() {
4010 clear();
4011 isl_ctx_free(ctx);
4012}
4013
Tobias Grosser75805372011-04-29 06:27:02 +00004014void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00004015 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00004016 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00004017 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00004018 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4019 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004020 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004021 AU.addRequired<AssumptionCacheTracker>();
Tobias Grosser75805372011-04-29 06:27:02 +00004022 AU.setPreservesAll();
4023}
4024
4025bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00004026 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00004027
Michael Krused868b5d2015-09-10 15:25:24 +00004028 if (!SD->isMaxRegionInScop(*R))
4029 return false;
4030
4031 Function *F = R->getEntry()->getParent();
4032 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4033 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4034 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
4035 TD = &F->getParent()->getDataLayout();
Michael Krusedaf66942015-12-13 22:10:37 +00004036 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004037 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krused868b5d2015-09-10 15:25:24 +00004038
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004039 DebugLoc Beg, End;
4040 getDebugLocations(R, Beg, End);
4041 std::string Msg = "SCoP begins here.";
4042 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg);
4043
Michael Krusedaf66942015-12-13 22:10:37 +00004044 buildScop(*R, AC);
Tobias Grosser75805372011-04-29 06:27:02 +00004045
Tobias Grosserd6a50b32015-05-30 06:26:21 +00004046 DEBUG(scop->print(dbgs()));
4047
Michael Kruseafe06702015-10-02 16:33:27 +00004048 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004049 Msg = "SCoP ends here but was dismissed.";
Johannes Doerfert43788c52015-08-20 05:58:56 +00004050 delete scop;
4051 scop = nullptr;
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004052 } else {
4053 Msg = "SCoP ends here.";
4054 ++ScopFound;
4055 if (scop->getMaxLoopDepth() > 0)
4056 ++RichScopFound;
Johannes Doerfert43788c52015-08-20 05:58:56 +00004057 }
4058
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004059 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg);
4060
Tobias Grosser75805372011-04-29 06:27:02 +00004061 return false;
4062}
4063
4064char ScopInfo::ID = 0;
4065
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004066Pass *polly::createScopInfoPass() { return new ScopInfo(); }
4067
Tobias Grosser73600b82011-10-08 00:30:40 +00004068INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
4069 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004070 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004071INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004072INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004073INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004074INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004075INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004076INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004077INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00004078INITIALIZE_PASS_END(ScopInfo, "polly-scops",
4079 "Polly - Create polyhedral description of Scops", false,
4080 false)