blob: ec90ccb6962543f9ff9ca2a4f09916d29451ad97 [file] [log] [blame]
Johannes Doerfert58a7c752015-09-28 09:48:53 +00001//===--------- ScopInfo.cpp - Create Scops from LLVM IR ------------------===//
Tobias Grosser75805372011-04-29 06:27:02 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Create a polyhedral description for a static control flow region.
11//
12// The pass creates a polyhedral description of the Scops detected by the Scop
13// detection derived from their LLVM-IR code.
14//
Tobias Grossera5605d32014-10-29 19:58:28 +000015// This representation is shared among several tools in the polyhedral
Tobias Grosser75805372011-04-29 06:27:02 +000016// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
Tobias Grosser75805372011-04-29 06:27:02 +000020#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000021#include "polly/Options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000022#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000023#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000024#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000025#include "polly/Support/ScopHelper.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000026#include "llvm/ADT/MapVector.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000027#include "llvm/ADT/PostOrderIterator.h"
28#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000029#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000030#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000031#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000032#include "llvm/Analysis/AliasAnalysis.h"
Johannes Doerfert2af10e22015-11-12 03:25:01 +000033#include "llvm/Analysis/AssumptionCache.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000034#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000035#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000036#include "llvm/Analysis/RegionIterator.h"
37#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Johannes Doerfert48fe86f2015-11-12 02:32:32 +000038#include "llvm/IR/DiagnosticInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000039#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000040#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000041#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000042#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000043#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000044#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000045#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000046#include "isl/schedule.h"
47#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000048#include "isl/set.h"
49#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000050#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000051#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000052#include <sstream>
53#include <string>
54#include <vector>
55
56using namespace llvm;
57using namespace polly;
58
Chandler Carruth95fef942014-04-22 03:30:19 +000059#define DEBUG_TYPE "polly-scops"
60
Tobias Grosser74394f02013-01-14 22:40:23 +000061STATISTIC(ScopFound, "Number of valid Scops");
62STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000063
Michael Kruse7bf39442015-09-10 12:46:52 +000064static cl::opt<bool> ModelReadOnlyScalars(
65 "polly-analyze-read-only-scalars",
66 cl::desc("Model read-only scalar values in the scop description"),
67 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
68
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000069// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000070// operations can overflow easily. Additive reductions and bit operations
71// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000072static cl::opt<bool> DisableMultiplicativeReductions(
73 "polly-disable-multiplicative-reductions",
74 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
75 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000076
Johannes Doerfert9143d672014-09-27 11:02:39 +000077static cl::opt<unsigned> RunTimeChecksMaxParameters(
78 "polly-rtc-max-parameters",
79 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
80 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
81
Tobias Grosser71500722015-03-28 15:11:14 +000082static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
83 "polly-rtc-max-arrays-per-group",
84 cl::desc("The maximal number of arrays to compare in each alias group."),
85 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000086static cl::opt<std::string> UserContextStr(
87 "polly-context", cl::value_desc("isl parameter set"),
88 cl::desc("Provide additional constraints on the context parameters"),
89 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000090
Tobias Grosserd83b8a82015-08-20 19:08:11 +000091static cl::opt<bool> DetectReductions("polly-detect-reductions",
92 cl::desc("Detect and exploit reductions"),
93 cl::Hidden, cl::ZeroOrMore,
94 cl::init(true), cl::cat(PollyCategory));
95
Tobias Grosser20a4c0c2015-11-11 16:22:36 +000096static cl::opt<int> MaxDisjunctsAssumed(
97 "polly-max-disjuncts-assumed",
98 cl::desc("The maximal number of disjuncts we allow in the assumption "
99 "context (this bounds compile time)"),
100 cl::Hidden, cl::ZeroOrMore, cl::init(150), cl::cat(PollyCategory));
101
Michael Kruse7bf39442015-09-10 12:46:52 +0000102//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000103
Michael Kruse046dde42015-08-10 13:01:57 +0000104// Create a sequence of two schedules. Either argument may be null and is
105// interpreted as the empty schedule. Can also return null if both schedules are
106// empty.
107static __isl_give isl_schedule *
108combineInSequence(__isl_take isl_schedule *Prev,
109 __isl_take isl_schedule *Succ) {
110 if (!Prev)
111 return Succ;
112 if (!Succ)
113 return Prev;
114
115 return isl_schedule_sequence(Prev, Succ);
116}
117
Johannes Doerferte7044942015-02-24 11:58:30 +0000118static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
119 const ConstantRange &Range,
120 int dim,
121 enum isl_dim_type type) {
122 isl_val *V;
123 isl_ctx *ctx = isl_set_get_ctx(S);
124
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000125 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
126 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000127 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000128 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
129
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000130 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000131 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000132 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000133 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000134 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
135
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000136 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000137 return isl_set_union(SLB, SUB);
138 else
139 return isl_set_intersect(SLB, SUB);
140}
141
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000142static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
143 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
144 if (!BasePtrLI)
145 return nullptr;
146
147 if (!S->getRegion().contains(BasePtrLI))
148 return nullptr;
149
150 ScalarEvolution &SE = *S->getSE();
151
152 auto *OriginBaseSCEV =
153 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
154 if (!OriginBaseSCEV)
155 return nullptr;
156
157 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
158 if (!OriginBaseSCEVUnknown)
159 return nullptr;
160
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000161 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
162 ScopArrayInfo::KIND_ARRAY);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000163}
164
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000165ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000166 ArrayRef<const SCEV *> Sizes, enum ARRAYKIND Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000167 const DataLayout &DL, Scop *S)
168 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000169 std::string BasePtrName =
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000170 getIslCompatibleName("MemRef_", BasePtr, Kind == KIND_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000171 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000172
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000173 updateSizes(Sizes);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000174 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
175 if (BasePtrOriginSAI)
176 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000177}
178
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000179__isl_give isl_space *ScopArrayInfo::getSpace() const {
180 auto Space =
181 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
182 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
183 return Space;
184}
185
Tobias Grosser8286b832015-11-02 11:29:32 +0000186bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000187 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
188 int ExtraDimsNew = NewSizes.size() - SharedDims;
189 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Tobias Grosser8286b832015-11-02 11:29:32 +0000190 for (int i = 0; i < SharedDims; i++)
191 if (NewSizes[i + ExtraDimsNew] != DimensionSizes[i + ExtraDimsOld])
192 return false;
193
194 if (DimensionSizes.size() >= NewSizes.size())
195 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000196
197 DimensionSizes.clear();
198 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
199 NewSizes.end());
200 for (isl_pw_aff *Size : DimensionSizesPw)
201 isl_pw_aff_free(Size);
202 DimensionSizesPw.clear();
203 for (const SCEV *Expr : DimensionSizes) {
204 isl_pw_aff *Size = S.getPwAff(Expr);
205 DimensionSizesPw.push_back(Size);
206 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000207 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000208}
209
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000210ScopArrayInfo::~ScopArrayInfo() {
211 isl_id_free(Id);
212 for (isl_pw_aff *Size : DimensionSizesPw)
213 isl_pw_aff_free(Size);
214}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000215
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000216std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
217
218int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000219 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000220}
221
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000222isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
223
224void ScopArrayInfo::dump() const { print(errs()); }
225
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000226void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000227 OS.indent(8) << *getElementType() << " " << getName();
228 if (getNumberOfDimensions() > 0)
229 OS << "[*]";
Tobias Grosser26253842015-11-10 14:24:21 +0000230 for (unsigned u = 1; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000231 OS << "[";
232
Tobias Grosser26253842015-11-10 14:24:21 +0000233 if (SizeAsPwAff) {
234 auto Size = getDimensionSizePw(u);
235 OS << " " << Size << " ";
236 isl_pw_aff_free(Size);
237 } else {
238 OS << *getDimensionSize(u);
239 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000240
241 OS << "]";
242 }
243
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000244 OS << ";";
245
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000246 if (BasePtrOriginSAI)
247 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
248
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000249 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000250}
251
252const ScopArrayInfo *
253ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
254 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
255 assert(Id && "Output dimension didn't have an ID");
256 return getFromId(Id);
257}
258
259const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
260 void *User = isl_id_get_user(Id);
261 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
262 isl_id_free(Id);
263 return SAI;
264}
265
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000266void MemoryAccess::updateDimensionality() {
267 auto ArraySpace = getScopArrayInfo()->getSpace();
268 auto AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
269
270 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
271 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
272 auto DimsMissing = DimsArray - DimsAccess;
273
274 auto Map = isl_map_from_domain_and_range(isl_set_universe(AccessSpace),
275 isl_set_universe(ArraySpace));
276
277 for (unsigned i = 0; i < DimsMissing; i++)
278 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
279
280 for (unsigned i = DimsMissing; i < DimsArray; i++)
281 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
282
283 AccessRelation = isl_map_apply_range(AccessRelation, Map);
284}
285
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000286const std::string
287MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
288 switch (RT) {
289 case MemoryAccess::RT_NONE:
290 llvm_unreachable("Requested a reduction operator string for a memory "
291 "access which isn't a reduction");
292 case MemoryAccess::RT_ADD:
293 return "+";
294 case MemoryAccess::RT_MUL:
295 return "*";
296 case MemoryAccess::RT_BOR:
297 return "|";
298 case MemoryAccess::RT_BXOR:
299 return "^";
300 case MemoryAccess::RT_BAND:
301 return "&";
302 }
303 llvm_unreachable("Unknown reduction type");
304 return "";
305}
306
Johannes Doerfertf6183392014-07-01 20:52:51 +0000307/// @brief Return the reduction type for a given binary operator
308static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
309 const Instruction *Load) {
310 if (!BinOp)
311 return MemoryAccess::RT_NONE;
312 switch (BinOp->getOpcode()) {
313 case Instruction::FAdd:
314 if (!BinOp->hasUnsafeAlgebra())
315 return MemoryAccess::RT_NONE;
316 // Fall through
317 case Instruction::Add:
318 return MemoryAccess::RT_ADD;
319 case Instruction::Or:
320 return MemoryAccess::RT_BOR;
321 case Instruction::Xor:
322 return MemoryAccess::RT_BXOR;
323 case Instruction::And:
324 return MemoryAccess::RT_BAND;
325 case Instruction::FMul:
326 if (!BinOp->hasUnsafeAlgebra())
327 return MemoryAccess::RT_NONE;
328 // Fall through
329 case Instruction::Mul:
330 if (DisableMultiplicativeReductions)
331 return MemoryAccess::RT_NONE;
332 return MemoryAccess::RT_MUL;
333 default:
334 return MemoryAccess::RT_NONE;
335 }
336}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000337
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000338/// @brief Derive the individual index expressions from a GEP instruction
339///
340/// This function optimistically assumes the GEP references into a fixed size
341/// array. If this is actually true, this function returns a list of array
342/// subscript expressions as SCEV as well as a list of integers describing
343/// the size of the individual array dimensions. Both lists have either equal
344/// length of the size list is one element shorter in case there is no known
345/// size available for the outermost array dimension.
346///
347/// @param GEP The GetElementPtr instruction to analyze.
348///
349/// @return A tuple with the subscript expressions and the dimension sizes.
350static std::tuple<std::vector<const SCEV *>, std::vector<int>>
351getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
352 std::vector<const SCEV *> Subscripts;
353 std::vector<int> Sizes;
354
355 Type *Ty = GEP->getPointerOperandType();
356
357 bool DroppedFirstDim = false;
358
Michael Kruse26ed65e2015-09-24 17:32:49 +0000359 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000360
361 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
362
363 if (i == 1) {
364 if (auto PtrTy = dyn_cast<PointerType>(Ty)) {
365 Ty = PtrTy->getElementType();
366 } else if (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
367 Ty = ArrayTy->getElementType();
368 } else {
369 Subscripts.clear();
370 Sizes.clear();
371 break;
372 }
373 if (auto Const = dyn_cast<SCEVConstant>(Expr))
374 if (Const->getValue()->isZero()) {
375 DroppedFirstDim = true;
376 continue;
377 }
378 Subscripts.push_back(Expr);
379 continue;
380 }
381
382 auto ArrayTy = dyn_cast<ArrayType>(Ty);
383 if (!ArrayTy) {
384 Subscripts.clear();
385 Sizes.clear();
386 break;
387 }
388
389 Subscripts.push_back(Expr);
390 if (!(DroppedFirstDim && i == 2))
391 Sizes.push_back(ArrayTy->getNumElements());
392
393 Ty = ArrayTy->getElementType();
394 }
395
396 return std::make_tuple(Subscripts, Sizes);
397}
398
Tobias Grosser75805372011-04-29 06:27:02 +0000399MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000400 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000401 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000402 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000403}
404
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000405const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
406 isl_id *ArrayId = getArrayId();
407 void *User = isl_id_get_user(ArrayId);
408 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
409 isl_id_free(ArrayId);
410 return SAI;
411}
412
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000413__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000414 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
415}
416
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000417__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
418 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000419 isl_map *Schedule, *ScheduledAccRel;
420 isl_union_set *UDomain;
421
422 UDomain = isl_union_set_from_set(getStatement()->getDomain());
423 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
424 Schedule = isl_map_from_union_map(USchedule);
425 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
426 return isl_pw_multi_aff_from_map(ScheduledAccRel);
427}
428
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000429__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000430 return isl_map_copy(AccessRelation);
431}
432
Johannes Doerferta99130f2014-10-13 12:58:03 +0000433std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000434 return stringFromIslObj(AccessRelation);
435}
436
Johannes Doerferta99130f2014-10-13 12:58:03 +0000437__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000438 return isl_map_get_space(AccessRelation);
439}
440
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000441__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000442 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000443}
444
Tobias Grosser6f730082015-09-05 07:46:47 +0000445std::string MemoryAccess::getNewAccessRelationStr() const {
446 return stringFromIslObj(NewAccessRelation);
447}
448
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000449__isl_give isl_basic_map *
450MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000451 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000452 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000453
Tobias Grosser084d8f72012-05-29 09:29:44 +0000454 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000455 isl_basic_set_universe(Statement->getDomainSpace()),
456 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000457}
458
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000459// Formalize no out-of-bound access assumption
460//
461// When delinearizing array accesses we optimistically assume that the
462// delinearized accesses do not access out of bound locations (the subscript
463// expression of each array evaluates for each statement instance that is
464// executed to a value that is larger than zero and strictly smaller than the
465// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000466// dimension for which we do not need to assume any upper bound. At this point
467// we formalize this assumption to ensure that at code generation time the
468// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000469//
470// To find the set of constraints necessary to avoid out of bound accesses, we
471// first build the set of data locations that are not within array bounds. We
472// then apply the reverse access relation to obtain the set of iterations that
473// may contain invalid accesses and reduce this set of iterations to the ones
474// that are actually executed by intersecting them with the domain of the
475// statement. If we now project out all loop dimensions, we obtain a set of
476// parameters that may cause statement instances to be executed that may
477// possibly yield out of bound memory accesses. The complement of these
478// constraints is the set of constraints that needs to be assumed to ensure such
479// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000480void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000481 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000482 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Michael Krusee2bccbb2015-09-18 19:59:43 +0000483 for (int i = 1, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000484 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
485 isl_pw_aff *Var =
486 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
487 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
488
489 isl_set *DimOutside;
490
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000491 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Michael Krusee2bccbb2015-09-18 19:59:43 +0000492 isl_pw_aff *SizeE = Statement->getPwAff(Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000493
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000494 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
495 Statement->getNumIterators());
496 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
497 isl_space_dim(Space, isl_dim_set));
498 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
499 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000500
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000501 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000502
503 Outside = isl_set_union(Outside, DimOutside);
504 }
505
506 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
507 Outside = isl_set_intersect(Outside, Statement->getDomain());
508 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000509
510 // Remove divs to avoid the construction of overly complicated assumptions.
511 // Doing so increases the set of parameter combinations that are assumed to
512 // not appear. This is always save, but may make the resulting run-time check
513 // bail out more often than strictly necessary.
514 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000515 Outside = isl_set_complement(Outside);
Johannes Doerfertd84493e2015-11-12 02:33:38 +0000516 Statement->getParent()->addAssumption(INBOUNDS, Outside,
517 getAccessInstruction()->getDebugLoc());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000518 isl_space_free(Space);
519}
520
Johannes Doerferte7044942015-02-24 11:58:30 +0000521void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
522 ScalarEvolution *SE = Statement->getParent()->getSE();
523
524 Value *Ptr = getPointerOperand(*getAccessInstruction());
525 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
526 return;
527
528 auto *PtrSCEV = SE->getSCEV(Ptr);
529 if (isa<SCEVCouldNotCompute>(PtrSCEV))
530 return;
531
532 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
533 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
534 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
535
536 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
537 if (Range.isFullSet())
538 return;
539
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000540 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000541 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000542 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
543 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
544
545 auto Min = LB.sdiv(APInt(BW, ElementSize));
546 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000547
548 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
549 AccessRange =
550 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
551 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
552}
553
Michael Krusee2bccbb2015-09-18 19:59:43 +0000554__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000555 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000556 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000557
558 for (int i = Size - 2; i >= 0; --i) {
559 isl_space *Space;
560 isl_map *MapOne, *MapTwo;
Michael Krusee2bccbb2015-09-18 19:59:43 +0000561 isl_pw_aff *DimSize = Statement->getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000562
563 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
564 isl_pw_aff_free(DimSize);
565 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
566
567 Space = isl_map_get_space(AccessRelation);
568 Space = isl_space_map_from_set(isl_space_range(Space));
569 Space = isl_space_align_params(Space, SpaceSize);
570
571 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
572 isl_id_free(ParamId);
573
574 MapOne = isl_map_universe(isl_space_copy(Space));
575 for (int j = 0; j < Size; ++j)
576 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
577 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
578
579 MapTwo = isl_map_universe(isl_space_copy(Space));
580 for (int j = 0; j < Size; ++j)
581 if (j < i || j > i + 1)
582 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
583
584 isl_local_space *LS = isl_local_space_from_space(Space);
585 isl_constraint *C;
586 C = isl_equality_alloc(isl_local_space_copy(LS));
587 C = isl_constraint_set_constant_si(C, -1);
588 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
589 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
590 MapTwo = isl_map_add_constraint(MapTwo, C);
591 C = isl_equality_alloc(LS);
592 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
593 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
594 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
595 MapTwo = isl_map_add_constraint(MapTwo, C);
596 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
597
598 MapOne = isl_map_union(MapOne, MapTwo);
599 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
600 }
601 return AccessRelation;
602}
603
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000604/// @brief Check if @p Expr is divisible by @p Size.
605static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
606
607 // Only one factor needs to be divisible.
608 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
609 for (auto *FactorExpr : MulExpr->operands())
610 if (isDivisible(FactorExpr, Size, SE))
611 return true;
612 return false;
613 }
614
615 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
616 // to be divisble.
617 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
618 for (auto *OpExpr : NAryExpr->operands())
619 if (!isDivisible(OpExpr, Size, SE))
620 return false;
621 return true;
622 }
623
624 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
625 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
626 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
627 return MulSCEV == Expr;
628}
629
Michael Krusee2bccbb2015-09-18 19:59:43 +0000630void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
631 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000632
Michael Krusee2bccbb2015-09-18 19:59:43 +0000633 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000634 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000635
Michael Krusee2bccbb2015-09-18 19:59:43 +0000636 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000637 // We overapproximate non-affine accesses with a possible access to the
638 // whole array. For read accesses it does not make a difference, if an
639 // access must or may happen. However, for write accesses it is important to
640 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000641 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000642 AccessRelation =
643 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000644
Michael Krusee2bccbb2015-09-18 19:59:43 +0000645 computeBoundsOnAccessRelation(getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000646 return;
647 }
648
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000649 Scop &S = *getStatement()->getParent();
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000650 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000651 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000652
Michael Krusee2bccbb2015-09-18 19:59:43 +0000653 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
654 isl_pw_aff *Affine = Statement->getPwAff(Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000655
Sebastian Pop422e33f2014-06-03 18:16:31 +0000656 if (Size == 1) {
657 // For the non delinearized arrays, divide the access function of the last
658 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000659 //
660 // A stride one array access in C expressed as A[i] is expressed in
661 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
662 // two subsequent values of 'i' index two values that are stored next to
663 // each other in memory. By this division we make this characteristic
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000664 // obvious again. However, if the index is not divisible by the element
665 // size we will bail out.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000666 isl_val *v = isl_val_int_from_si(Ctx, getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000667 Affine = isl_pw_aff_scale_down_val(Affine, v);
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000668
669 if (!isDivisible(Subscripts[0], getElemSizeInBytes(), *S.getSE()))
670 S.addAssumption(ALIGNMENT, isl_set_empty(S.getParamSpace()),
671 AccessInstruction->getDebugLoc());
Sebastian Pop18016682014-04-08 21:20:44 +0000672 }
673
674 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
675
Tobias Grosser79baa212014-04-10 08:38:02 +0000676 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000677 }
678
Michael Krusee2bccbb2015-09-18 19:59:43 +0000679 if (Sizes.size() > 1 && !isa<SCEVConstant>(Sizes[0]))
680 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000681
Tobias Grosser79baa212014-04-10 08:38:02 +0000682 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000683 AccessRelation = isl_map_set_tuple_id(
684 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000685 AccessRelation =
686 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
687
Michael Krusee2bccbb2015-09-18 19:59:43 +0000688 assumeNoOutOfBound();
Tobias Grosseraa660a92015-03-30 00:07:50 +0000689 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000690 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000691}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000692
Michael Krusecac948e2015-10-02 13:53:07 +0000693MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000694 AccessType Type, Value *BaseAddress,
695 unsigned ElemBytes, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000696 ArrayRef<const SCEV *> Subscripts,
697 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Michael Kruse8d0b7342015-09-25 21:21:00 +0000698 AccessOrigin Origin, StringRef BaseName)
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000699 : Origin(Origin), AccType(Type), RedType(RT_NONE), Statement(Stmt),
Michael Krusecac948e2015-10-02 13:53:07 +0000700 BaseAddr(BaseAddress), BaseName(BaseName), ElemBytes(ElemBytes),
701 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
702 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000703 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000704 NewAccessRelation(nullptr) {
705
706 std::string IdName = "__polly_array_ref";
707 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
708}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000709
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000710void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000711 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000712 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000713}
714
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000715const std::string MemoryAccess::getReductionOperatorStr() const {
716 return MemoryAccess::getReductionOperatorStr(getReductionType());
717}
718
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000719__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
720
Johannes Doerfertf6183392014-07-01 20:52:51 +0000721raw_ostream &polly::operator<<(raw_ostream &OS,
722 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000723 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000724 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000725 else
726 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000727 return OS;
728}
729
Tobias Grosser75805372011-04-29 06:27:02 +0000730void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000731 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000732 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000733 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000734 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000735 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000736 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000737 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000738 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000739 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000740 break;
741 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000742 OS << "[Reduction Type: " << getReductionType() << "] ";
Michael Kruse8d0b7342015-09-25 21:21:00 +0000743 OS << "[Scalar: " << isImplicit() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000744 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000745 if (hasNewAccessRelation())
746 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000747}
748
Tobias Grosser74394f02013-01-14 22:40:23 +0000749void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000750
751// Create a map in the size of the provided set domain, that maps from the
752// one element of the provided set domain to another element of the provided
753// set domain.
754// The mapping is limited to all points that are equal in all but the last
755// dimension and for which the last dimension of the input is strict smaller
756// than the last dimension of the output.
757//
758// getEqualAndLarger(set[i0, i1, ..., iX]):
759//
760// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
761// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
762//
Tobias Grosserf5338802011-10-06 00:03:35 +0000763static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000764 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000765 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000766 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000767
768 // Set all but the last dimension to be equal for the input and output
769 //
770 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
771 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000772 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000773 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000774
775 // Set the last dimension of the input to be strict smaller than the
776 // last dimension of the output.
777 //
778 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000779 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
780 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000781 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000782}
783
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000784__isl_give isl_set *
785MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000786 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000787 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000788 isl_space *Space = isl_space_range(isl_map_get_space(S));
789 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000790
Sebastian Popa00a0292012-12-18 07:46:06 +0000791 S = isl_map_reverse(S);
792 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000793
Sebastian Popa00a0292012-12-18 07:46:06 +0000794 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
795 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
796 NextScatt = isl_map_apply_domain(NextScatt, S);
797 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000798
Sebastian Popa00a0292012-12-18 07:46:06 +0000799 isl_set *Deltas = isl_map_deltas(NextScatt);
800 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000801}
802
Sebastian Popa00a0292012-12-18 07:46:06 +0000803bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000804 int StrideWidth) const {
805 isl_set *Stride, *StrideX;
806 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000807
Sebastian Popa00a0292012-12-18 07:46:06 +0000808 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000809 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000810 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
811 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
812 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
813 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000814 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000815
Tobias Grosser28dd4862012-01-24 16:42:16 +0000816 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000817 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000818
Tobias Grosser28dd4862012-01-24 16:42:16 +0000819 return IsStrideX;
820}
821
Sebastian Popa00a0292012-12-18 07:46:06 +0000822bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
823 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000824}
825
Sebastian Popa00a0292012-12-18 07:46:06 +0000826bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
827 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000828}
829
Tobias Grosser166c4222015-09-05 07:46:40 +0000830void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
831 isl_map_free(NewAccessRelation);
832 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000833}
Tobias Grosser75805372011-04-29 06:27:02 +0000834
835//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000836
Tobias Grosser808cd692015-07-14 09:33:13 +0000837isl_map *ScopStmt::getSchedule() const {
838 isl_set *Domain = getDomain();
839 if (isl_set_is_empty(Domain)) {
840 isl_set_free(Domain);
841 return isl_map_from_aff(
842 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
843 }
844 auto *Schedule = getParent()->getSchedule();
845 Schedule = isl_union_map_intersect_domain(
846 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
847 if (isl_union_map_is_empty(Schedule)) {
848 isl_set_free(Domain);
849 isl_union_map_free(Schedule);
850 return isl_map_from_aff(
851 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
852 }
853 auto *M = isl_map_from_union_map(Schedule);
854 M = isl_map_coalesce(M);
855 M = isl_map_gist_domain(M, Domain);
856 M = isl_map_coalesce(M);
857 return M;
858}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000859
Johannes Doerfert574182d2015-08-12 10:19:50 +0000860__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000861 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
862 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000863}
864
Tobias Grosser37eb4222014-02-20 21:43:54 +0000865void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
866 assert(isl_set_is_subset(NewDomain, Domain) &&
867 "New domain is not a subset of old domain!");
868 isl_set_free(Domain);
869 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000870}
871
Michael Krusecac948e2015-10-02 13:53:07 +0000872void ScopStmt::buildAccessRelations() {
873 for (MemoryAccess *Access : MemAccs) {
874 Type *ElementType = Access->getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000875
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000876 ScopArrayInfo::ARRAYKIND Ty;
877 if (Access->isPHI())
878 Ty = ScopArrayInfo::KIND_PHI;
879 else if (Access->isImplicit())
880 Ty = ScopArrayInfo::KIND_SCALAR;
881 else
882 Ty = ScopArrayInfo::KIND_ARRAY;
883
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000884 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000885 Access->getBaseAddr(), ElementType, Access->Sizes, Ty);
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000886
Michael Krusecac948e2015-10-02 13:53:07 +0000887 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +0000888 }
889}
890
Michael Krusecac948e2015-10-02 13:53:07 +0000891void ScopStmt::addAccess(MemoryAccess *Access) {
892 Instruction *AccessInst = Access->getAccessInstruction();
893
894 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
895 if (!MAL)
896 MAL = new MemoryAccessList();
897 MAL->emplace_front(Access);
898 MemAccs.push_back(MAL->front());
899}
900
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000901void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000902 for (MemoryAccess *MA : *this)
903 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000904
905 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000906}
907
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000908/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
909static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
910 void *User) {
911 isl_set **BoundedParts = static_cast<isl_set **>(User);
912 if (isl_basic_set_is_bounded(BSet))
913 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
914 else
915 isl_basic_set_free(BSet);
916 return isl_stat_ok;
917}
918
919/// @brief Return the bounded parts of @p S.
920static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
921 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
922 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
923 isl_set_free(S);
924 return BoundedParts;
925}
926
927/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
928///
929/// @returns A separation of @p S into first an unbounded then a bounded subset,
930/// both with regards to the dimension @p Dim.
931static std::pair<__isl_give isl_set *, __isl_give isl_set *>
932partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
933
934 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000935 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000936
937 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000938 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000939
940 // Remove dimensions that are greater than Dim as they are not interesting.
941 assert(NumDimsS >= Dim + 1);
942 OnlyDimS =
943 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
944
945 // Create artificial parametric upper bounds for dimensions smaller than Dim
946 // as we are not interested in them.
947 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
948 for (unsigned u = 0; u < Dim; u++) {
949 isl_constraint *C = isl_inequality_alloc(
950 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
951 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
952 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
953 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
954 }
955
956 // Collect all bounded parts of OnlyDimS.
957 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
958
959 // Create the dimensions greater than Dim again.
960 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
961 NumDimsS - Dim - 1);
962
963 // Remove the artificial upper bound parameters again.
964 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
965
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000966 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000967 return std::make_pair(UnboundedParts, BoundedParts);
968}
969
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000970/// @brief Set the dimension Ids from @p From in @p To.
971static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
972 __isl_take isl_set *To) {
973 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
974 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
975 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
976 }
977 return To;
978}
979
980/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000981static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000982 __isl_take isl_pw_aff *L,
983 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +0000984 switch (Pred) {
985 case ICmpInst::ICMP_EQ:
986 return isl_pw_aff_eq_set(L, R);
987 case ICmpInst::ICMP_NE:
988 return isl_pw_aff_ne_set(L, R);
989 case ICmpInst::ICMP_SLT:
990 return isl_pw_aff_lt_set(L, R);
991 case ICmpInst::ICMP_SLE:
992 return isl_pw_aff_le_set(L, R);
993 case ICmpInst::ICMP_SGT:
994 return isl_pw_aff_gt_set(L, R);
995 case ICmpInst::ICMP_SGE:
996 return isl_pw_aff_ge_set(L, R);
997 case ICmpInst::ICMP_ULT:
998 return isl_pw_aff_lt_set(L, R);
999 case ICmpInst::ICMP_UGT:
1000 return isl_pw_aff_gt_set(L, R);
1001 case ICmpInst::ICMP_ULE:
1002 return isl_pw_aff_le_set(L, R);
1003 case ICmpInst::ICMP_UGE:
1004 return isl_pw_aff_ge_set(L, R);
1005 default:
1006 llvm_unreachable("Non integer predicate not supported");
1007 }
1008}
1009
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001010/// @brief Create the conditions under which @p L @p Pred @p R is true.
1011///
1012/// Helper function that will make sure the dimensions of the result have the
1013/// same isl_id's as the @p Domain.
1014static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1015 __isl_take isl_pw_aff *L,
1016 __isl_take isl_pw_aff *R,
1017 __isl_keep isl_set *Domain) {
1018 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1019 return setDimensionIds(Domain, ConsequenceCondSet);
1020}
1021
1022/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001023///
1024/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001025/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1026/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001027static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001028buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001029 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1030
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001031 Value *Condition = getConditionFromTerminator(SI);
1032 assert(Condition && "No condition for switch");
1033
1034 ScalarEvolution &SE = *S.getSE();
1035 BasicBlock *BB = SI->getParent();
1036 isl_pw_aff *LHS, *RHS;
1037 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
1038
1039 unsigned NumSuccessors = SI->getNumSuccessors();
1040 ConditionSets.resize(NumSuccessors);
1041 for (auto &Case : SI->cases()) {
1042 unsigned Idx = Case.getSuccessorIndex();
1043 ConstantInt *CaseValue = Case.getCaseValue();
1044
1045 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
1046 isl_set *CaseConditionSet =
1047 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1048 ConditionSets[Idx] = isl_set_coalesce(
1049 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1050 }
1051
1052 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1053 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1054 for (unsigned u = 2; u < NumSuccessors; u++)
1055 ConditionSetUnion =
1056 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1057 ConditionSets[0] = setDimensionIds(
1058 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1059
1060 S.markAsOptimized();
1061 isl_pw_aff_free(LHS);
1062}
1063
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001064/// @brief Build the conditions sets for the branch condition @p Condition in
1065/// the @p Domain.
1066///
1067/// This will fill @p ConditionSets with the conditions under which control
1068/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001069/// have as many elements as @p TI has successors. If @p TI is nullptr the
1070/// context under which @p Condition is true/false will be returned as the
1071/// new elements of @p ConditionSets.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001072static void
1073buildConditionSets(Scop &S, Value *Condition, TerminatorInst *TI, Loop *L,
1074 __isl_keep isl_set *Domain,
1075 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1076
1077 isl_set *ConsequenceCondSet = nullptr;
1078 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1079 if (CCond->isZero())
1080 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1081 else
1082 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1083 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1084 auto Opcode = BinOp->getOpcode();
1085 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1086
1087 buildConditionSets(S, BinOp->getOperand(0), TI, L, Domain, ConditionSets);
1088 buildConditionSets(S, BinOp->getOperand(1), TI, L, Domain, ConditionSets);
1089
1090 isl_set_free(ConditionSets.pop_back_val());
1091 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1092 isl_set_free(ConditionSets.pop_back_val());
1093 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1094
1095 if (Opcode == Instruction::And)
1096 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1097 else
1098 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1099 } else {
1100 auto *ICond = dyn_cast<ICmpInst>(Condition);
1101 assert(ICond &&
1102 "Condition of exiting branch was neither constant nor ICmp!");
1103
1104 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001105 BasicBlock *BB = TI ? TI->getParent() : nullptr;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001106 isl_pw_aff *LHS, *RHS;
1107 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1108 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
1109 ConsequenceCondSet =
1110 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1111 }
1112
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001113 // If no terminator was given we are only looking for parameter constraints
1114 // under which @p Condition is true/false.
1115 if (!TI)
1116 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
1117
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001118 assert(ConsequenceCondSet);
1119 isl_set *AlternativeCondSet =
1120 isl_set_complement(isl_set_copy(ConsequenceCondSet));
1121
1122 ConditionSets.push_back(isl_set_coalesce(
1123 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
1124 ConditionSets.push_back(isl_set_coalesce(
1125 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
1126}
1127
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001128/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1129///
1130/// This will fill @p ConditionSets with the conditions under which control
1131/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1132/// have as many elements as @p TI has successors.
1133static void
1134buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1135 __isl_keep isl_set *Domain,
1136 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1137
1138 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1139 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1140
1141 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1142
1143 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001144 ConditionSets.push_back(isl_set_copy(Domain));
1145 return;
1146 }
1147
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001148 Value *Condition = getConditionFromTerminator(TI);
1149 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001150
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001151 return buildConditionSets(S, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001152}
1153
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001154void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +00001155 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +00001156
Tobias Grosser084d8f72012-05-29 09:29:44 +00001157 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1158
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001159 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001160 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001161}
1162
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001163void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001164 isl_ctx *Ctx = Parent.getIslCtx();
1165 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1166 Type *Ty = GEP->getPointerOperandType();
1167 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001168 ScopDetection &SD = Parent.getSD();
1169
1170 // The set of loads that are required to be invariant.
1171 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001172
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001173 std::vector<const SCEV *> Subscripts;
1174 std::vector<int> Sizes;
1175
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001176 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001177
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001178 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001179 Ty = PtrTy->getElementType();
1180 }
1181
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001182 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001183
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001184 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001185
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001186 for (size_t i = 0; i < Sizes.size(); i++) {
1187 auto Expr = Subscripts[i + IndexOffset];
1188 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001189
Johannes Doerfert09e36972015-10-07 20:17:36 +00001190 InvariantLoadsSetTy AccessILS;
1191 if (!isAffineExpr(&Parent.getRegion(), Expr, SE, nullptr, &AccessILS))
1192 continue;
1193
1194 bool NonAffine = false;
1195 for (LoadInst *LInst : AccessILS)
1196 if (!ScopRIL.count(LInst))
1197 NonAffine = true;
1198
1199 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001200 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001201
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001202 isl_pw_aff *AccessOffset = getPwAff(Expr);
1203 AccessOffset =
1204 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001205
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001206 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1207 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001208
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001209 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1210 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1211 OutOfBound = isl_set_params(OutOfBound);
1212 isl_set *InBound = isl_set_complement(OutOfBound);
1213 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001214
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001215 // A => B == !A or B
1216 isl_set *InBoundIfExecuted =
1217 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001218
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001219 Parent.addAssumption(INBOUNDS, InBoundIfExecuted, GEP->getDebugLoc());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001220 }
1221
1222 isl_local_space_free(LSpace);
1223}
1224
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001225void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1226 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001227 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1228 deriveAssumptionsFromGEP(GEP);
1229}
1230
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001231void ScopStmt::collectSurroundingLoops() {
1232 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1233 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1234 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1235 isl_id_free(DimId);
1236 }
1237}
1238
Michael Kruse9d080092015-09-11 21:41:48 +00001239ScopStmt::ScopStmt(Scop &parent, Region &R)
Michael Krusecac948e2015-10-02 13:53:07 +00001240 : Parent(parent), Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001241
Tobias Grosser16c44032015-07-09 07:31:45 +00001242 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001243}
1244
Michael Kruse9d080092015-09-11 21:41:48 +00001245ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Michael Krusecac948e2015-10-02 13:53:07 +00001246 : Parent(parent), Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001247
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001248 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001249}
1250
1251void ScopStmt::init() {
1252 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001253
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001254 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001255 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001256 buildAccessRelations();
1257
1258 if (BB) {
1259 deriveAssumptions(BB);
1260 } else {
1261 for (BasicBlock *Block : R->blocks()) {
1262 deriveAssumptions(Block);
1263 }
1264 }
1265
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001266 if (DetectReductions)
1267 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001268}
1269
Johannes Doerferte58a0122014-06-27 20:31:28 +00001270/// @brief Collect loads which might form a reduction chain with @p StoreMA
1271///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001272/// Check if the stored value for @p StoreMA is a binary operator with one or
1273/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001274/// used only once (by @p StoreMA) and its load operands are also used only
1275/// once, we have found a possible reduction chain. It starts at an operand
1276/// load and includes the binary operator and @p StoreMA.
1277///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001278/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001279/// escape this block or into any other store except @p StoreMA.
1280void ScopStmt::collectCandiateReductionLoads(
1281 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1282 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1283 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001284 return;
1285
1286 // Skip if there is not one binary operator between the load and the store
1287 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001288 if (!BinOp)
1289 return;
1290
1291 // Skip if the binary operators has multiple uses
1292 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001293 return;
1294
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001295 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001296 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1297 return;
1298
Johannes Doerfert9890a052014-07-01 00:32:29 +00001299 // Skip if the binary operator is outside the current SCoP
1300 if (BinOp->getParent() != Store->getParent())
1301 return;
1302
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001303 // Skip if it is a multiplicative reduction and we disabled them
1304 if (DisableMultiplicativeReductions &&
1305 (BinOp->getOpcode() == Instruction::Mul ||
1306 BinOp->getOpcode() == Instruction::FMul))
1307 return;
1308
Johannes Doerferte58a0122014-06-27 20:31:28 +00001309 // Check the binary operator operands for a candidate load
1310 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1311 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1312 if (!PossibleLoad0 && !PossibleLoad1)
1313 return;
1314
1315 // A load is only a candidate if it cannot escape (thus has only this use)
1316 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001317 if (PossibleLoad0->getParent() == Store->getParent())
1318 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001319 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001320 if (PossibleLoad1->getParent() == Store->getParent())
1321 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001322}
1323
1324/// @brief Check for reductions in this ScopStmt
1325///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001326/// Iterate over all store memory accesses and check for valid binary reduction
1327/// like chains. For all candidates we check if they have the same base address
1328/// and there are no other accesses which overlap with them. The base address
1329/// check rules out impossible reductions candidates early. The overlap check,
1330/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001331/// guarantees that none of the intermediate results will escape during
1332/// execution of the loop nest. We basically check here that no other memory
1333/// access can access the same memory as the potential reduction.
1334void ScopStmt::checkForReductions() {
1335 SmallVector<MemoryAccess *, 2> Loads;
1336 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1337
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001338 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001339 // stores and collecting possible reduction loads.
1340 for (MemoryAccess *StoreMA : MemAccs) {
1341 if (StoreMA->isRead())
1342 continue;
1343
1344 Loads.clear();
1345 collectCandiateReductionLoads(StoreMA, Loads);
1346 for (MemoryAccess *LoadMA : Loads)
1347 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1348 }
1349
1350 // Then check each possible candidate pair.
1351 for (const auto &CandidatePair : Candidates) {
1352 bool Valid = true;
1353 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1354 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1355
1356 // Skip those with obviously unequal base addresses.
1357 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1358 isl_map_free(LoadAccs);
1359 isl_map_free(StoreAccs);
1360 continue;
1361 }
1362
1363 // And check if the remaining for overlap with other memory accesses.
1364 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1365 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1366 isl_set *AllAccs = isl_map_range(AllAccsRel);
1367
1368 for (MemoryAccess *MA : MemAccs) {
1369 if (MA == CandidatePair.first || MA == CandidatePair.second)
1370 continue;
1371
1372 isl_map *AccRel =
1373 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1374 isl_set *Accs = isl_map_range(AccRel);
1375
1376 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1377 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1378 Valid = Valid && isl_set_is_empty(OverlapAccs);
1379 isl_set_free(OverlapAccs);
1380 }
1381 }
1382
1383 isl_set_free(AllAccs);
1384 if (!Valid)
1385 continue;
1386
Johannes Doerfertf6183392014-07-01 20:52:51 +00001387 const LoadInst *Load =
1388 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1389 MemoryAccess::ReductionType RT =
1390 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1391
Johannes Doerferte58a0122014-06-27 20:31:28 +00001392 // If no overlapping access was found we mark the load and store as
1393 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001394 CandidatePair.first->markAsReductionLike(RT);
1395 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001396 }
Tobias Grosser75805372011-04-29 06:27:02 +00001397}
1398
Tobias Grosser74394f02013-01-14 22:40:23 +00001399std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001400
Tobias Grosser54839312015-04-21 11:37:25 +00001401std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001402 auto *S = getSchedule();
1403 auto Str = stringFromIslObj(S);
1404 isl_map_free(S);
1405 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001406}
1407
Tobias Grosser74394f02013-01-14 22:40:23 +00001408unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001409
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001410unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001411
Tobias Grosser75805372011-04-29 06:27:02 +00001412const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1413
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001414const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001415 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001416}
1417
Tobias Grosser74394f02013-01-14 22:40:23 +00001418isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001419
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001420__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001421
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001422__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001423 return isl_set_get_space(Domain);
1424}
1425
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001426__isl_give isl_id *ScopStmt::getDomainId() const {
1427 return isl_set_get_tuple_id(Domain);
1428}
Tobias Grossercd95b772012-08-30 11:49:38 +00001429
Tobias Grosser75805372011-04-29 06:27:02 +00001430ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001431 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001432 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001433}
1434
1435void ScopStmt::print(raw_ostream &OS) const {
1436 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001437 OS.indent(12) << "Domain :=\n";
1438
1439 if (Domain) {
1440 OS.indent(16) << getDomainStr() << ";\n";
1441 } else
1442 OS.indent(16) << "n/a\n";
1443
Tobias Grosser54839312015-04-21 11:37:25 +00001444 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001445
1446 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001447 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001448 } else
1449 OS.indent(16) << "n/a\n";
1450
Tobias Grosser083d3d32014-06-28 08:59:45 +00001451 for (MemoryAccess *Access : MemAccs)
1452 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001453}
1454
1455void ScopStmt::dump() const { print(dbgs()); }
1456
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001457void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001458
1459 // Remove all memory accesses in @p InvMAs from this statement together
1460 // with all scalar accesses that were caused by them. The tricky iteration
1461 // order uses is needed because the MemAccs is a vector and the order in
1462 // which the accesses of each memory access list (MAL) are stored in this
1463 // vector is reversed.
1464 for (MemoryAccess *MA : InvMAs) {
1465 auto &MAL = *lookupAccessesFor(MA->getAccessInstruction());
1466 MAL.reverse();
1467
1468 auto MALIt = MAL.begin();
1469 auto MALEnd = MAL.end();
1470 auto MemAccsIt = MemAccs.begin();
1471 while (MALIt != MALEnd) {
1472 while (*MemAccsIt != *MALIt)
1473 MemAccsIt++;
1474
1475 MALIt++;
1476 MemAccs.erase(MemAccsIt);
1477 }
1478
1479 InstructionToAccess.erase(MA->getAccessInstruction());
1480 delete &MAL;
1481 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001482}
1483
Tobias Grosser75805372011-04-29 06:27:02 +00001484//===----------------------------------------------------------------------===//
1485/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001486
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001487void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001488 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1489 isl_set_free(Context);
1490 Context = NewContext;
1491}
1492
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001493/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1494struct SCEVSensitiveParameterRewriter
1495 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1496 ValueToValueMap &VMap;
1497 ScalarEvolution &SE;
1498
1499public:
1500 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1501 : VMap(VMap), SE(SE) {}
1502
1503 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1504 ValueToValueMap &VMap) {
1505 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1506 return SSPR.visit(E);
1507 }
1508
1509 const SCEV *visit(const SCEV *E) {
1510 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1511 }
1512
1513 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1514
1515 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1516 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1517 }
1518
1519 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1520 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1521 }
1522
1523 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1524 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1525 }
1526
1527 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1528 SmallVector<const SCEV *, 4> Operands;
1529 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1530 Operands.push_back(visit(E->getOperand(i)));
1531 return SE.getAddExpr(Operands);
1532 }
1533
1534 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1535 SmallVector<const SCEV *, 4> Operands;
1536 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1537 Operands.push_back(visit(E->getOperand(i)));
1538 return SE.getMulExpr(Operands);
1539 }
1540
1541 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1542 SmallVector<const SCEV *, 4> Operands;
1543 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1544 Operands.push_back(visit(E->getOperand(i)));
1545 return SE.getSMaxExpr(Operands);
1546 }
1547
1548 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1549 SmallVector<const SCEV *, 4> Operands;
1550 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1551 Operands.push_back(visit(E->getOperand(i)));
1552 return SE.getUMaxExpr(Operands);
1553 }
1554
1555 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1556 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1557 }
1558
1559 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1560 auto *Start = visit(E->getStart());
1561 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1562 visit(E->getStepRecurrence(SE)),
1563 E->getLoop(), SCEV::FlagAnyWrap);
1564 return SE.getAddExpr(Start, AddRec);
1565 }
1566
1567 const SCEV *visitUnknown(const SCEVUnknown *E) {
1568 if (auto *NewValue = VMap.lookup(E->getValue()))
1569 return SE.getUnknown(NewValue);
1570 return E;
1571 }
1572};
1573
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001574const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001575 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001576}
1577
Tobias Grosserabfbe632013-02-05 12:09:06 +00001578void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001579 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001580 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001581
1582 // Normalize the SCEV to get the representing element for an invariant load.
1583 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1584
Tobias Grosser60b54f12011-11-08 15:41:28 +00001585 if (ParameterIds.find(Parameter) != ParameterIds.end())
1586 continue;
1587
1588 int dimension = Parameters.size();
1589
1590 Parameters.push_back(Parameter);
1591 ParameterIds[Parameter] = dimension;
1592 }
1593}
1594
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001595__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001596 // Normalize the SCEV to get the representing element for an invariant load.
1597 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1598
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001599 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001600
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001601 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001602 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001603
Tobias Grosser8f99c162011-11-15 11:38:55 +00001604 std::string ParameterName;
1605
1606 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1607 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001608 ParameterName = Val->getName();
Johannes Doerferte071f6d2015-11-03 16:49:59 +00001609 if (!Val->hasName())
1610 if (LoadInst *LI = dyn_cast<LoadInst>(Val))
1611 ParameterName =
1612 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001613 }
1614
1615 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001616 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001617
Tobias Grosser20532b82014-04-11 17:56:49 +00001618 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1619 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001620}
Tobias Grosser75805372011-04-29 06:27:02 +00001621
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001622isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1623 isl_set *DomainContext = isl_union_set_params(getDomains());
1624 return isl_set_intersect_params(C, DomainContext);
1625}
1626
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001627void Scop::buildBoundaryContext() {
1628 BoundaryContext = Affinator.getWrappingContext();
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001629
1630 // The isl_set_complement operation used to create the boundary context
1631 // can possibly become very expensive. We bound the compile time of
1632 // this operation by setting a compute out.
1633 //
1634 // TODO: We can probably get around using isl_set_complement and directly
1635 // AST generate BoundaryContext.
1636 long MaxOpsOld = isl_ctx_get_max_operations(getIslCtx());
1637 isl_ctx_set_max_operations(getIslCtx(), 300000);
1638 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_CONTINUE);
1639
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001640 BoundaryContext = isl_set_complement(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001641
Tobias Grossera52b4da2015-11-11 17:59:53 +00001642 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
1643 isl_set_free(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001644 BoundaryContext = isl_set_empty(getParamSpace());
Tobias Grossera52b4da2015-11-11 17:59:53 +00001645 }
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001646
1647 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
1648 isl_ctx_reset_operations(getIslCtx());
1649 isl_ctx_set_max_operations(getIslCtx(), MaxOpsOld);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001650 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001651 trackAssumption(WRAPPING, BoundaryContext, DebugLoc());
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001652}
1653
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001654void Scop::addUserAssumptions(AssumptionCache &AC) {
1655 auto *R = &getRegion();
1656 auto &F = *R->getEntry()->getParent();
1657 for (auto &Assumption : AC.assumptions()) {
1658 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1659 if (!CI || CI->getNumArgOperands() != 1)
1660 continue;
1661 if (!DT.dominates(CI->getParent(), R->getEntry()))
1662 continue;
1663
1664 auto *Val = CI->getArgOperand(0);
1665 std::vector<const SCEV *> Params;
1666 if (!isAffineParamConstraint(Val, R, *SE, Params)) {
1667 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1668 CI->getDebugLoc(),
1669 "Non-affine user assumption ignored.");
1670 continue;
1671 }
1672
1673 addParams(Params);
1674
1675 auto *L = LI.getLoopFor(CI->getParent());
1676 SmallVector<isl_set *, 2> ConditionSets;
1677 buildConditionSets(*this, Val, nullptr, L, Context, ConditionSets);
1678 assert(ConditionSets.size() == 2);
1679 isl_set_free(ConditionSets[1]);
1680
1681 auto *AssumptionCtx = ConditionSets[0];
1682 emitOptimizationRemarkAnalysis(
1683 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1684 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1685 Context = isl_set_intersect(Context, AssumptionCtx);
1686 }
1687}
1688
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001689void Scop::addUserContext() {
1690 if (UserContextStr.empty())
1691 return;
1692
1693 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1694 isl_space *Space = getParamSpace();
1695 if (isl_space_dim(Space, isl_dim_param) !=
1696 isl_set_dim(UserContext, isl_dim_param)) {
1697 auto SpaceStr = isl_space_to_str(Space);
1698 errs() << "Error: the context provided in -polly-context has not the same "
1699 << "number of dimensions than the computed context. Due to this "
1700 << "mismatch, the -polly-context option is ignored. Please provide "
1701 << "the context in the parameter space: " << SpaceStr << ".\n";
1702 free(SpaceStr);
1703 isl_set_free(UserContext);
1704 isl_space_free(Space);
1705 return;
1706 }
1707
1708 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1709 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1710 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1711
1712 if (strcmp(NameContext, NameUserContext) != 0) {
1713 auto SpaceStr = isl_space_to_str(Space);
1714 errs() << "Error: the name of dimension " << i
1715 << " provided in -polly-context "
1716 << "is '" << NameUserContext << "', but the name in the computed "
1717 << "context is '" << NameContext
1718 << "'. Due to this name mismatch, "
1719 << "the -polly-context option is ignored. Please provide "
1720 << "the context in the parameter space: " << SpaceStr << ".\n";
1721 free(SpaceStr);
1722 isl_set_free(UserContext);
1723 isl_space_free(Space);
1724 return;
1725 }
1726
1727 UserContext =
1728 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1729 isl_space_get_dim_id(Space, isl_dim_param, i));
1730 }
1731
1732 Context = isl_set_intersect(Context, UserContext);
1733 isl_space_free(Space);
1734}
1735
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001736void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001737 DenseMap<const SCEV *, LoadInst *> EquivClasses;
1738
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001739 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001740 for (LoadInst *LInst : RIL) {
1741 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1742
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001743 LoadInst *&ClassRep = EquivClasses[PointerSCEV];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001744 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001745 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001746 continue;
1747 }
1748
1749 ClassRep = LInst;
1750 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(),
1751 nullptr);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001752 }
1753}
1754
Tobias Grosser6be480c2011-11-08 15:41:13 +00001755void Scop::buildContext() {
1756 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001757 Context = isl_set_universe(isl_space_copy(Space));
1758 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001759}
1760
Tobias Grosser18daaca2012-05-22 10:47:27 +00001761void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001762 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001763 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001764
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001765 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001766
Johannes Doerferte7044942015-02-24 11:58:30 +00001767 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001768 }
1769}
1770
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001771void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001772 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001773 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001774
Tobias Grosser083d3d32014-06-28 08:59:45 +00001775 for (const auto &ParamID : ParameterIds) {
1776 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001777 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001778 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001779 }
1780
1781 // Align the parameters of all data structures to the model.
1782 Context = isl_set_align_params(Context, Space);
1783
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001784 for (ScopStmt &Stmt : *this)
1785 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001786}
1787
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001788static __isl_give isl_set *
1789simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1790 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001791 // If we modelt all blocks in the SCoP that have side effects we can simplify
1792 // the context with the constraints that are needed for anything to be
1793 // executed at all. However, if we have error blocks in the SCoP we already
1794 // assumed some parameter combinations cannot occure and removed them from the
1795 // domains, thus we cannot use the remaining domain to simplify the
1796 // assumptions.
1797 if (!S.hasErrorBlock()) {
1798 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1799 AssumptionContext =
1800 isl_set_gist_params(AssumptionContext, DomainParameters);
1801 }
1802
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001803 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1804 return AssumptionContext;
1805}
1806
1807void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001808 // The parameter constraints of the iteration domains give us a set of
1809 // constraints that need to hold for all cases where at least a single
1810 // statement iteration is executed in the whole scop. We now simplify the
1811 // assumed context under the assumption that such constraints hold and at
1812 // least a single statement iteration is executed. For cases where no
1813 // statement instances are executed, the assumptions we have taken about
1814 // the executed code do not matter and can be changed.
1815 //
1816 // WARNING: This only holds if the assumptions we have taken do not reduce
1817 // the set of statement instances that are executed. Otherwise we
1818 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001819 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001820 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001821 // performed. In such a case, modifying the run-time conditions and
1822 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001823 // to not be executed.
1824 //
1825 // Example:
1826 //
1827 // When delinearizing the following code:
1828 //
1829 // for (long i = 0; i < 100; i++)
1830 // for (long j = 0; j < m; j++)
1831 // A[i+p][j] = 1.0;
1832 //
1833 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001834 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001835 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001836 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1837 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001838}
1839
Johannes Doerfertb164c792014-09-18 11:17:17 +00001840/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001841static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001842 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1843 isl_pw_multi_aff *MinPMA, *MaxPMA;
1844 isl_pw_aff *LastDimAff;
1845 isl_aff *OneAff;
1846 unsigned Pos;
1847
Johannes Doerfert9143d672014-09-27 11:02:39 +00001848 // Restrict the number of parameters involved in the access as the lexmin/
1849 // lexmax computation will take too long if this number is high.
1850 //
1851 // Experiments with a simple test case using an i7 4800MQ:
1852 //
1853 // #Parameters involved | Time (in sec)
1854 // 6 | 0.01
1855 // 7 | 0.04
1856 // 8 | 0.12
1857 // 9 | 0.40
1858 // 10 | 1.54
1859 // 11 | 6.78
1860 // 12 | 30.38
1861 //
1862 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1863 unsigned InvolvedParams = 0;
1864 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1865 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1866 InvolvedParams++;
1867
1868 if (InvolvedParams > RunTimeChecksMaxParameters) {
1869 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001870 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001871 }
1872 }
1873
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001874 Set = isl_set_remove_divs(Set);
1875
Johannes Doerfertb164c792014-09-18 11:17:17 +00001876 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1877 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1878
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001879 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1880 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1881
Johannes Doerfertb164c792014-09-18 11:17:17 +00001882 // Adjust the last dimension of the maximal access by one as we want to
1883 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1884 // we test during code generation might now point after the end of the
1885 // allocated array but we will never dereference it anyway.
1886 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1887 "Assumed at least one output dimension");
1888 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1889 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1890 OneAff = isl_aff_zero_on_domain(
1891 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1892 OneAff = isl_aff_add_constant_si(OneAff, 1);
1893 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1894 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1895
1896 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1897
1898 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001899 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001900}
1901
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001902static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1903 isl_set *Domain = MA->getStatement()->getDomain();
1904 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1905 return isl_set_reset_tuple_id(Domain);
1906}
1907
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001908/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1909static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001910 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001911 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001912
1913 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1914 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001915 Locations = isl_union_set_coalesce(Locations);
1916 Locations = isl_union_set_detect_equalities(Locations);
1917 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001918 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001919 isl_union_set_free(Locations);
1920 return Valid;
1921}
1922
Johannes Doerfert96425c22015-08-30 21:13:53 +00001923/// @brief Helper to treat non-affine regions and basic blocks the same.
1924///
1925///{
1926
1927/// @brief Return the block that is the representing block for @p RN.
1928static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1929 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1930 : RN->getNodeAs<BasicBlock>();
1931}
1932
1933/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001934static inline BasicBlock *
1935getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001936 if (RN->isSubRegion()) {
1937 assert(idx == 0);
1938 return RN->getNodeAs<Region>()->getExit();
1939 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001940 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001941}
1942
1943/// @brief Return the smallest loop surrounding @p RN.
1944static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1945 if (!RN->isSubRegion())
1946 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1947
1948 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1949 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1950 while (L && NonAffineSubRegion->contains(L))
1951 L = L->getParentLoop();
1952 return L;
1953}
1954
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001955static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1956 if (!RN->isSubRegion())
1957 return 1;
1958
1959 unsigned NumBlocks = 0;
1960 Region *R = RN->getNodeAs<Region>();
1961 for (auto BB : R->blocks()) {
1962 (void)BB;
1963 NumBlocks++;
1964 }
1965 return NumBlocks;
1966}
1967
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001968static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
1969 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00001970 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001971 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00001972 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001973 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00001974 return true;
1975 return false;
1976}
1977
Johannes Doerfert96425c22015-08-30 21:13:53 +00001978///}
1979
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001980static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1981 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001982 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001983 isl_id *DimId =
1984 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
1985 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
1986}
1987
Johannes Doerfert96425c22015-08-30 21:13:53 +00001988isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1989 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1990 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00001991 return getDomainConditions(BB);
1992}
1993
1994isl_set *Scop::getDomainConditions(BasicBlock *BB) {
1995 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001996 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001997}
1998
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001999void Scop::buildDomains(Region *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002000
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002001 auto *EntryBB = R->getEntry();
2002 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
2003 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002004
2005 Loop *L = LI.getLoopFor(EntryBB);
2006 while (LD-- >= 0) {
2007 S = addDomainDimId(S, LD + 1, L);
2008 L = L->getParentLoop();
2009 }
2010
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002011 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002012
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002013 if (SD.isNonAffineSubRegion(R, R))
2014 return;
2015
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002016 buildDomainsWithBranchConstraints(R);
2017 propagateDomainConstraints(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002018}
2019
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002020void Scop::buildDomainsWithBranchConstraints(Region *R) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002021 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00002022
2023 // To create the domain for each block in R we iterate over all blocks and
2024 // subregions in R and propagate the conditions under which the current region
2025 // element is executed. To this end we iterate in reverse post order over R as
2026 // it ensures that we first visit all predecessors of a region node (either a
2027 // basic block or a subregion) before we visit the region node itself.
2028 // Initially, only the domain for the SCoP region entry block is set and from
2029 // there we propagate the current domain to all successors, however we add the
2030 // condition that the successor is actually executed next.
2031 // As we are only interested in non-loop carried constraints here we can
2032 // simply skip loop back edges.
2033
2034 ReversePostOrderTraversal<Region *> RTraversal(R);
2035 for (auto *RN : RTraversal) {
2036
2037 // Recurse for affine subregions but go on for basic blocks and non-affine
2038 // subregions.
2039 if (RN->isSubRegion()) {
2040 Region *SubRegion = RN->getNodeAs<Region>();
2041 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002042 buildDomainsWithBranchConstraints(SubRegion);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002043 continue;
2044 }
2045 }
2046
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002047 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002048 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002049
Johannes Doerfert96425c22015-08-30 21:13:53 +00002050 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002051 TerminatorInst *TI = BB->getTerminator();
2052
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002053 if (isa<UnreachableInst>(TI))
2054 continue;
2055
Johannes Doerfertf5673802015-10-01 23:48:18 +00002056 isl_set *Domain = DomainMap.lookup(BB);
2057 if (!Domain) {
2058 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2059 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002060 continue;
2061 }
2062
Johannes Doerfert96425c22015-08-30 21:13:53 +00002063 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002064
2065 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2066 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2067
2068 // Build the condition sets for the successor nodes of the current region
2069 // node. If it is a non-affine subregion we will always execute the single
2070 // exit node, hence the single entry node domain is the condition set. For
2071 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002072 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002073 if (RN->isSubRegion())
2074 ConditionSets.push_back(isl_set_copy(Domain));
2075 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002076 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002077
2078 // Now iterate over the successors and set their initial domain based on
2079 // their condition set. We skip back edges here and have to be careful when
2080 // we leave a loop not to keep constraints over a dimension that doesn't
2081 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002082 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002083 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002084 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002085 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002086
2087 // Skip back edges.
2088 if (DT.dominates(SuccBB, BB)) {
2089 isl_set_free(CondSet);
2090 continue;
2091 }
2092
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002093 // Do not adjust the number of dimensions if we enter a boxed loop or are
2094 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002095 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002096 Region *SuccRegion = RI.getRegionFor(SuccBB);
Johannes Doerfert634909c2015-10-04 14:57:41 +00002097 if (SD.isNonAffineSubRegion(SuccRegion, &getRegion()))
2098 while (SuccBBLoop && SuccRegion->contains(SuccBBLoop))
2099 SuccBBLoop = SuccBBLoop->getParentLoop();
2100
2101 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002102
2103 // Check if the edge to SuccBB is a loop entry or exit edge. If so
2104 // adjust the dimensionality accordingly. Lastly, if we leave a loop
2105 // and enter a new one we need to drop the old constraints.
2106 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002107 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002108 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002109 CondSet = isl_set_project_out(CondSet, isl_dim_set,
2110 isl_set_n_dim(CondSet) - LoopDepthDiff,
2111 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002112 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002113 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002114 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002115 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002116 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002117 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002118 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
2119 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002120 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002121 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002122 }
2123
2124 // Set the domain for the successor or merge it with an existing domain in
2125 // case there are multiple paths (without loop back edges) to the
2126 // successor block.
2127 isl_set *&SuccDomain = DomainMap[SuccBB];
2128 if (!SuccDomain)
2129 SuccDomain = CondSet;
2130 else
2131 SuccDomain = isl_set_union(SuccDomain, CondSet);
2132
2133 SuccDomain = isl_set_coalesce(SuccDomain);
Johannes Doerfert634909c2015-10-04 14:57:41 +00002134 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
2135 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002136 }
2137 }
2138}
2139
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002140/// @brief Return the domain for @p BB wrt @p DomainMap.
2141///
2142/// This helper function will lookup @p BB in @p DomainMap but also handle the
2143/// case where @p BB is contained in a non-affine subregion using the region
2144/// tree obtained by @p RI.
2145static __isl_give isl_set *
2146getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
2147 RegionInfo &RI) {
2148 auto DIt = DomainMap.find(BB);
2149 if (DIt != DomainMap.end())
2150 return isl_set_copy(DIt->getSecond());
2151
2152 Region *R = RI.getRegionFor(BB);
2153 while (R->getEntry() == BB)
2154 R = R->getParent();
2155 return getDomainForBlock(R->getEntry(), DomainMap, RI);
2156}
2157
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002158void Scop::propagateDomainConstraints(Region *R) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002159 // Iterate over the region R and propagate the domain constrains from the
2160 // predecessors to the current node. In contrast to the
2161 // buildDomainsWithBranchConstraints function, this one will pull the domain
2162 // information from the predecessors instead of pushing it to the successors.
2163 // Additionally, we assume the domains to be already present in the domain
2164 // map here. However, we iterate again in reverse post order so we know all
2165 // predecessors have been visited before a block or non-affine subregion is
2166 // visited.
2167
2168 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2169 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2170
2171 ReversePostOrderTraversal<Region *> RTraversal(R);
2172 for (auto *RN : RTraversal) {
2173
2174 // Recurse for affine subregions but go on for basic blocks and non-affine
2175 // subregions.
2176 if (RN->isSubRegion()) {
2177 Region *SubRegion = RN->getNodeAs<Region>();
2178 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002179 propagateDomainConstraints(SubRegion);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002180 continue;
2181 }
2182 }
2183
Johannes Doerfertf5673802015-10-01 23:48:18 +00002184 // Get the domain for the current block and check if it was initialized or
2185 // not. The only way it was not is if this block is only reachable via error
2186 // blocks, thus will not be executed under the assumptions we make. Such
2187 // blocks have to be skipped as their predecessors might not have domains
2188 // either. It would not benefit us to compute the domain anyway, only the
2189 // domains of the error blocks that are reachable from non-error blocks
2190 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002191 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002192 isl_set *&Domain = DomainMap[BB];
2193 if (!Domain) {
2194 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2195 << ", it is only reachable from error blocks.\n");
2196 DomainMap.erase(BB);
2197 continue;
2198 }
2199 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
2200
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002201 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2202 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2203
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002204 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2205 for (auto *PredBB : predecessors(BB)) {
2206
2207 // Skip backedges
2208 if (DT.dominates(BB, PredBB))
2209 continue;
2210
2211 isl_set *PredBBDom = nullptr;
2212
2213 // Handle the SCoP entry block with its outside predecessors.
2214 if (!getRegion().contains(PredBB))
2215 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
2216
2217 if (!PredBBDom) {
2218 // Determine the loop depth of the predecessor and adjust its domain to
2219 // the domain of the current block. This can mean we have to:
2220 // o) Drop a dimension if this block is the exit of a loop, not the
2221 // header of a new loop and the predecessor was part of the loop.
2222 // o) Add an unconstrainted new dimension if this block is the header
2223 // of a loop and the predecessor is not part of it.
2224 // o) Drop the information about the innermost loop dimension when the
2225 // predecessor and the current block are surrounded by different
2226 // loops in the same depth.
2227 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2228 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2229 while (BoxedLoops.count(PredBBLoop))
2230 PredBBLoop = PredBBLoop->getParentLoop();
2231
2232 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002233 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002234 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002235 PredBBDom = isl_set_project_out(
2236 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2237 LoopDepthDiff);
2238 else if (PredBBLoopDepth < BBLoopDepth) {
2239 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002240 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002241 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2242 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002243 PredBBDom = isl_set_drop_constraints_involving_dims(
2244 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002245 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002246 }
2247
2248 PredDom = isl_set_union(PredDom, PredBBDom);
2249 }
2250
2251 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002252 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002253
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002254 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002255 addLoopBoundsToHeaderDomain(BBLoop);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002256
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002257 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002258 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002259 IsOptimized = true;
2260 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002261 addAssumption(ERRORBLOCK, isl_set_complement(DomPar),
2262 BB->getTerminator()->getDebugLoc());
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002263 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002264 }
2265}
2266
2267/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2268/// is incremented by one and all other dimensions are equal, e.g.,
2269/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2270/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2271static __isl_give isl_map *
2272createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2273 auto *MapSpace = isl_space_map_from_set(SetSpace);
2274 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2275 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2276 if (u != Dim)
2277 NextIterationMap =
2278 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2279 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2280 C = isl_constraint_set_constant_si(C, 1);
2281 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2282 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2283 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2284 return NextIterationMap;
2285}
2286
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002287void Scop::addLoopBoundsToHeaderDomain(Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002288 int LoopDepth = getRelativeLoopDepth(L);
2289 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002290
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002291 BasicBlock *HeaderBB = L->getHeader();
2292 assert(DomainMap.count(HeaderBB));
2293 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002294
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002295 isl_map *NextIterationMap =
2296 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002297
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002298 isl_set *UnionBackedgeCondition =
2299 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002300
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002301 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2302 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002303
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002304 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002305
2306 // If the latch is only reachable via error statements we skip it.
2307 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2308 if (!LatchBBDom)
2309 continue;
2310
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002311 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002312
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002313 TerminatorInst *TI = LatchBB->getTerminator();
2314 BranchInst *BI = dyn_cast<BranchInst>(TI);
2315 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002316 BackedgeCondition = isl_set_copy(LatchBBDom);
2317 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002318 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002319 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002320 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002321
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002322 // Free the non back edge condition set as we do not need it.
2323 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002324
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002325 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002326 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002327
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002328 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2329 assert(LatchLoopDepth >= LoopDepth);
2330 BackedgeCondition =
2331 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2332 LatchLoopDepth - LoopDepth);
2333 UnionBackedgeCondition =
2334 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002335 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002336
2337 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2338 for (int i = 0; i < LoopDepth; i++)
2339 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2340
2341 isl_set *UnionBackedgeConditionComplement =
2342 isl_set_complement(UnionBackedgeCondition);
2343 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2344 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2345 UnionBackedgeConditionComplement =
2346 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2347 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2348 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2349
2350 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2351 HeaderBBDom = Parts.second;
2352
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002353 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2354 // the bounded assumptions to the context as they are already implied by the
2355 // <nsw> tag.
2356 if (Affinator.hasNSWAddRecForLoop(L)) {
2357 isl_set_free(Parts.first);
2358 return;
2359 }
2360
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002361 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2362 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002363 addAssumption(INFINITELOOP, BoundedCtx,
2364 HeaderBB->getTerminator()->getDebugLoc());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002365}
2366
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002367void Scop::buildAliasChecks(AliasAnalysis &AA) {
2368 if (!PollyUseRuntimeAliasChecks)
2369 return;
2370
2371 if (buildAliasGroups(AA))
2372 return;
2373
2374 // If a problem occurs while building the alias groups we need to delete
2375 // this SCoP and pretend it wasn't valid in the first place. To this end
2376 // we make the assumed context infeasible.
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002377 addAssumption(ALIASING, isl_set_empty(getParamSpace()), DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002378
2379 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2380 << " could not be created as the number of parameters involved "
2381 "is too high. The SCoP will be "
2382 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2383 "the maximal number of parameters but be advised that the "
2384 "compile time might increase exponentially.\n\n");
2385}
2386
Johannes Doerfert9143d672014-09-27 11:02:39 +00002387bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002388 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002389 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002390 // for all memory accesses inside the SCoP.
2391 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002392 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002393 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002394 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002395 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002396 // if their access domains intersect, otherwise they are in different
2397 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002398 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002399 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002400 // and maximal accesses to each array of a group in read only and non
2401 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002402 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2403
2404 AliasSetTracker AST(AA);
2405
2406 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002407 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002408 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002409
2410 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002411 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002412 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2413 isl_set_free(StmtDomain);
2414 if (StmtDomainEmpty)
2415 continue;
2416
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002417 for (MemoryAccess *MA : Stmt) {
Michael Kruse8d0b7342015-09-25 21:21:00 +00002418 if (MA->isImplicit())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002419 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002420 if (!MA->isRead())
2421 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002422 Instruction *Acc = MA->getAccessInstruction();
2423 PtrToAcc[getPointerOperand(*Acc)] = MA;
2424 AST.add(Acc);
2425 }
2426 }
2427
2428 SmallVector<AliasGroupTy, 4> AliasGroups;
2429 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002430 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002431 continue;
2432 AliasGroupTy AG;
2433 for (auto PR : AS)
2434 AG.push_back(PtrToAcc[PR.getValue()]);
2435 assert(AG.size() > 1 &&
2436 "Alias groups should contain at least two accesses");
2437 AliasGroups.push_back(std::move(AG));
2438 }
2439
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002440 // Split the alias groups based on their domain.
2441 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2442 AliasGroupTy NewAG;
2443 AliasGroupTy &AG = AliasGroups[u];
2444 AliasGroupTy::iterator AGI = AG.begin();
2445 isl_set *AGDomain = getAccessDomain(*AGI);
2446 while (AGI != AG.end()) {
2447 MemoryAccess *MA = *AGI;
2448 isl_set *MADomain = getAccessDomain(MA);
2449 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2450 NewAG.push_back(MA);
2451 AGI = AG.erase(AGI);
2452 isl_set_free(MADomain);
2453 } else {
2454 AGDomain = isl_set_union(AGDomain, MADomain);
2455 AGI++;
2456 }
2457 }
2458 if (NewAG.size() > 1)
2459 AliasGroups.push_back(std::move(NewAG));
2460 isl_set_free(AGDomain);
2461 }
2462
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002463 auto &F = *getRegion().getEntry()->getParent();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002464 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002465 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2466 for (AliasGroupTy &AG : AliasGroups) {
2467 NonReadOnlyBaseValues.clear();
2468 ReadOnlyPairs.clear();
2469
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002470 if (AG.size() < 2) {
2471 AG.clear();
2472 continue;
2473 }
2474
Johannes Doerfert13771732014-10-01 12:40:46 +00002475 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002476 emitOptimizationRemarkAnalysis(
2477 F.getContext(), DEBUG_TYPE, F,
2478 (*II)->getAccessInstruction()->getDebugLoc(),
2479 "Possibly aliasing pointer, use restrict keyword.");
2480
Johannes Doerfert13771732014-10-01 12:40:46 +00002481 Value *BaseAddr = (*II)->getBaseAddr();
2482 if (HasWriteAccess.count(BaseAddr)) {
2483 NonReadOnlyBaseValues.insert(BaseAddr);
2484 II++;
2485 } else {
2486 ReadOnlyPairs[BaseAddr].insert(*II);
2487 II = AG.erase(II);
2488 }
2489 }
2490
2491 // If we don't have read only pointers check if there are at least two
2492 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002493 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002494 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002495 continue;
2496 }
2497
2498 // If we don't have non read only pointers clear the alias group.
2499 if (NonReadOnlyBaseValues.empty()) {
2500 AG.clear();
2501 continue;
2502 }
2503
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002504 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002505 MinMaxAliasGroups.emplace_back();
2506 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2507 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2508 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2509 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002510
2511 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002512
2513 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002514 for (MemoryAccess *MA : AG)
2515 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002516
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002517 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2518 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002519
2520 // Bail out if the number of values we need to compare is too large.
2521 // This is important as the number of comparisions grows quadratically with
2522 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002523 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2524 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002525 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002526
2527 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002528 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002529 Accesses = isl_union_map_empty(getParamSpace());
2530
2531 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2532 for (MemoryAccess *MA : ReadOnlyPair.second)
2533 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2534
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002535 Valid =
2536 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002537
2538 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002539 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002540 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002541
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002542 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002543}
2544
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002545static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
2546 Loop *L = LI.getLoopFor(R.getEntry());
2547 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2548}
2549
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002550static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2551 ScopDetection &SD) {
2552
2553 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2554
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002555 unsigned MinLD = INT_MAX, MaxLD = 0;
2556 for (BasicBlock *BB : R.blocks()) {
2557 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002558 if (!R.contains(L))
2559 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002560 if (BoxedLoops && BoxedLoops->count(L))
2561 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002562 unsigned LD = L->getLoopDepth();
2563 MinLD = std::min(MinLD, LD);
2564 MaxLD = std::max(MaxLD, LD);
2565 }
2566 }
2567
2568 // Handle the case that there is no loop in the SCoP first.
2569 if (MaxLD == 0)
2570 return 1;
2571
2572 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2573 assert(MaxLD >= MinLD &&
2574 "Maximal loop depth was smaller than mininaml loop depth?");
2575 return MaxLD - MinLD + 1;
2576}
2577
Johannes Doerfert478a7de2015-10-02 13:09:31 +00002578Scop::Scop(Region &R, AccFuncMapType &AccFuncMap, ScopDetection &SD,
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002579 ScalarEvolution &ScalarEvolution, DominatorTree &DT, LoopInfo &LI,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002580 isl_ctx *Context, unsigned MaxLoopDepth)
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002581 : LI(LI), DT(DT), SE(&ScalarEvolution), SD(SD), R(R),
2582 AccFuncMap(AccFuncMap), IsOptimized(false),
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002583 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
2584 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Context(nullptr),
2585 Affinator(this), AssumedContext(nullptr), BoundaryContext(nullptr),
2586 Schedule(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002587
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002588void Scop::init(AliasAnalysis &AA, AssumptionCache &AC) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002589 buildContext();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002590 addUserAssumptions(AC);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002591 buildInvariantEquivalenceClasses();
2592
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002593 buildDomains(&R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002594
Michael Krusecac948e2015-10-02 13:53:07 +00002595 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002596 // Exit early in case there are no executable statements left in this scop.
Michael Krusecac948e2015-10-02 13:53:07 +00002597 simplifySCoP(true);
Michael Kruseafe06702015-10-02 16:33:27 +00002598 if (Stmts.empty())
2599 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002600
Michael Krusecac948e2015-10-02 13:53:07 +00002601 // The ScopStmts now have enough information to initialize themselves.
2602 for (ScopStmt &Stmt : Stmts)
2603 Stmt.init();
2604
2605 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002606 Loop *L = getLoopSurroundingRegion(R, LI);
2607 LoopSchedules[L];
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002608 buildSchedule(&R, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002609 Schedule = LoopSchedules[L].first;
Tobias Grosser75805372011-04-29 06:27:02 +00002610
Tobias Grosser8286b832015-11-02 11:29:32 +00002611 if (isl_set_is_empty(AssumedContext))
2612 return;
2613
2614 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002615 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002616 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002617 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002618 buildBoundaryContext();
2619 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002620 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002621
2622 hoistInvariantLoads();
Michael Krusecac948e2015-10-02 13:53:07 +00002623 simplifySCoP(false);
Tobias Grosser75805372011-04-29 06:27:02 +00002624}
2625
2626Scop::~Scop() {
2627 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002628 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002629 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002630 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002631
Johannes Doerfert96425c22015-08-30 21:13:53 +00002632 for (auto It : DomainMap)
2633 isl_set_free(It.second);
2634
Johannes Doerfertb164c792014-09-18 11:17:17 +00002635 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002636 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002637 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002638 isl_pw_multi_aff_free(MMA.first);
2639 isl_pw_multi_aff_free(MMA.second);
2640 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002641 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002642 isl_pw_multi_aff_free(MMA.first);
2643 isl_pw_multi_aff_free(MMA.second);
2644 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002645 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002646
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002647 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002648 isl_set_free(std::get<2>(IAClass));
Tobias Grosser75805372011-04-29 06:27:02 +00002649}
2650
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002651void Scop::updateAccessDimensionality() {
2652 for (auto &Stmt : *this)
2653 for (auto &Access : Stmt)
2654 Access->updateDimensionality();
2655}
2656
Michael Krusecac948e2015-10-02 13:53:07 +00002657void Scop::simplifySCoP(bool RemoveIgnoredStmts) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002658 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2659 ScopStmt &Stmt = *StmtIt;
Michael Krusecac948e2015-10-02 13:53:07 +00002660 RegionNode *RN = Stmt.isRegionStmt()
2661 ? Stmt.getRegion()->getNode()
2662 : getRegion().getBBNode(Stmt.getBasicBlock());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002663
Johannes Doerferteca9e892015-11-03 16:54:49 +00002664 bool RemoveStmt = StmtIt->isEmpty();
2665 if (!RemoveStmt)
2666 RemoveStmt = isl_set_is_empty(DomainMap[getRegionNodeBasicBlock(RN)]);
2667 if (!RemoveStmt)
2668 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002669
Johannes Doerferteca9e892015-11-03 16:54:49 +00002670 // Remove read only statements only after invariant loop hoisting.
2671 if (!RemoveStmt && !RemoveIgnoredStmts) {
2672 bool OnlyRead = true;
2673 for (MemoryAccess *MA : Stmt) {
2674 if (MA->isRead())
2675 continue;
2676
2677 OnlyRead = false;
2678 break;
2679 }
2680
2681 RemoveStmt = OnlyRead;
2682 }
2683
2684 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00002685 // Remove the statement because it is unnecessary.
2686 if (Stmt.isRegionStmt())
2687 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2688 StmtMap.erase(BB);
2689 else
2690 StmtMap.erase(Stmt.getBasicBlock());
2691
2692 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002693 continue;
2694 }
2695
Michael Krusecac948e2015-10-02 13:53:07 +00002696 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002697 }
2698}
2699
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002700const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2701 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2702 if (!LInst)
2703 return nullptr;
2704
2705 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2706 LInst = cast<LoadInst>(Rep);
2707
2708 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2709 for (auto &IAClass : InvariantEquivClasses)
2710 if (PointerSCEV == std::get<0>(IAClass))
2711 return &IAClass;
2712
2713 return nullptr;
2714}
2715
2716void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2717
2718 // Get the context under which the statement is executed.
2719 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2720 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2721 DomainCtx = isl_set_detect_equalities(DomainCtx);
2722 DomainCtx = isl_set_coalesce(DomainCtx);
2723
2724 // Project out all parameters that relate to loads in the statement. Otherwise
2725 // we could have cyclic dependences on the constraints under which the
2726 // hoisted loads are executed and we could not determine an order in which to
2727 // pre-load them. This happens because not only lower bounds are part of the
2728 // domain but also upper bounds.
2729 for (MemoryAccess *MA : InvMAs) {
2730 Instruction *AccInst = MA->getAccessInstruction();
2731 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00002732 SetVector<Value *> Values;
2733 for (const SCEV *Parameter : Parameters) {
2734 Values.clear();
2735 findValues(Parameter, Values);
2736 if (!Values.count(AccInst))
2737 continue;
2738
2739 if (isl_id *ParamId = getIdForParam(Parameter)) {
2740 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2741 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2742 isl_id_free(ParamId);
2743 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002744 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002745 }
2746 }
2747
2748 for (MemoryAccess *MA : InvMAs) {
2749 // Check for another invariant access that accesses the same location as
2750 // MA and if found consolidate them. Otherwise create a new equivalence
2751 // class at the end of InvariantEquivClasses.
2752 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
2753 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2754
2755 bool Consolidated = false;
2756 for (auto &IAClass : InvariantEquivClasses) {
2757 if (PointerSCEV != std::get<0>(IAClass))
2758 continue;
2759
2760 Consolidated = true;
2761
2762 // Add MA to the list of accesses that are in this class.
2763 auto &MAs = std::get<1>(IAClass);
2764 MAs.push_front(MA);
2765
2766 // Unify the execution context of the class and this statement.
2767 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002768 if (IAClassDomainCtx)
2769 IAClassDomainCtx = isl_set_coalesce(
2770 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
2771 else
2772 IAClassDomainCtx = isl_set_copy(DomainCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002773 break;
2774 }
2775
2776 if (Consolidated)
2777 continue;
2778
2779 // If we did not consolidate MA, thus did not find an equivalence class
2780 // for it, we create a new one.
2781 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
2782 isl_set_copy(DomainCtx));
2783 }
2784
2785 isl_set_free(DomainCtx);
2786}
2787
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002788void Scop::hoistInvariantLoads() {
2789 isl_union_map *Writes = getWrites();
2790 for (ScopStmt &Stmt : *this) {
2791
2792 // TODO: Loads that are not loop carried, hence are in a statement with
2793 // zero iterators, are by construction invariant, though we
Johannes Doerfert09e36972015-10-07 20:17:36 +00002794 // currently "hoist" them anyway. This is necessary because we allow
2795 // them to be treated as parameters (e.g., in conditions) and our code
2796 // generation would otherwise use the old value.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002797
Johannes Doerfert8930f482015-10-02 14:51:00 +00002798 BasicBlock *BB = Stmt.isBlockStmt() ? Stmt.getBasicBlock()
2799 : Stmt.getRegion()->getEntry();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002800 isl_set *Domain = Stmt.getDomain();
2801 MemoryAccessList InvMAs;
2802
2803 for (MemoryAccess *MA : Stmt) {
2804 if (MA->isImplicit() || MA->isWrite() || !MA->isAffine())
2805 continue;
2806
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002807 // Skip accesses that have an invariant base pointer which is defined but
2808 // not loaded inside the SCoP. This can happened e.g., if a readnone call
2809 // returns a pointer that is used as a base address. However, as we want
2810 // to hoist indirect pointers, we allow the base pointer to be defined in
Johannes Doerfert654c3282015-10-21 22:14:57 +00002811 // the region if it is also a memory access. Each ScopArrayInfo object
2812 // that has a base pointer origin has a base pointer that is loaded and
2813 // that it is invariant, thus it will be hoisted too. However, if there is
Tobias Grosser27e19a02015-10-25 12:05:14 +00002814 // no base pointer origin we check that the base pointer is defined
Johannes Doerfert654c3282015-10-21 22:14:57 +00002815 // outside the region.
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002816 const ScopArrayInfo *SAI = MA->getScopArrayInfo();
Johannes Doerfert654c3282015-10-21 22:14:57 +00002817 while (auto *BasePtrOriginSAI = SAI->getBasePtrOriginSAI())
2818 SAI = BasePtrOriginSAI;
2819
2820 if (auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr()))
2821 if (R.contains(BasePtrInst))
2822 continue;
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002823
Johannes Doerfert8930f482015-10-02 14:51:00 +00002824 // Skip accesses in non-affine subregions as they might not be executed
2825 // under the same condition as the entry of the non-affine subregion.
2826 if (BB != MA->getAccessInstruction()->getParent())
2827 continue;
2828
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002829 isl_map *AccessRelation = MA->getAccessRelation();
Johannes Doerfertb864c2c2015-10-18 19:50:18 +00002830
2831 // Skip accesses that have an empty access relation. These can be caused
2832 // by multiple offsets with a type cast in-between that cause the overall
2833 // byte offset to be not divisible by the new types sizes.
2834 if (isl_map_is_empty(AccessRelation)) {
2835 isl_map_free(AccessRelation);
2836 continue;
2837 }
2838
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002839 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
2840 Stmt.getNumIterators())) {
2841 isl_map_free(AccessRelation);
2842 continue;
2843 }
2844
2845 AccessRelation =
2846 isl_map_intersect_domain(AccessRelation, isl_set_copy(Domain));
2847 isl_set *AccessRange = isl_map_range(AccessRelation);
2848
2849 isl_union_map *Written = isl_union_map_intersect_range(
2850 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
2851 bool IsWritten = !isl_union_map_is_empty(Written);
2852 isl_union_map_free(Written);
2853
2854 if (IsWritten)
2855 continue;
2856
2857 InvMAs.push_front(MA);
2858 }
2859
2860 // We inserted invariant accesses always in the front but need them to be
2861 // sorted in a "natural order". The statements are already sorted in reverse
2862 // post order and that suffices for the accesses too. The reason we require
2863 // an order in the first place is the dependences between invariant loads
2864 // that can be caused by indirect loads.
2865 InvMAs.reverse();
2866
2867 // Transfer the memory access from the statement to the SCoP.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002868 Stmt.removeMemoryAccesses(InvMAs);
2869 addInvariantLoads(Stmt, InvMAs);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002870
2871 isl_set_free(Domain);
2872 }
2873 isl_union_map_free(Writes);
2874
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002875 auto &ScopRIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert09e36972015-10-07 20:17:36 +00002876 // Check required invariant loads that were tagged during SCoP detection.
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002877 for (LoadInst *LI : ScopRIL) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00002878 assert(LI && getRegion().contains(LI));
2879 ScopStmt *Stmt = getStmtForBasicBlock(LI->getParent());
2880 if (Stmt && Stmt->lookupAccessesFor(LI) != nullptr) {
2881 DEBUG(dbgs() << "\n\nWARNING: Load (" << *LI
2882 << ") is required to be invariant but was not marked as "
2883 "such. SCoP for "
2884 << getRegion() << " will be dropped\n\n");
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002885 addAssumption(INVARIANTLOAD, isl_set_empty(getParamSpace()),
2886 LI->getDebugLoc());
Johannes Doerfert09e36972015-10-07 20:17:36 +00002887 return;
2888 }
2889 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002890}
2891
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002892const ScopArrayInfo *
2893Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002894 ArrayRef<const SCEV *> Sizes,
2895 ScopArrayInfo::ARRAYKIND Kind) {
2896 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002897 if (!SAI) {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00002898 auto &DL = getRegion().getEntry()->getModule()->getDataLayout();
2899 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, Kind,
2900 DL, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002901 } else {
Tobias Grosser8286b832015-11-02 11:29:32 +00002902 // In case of mismatching array sizes, we bail out by setting the run-time
2903 // context to false.
2904 if (!SAI->updateSizes(Sizes))
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002905 addAssumption(DELINEARIZATION, isl_set_empty(getParamSpace()),
2906 DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002907 }
Tobias Grosserab671442015-05-23 05:58:27 +00002908 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002909}
2910
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002911const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
2912 ScopArrayInfo::ARRAYKIND Kind) {
2913 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002914 assert(SAI && "No ScopArrayInfo available for this base pointer");
2915 return SAI;
2916}
2917
Tobias Grosser74394f02013-01-14 22:40:23 +00002918std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002919std::string Scop::getAssumedContextStr() const {
2920 return stringFromIslObj(AssumedContext);
2921}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002922std::string Scop::getBoundaryContextStr() const {
2923 return stringFromIslObj(BoundaryContext);
2924}
Tobias Grosser75805372011-04-29 06:27:02 +00002925
2926std::string Scop::getNameStr() const {
2927 std::string ExitName, EntryName;
2928 raw_string_ostream ExitStr(ExitName);
2929 raw_string_ostream EntryStr(EntryName);
2930
Tobias Grosserf240b482014-01-09 10:42:15 +00002931 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002932 EntryStr.str();
2933
2934 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00002935 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002936 ExitStr.str();
2937 } else
2938 ExitName = "FunctionExit";
2939
2940 return EntryName + "---" + ExitName;
2941}
2942
Tobias Grosser74394f02013-01-14 22:40:23 +00002943__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00002944__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002945 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00002946}
2947
Tobias Grossere86109f2013-10-29 21:05:49 +00002948__isl_give isl_set *Scop::getAssumedContext() const {
2949 return isl_set_copy(AssumedContext);
2950}
2951
Johannes Doerfert43788c52015-08-20 05:58:56 +00002952__isl_give isl_set *Scop::getRuntimeCheckContext() const {
2953 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002954 RuntimeCheckContext =
2955 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
2956 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002957 return RuntimeCheckContext;
2958}
2959
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002960bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002961 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002962 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002963 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
2964 isl_set_free(RuntimeCheckContext);
2965 return IsFeasible;
2966}
2967
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002968static std::string toString(AssumptionKind Kind) {
2969 switch (Kind) {
2970 case ALIASING:
2971 return "No-aliasing";
2972 case INBOUNDS:
2973 return "Inbounds";
2974 case WRAPPING:
2975 return "No-overflows";
Johannes Doerferta4b77c02015-11-12 20:15:32 +00002976 case ALIGNMENT:
2977 return "Alignment";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002978 case ERRORBLOCK:
2979 return "No-error";
2980 case INFINITELOOP:
2981 return "Finite loop";
2982 case INVARIANTLOAD:
2983 return "Invariant load";
2984 case DELINEARIZATION:
2985 return "Delinearization";
2986 }
2987 llvm_unreachable("Unknown AssumptionKind!");
2988}
2989
2990void Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
2991 DebugLoc Loc) {
2992 if (isl_set_is_subset(Context, Set))
2993 return;
2994
2995 if (isl_set_is_subset(AssumedContext, Set))
2996 return;
2997
2998 auto &F = *getRegion().getEntry()->getParent();
2999 std::string Msg = toString(Kind) + " assumption:\t" + stringFromIslObj(Set);
3000 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
3001}
3002
3003void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
3004 DebugLoc Loc) {
3005 trackAssumption(Kind, Set, Loc);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003006 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003007
Johannes Doerfert9d7899e2015-11-11 20:01:31 +00003008 int NSets = isl_set_n_basic_set(AssumedContext);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003009 if (NSets >= MaxDisjunctsAssumed) {
3010 isl_space *Space = isl_set_get_space(AssumedContext);
3011 isl_set_free(AssumedContext);
Tobias Grossere19fca42015-11-11 20:21:39 +00003012 AssumedContext = isl_set_empty(Space);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003013 }
3014
Tobias Grosser7b50bee2014-11-25 10:51:12 +00003015 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003016}
3017
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003018__isl_give isl_set *Scop::getBoundaryContext() const {
3019 return isl_set_copy(BoundaryContext);
3020}
3021
Tobias Grosser75805372011-04-29 06:27:02 +00003022void Scop::printContext(raw_ostream &OS) const {
3023 OS << "Context:\n";
3024
3025 if (!Context) {
3026 OS.indent(4) << "n/a\n\n";
3027 return;
3028 }
3029
3030 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003031
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003032 OS.indent(4) << "Assumed Context:\n";
3033 if (!AssumedContext) {
3034 OS.indent(4) << "n/a\n\n";
3035 return;
3036 }
3037
3038 OS.indent(4) << getAssumedContextStr() << "\n";
3039
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003040 OS.indent(4) << "Boundary Context:\n";
3041 if (!BoundaryContext) {
3042 OS.indent(4) << "n/a\n\n";
3043 return;
3044 }
3045
3046 OS.indent(4) << getBoundaryContextStr() << "\n";
3047
Tobias Grosser083d3d32014-06-28 08:59:45 +00003048 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00003049 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00003050 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
3051 }
Tobias Grosser75805372011-04-29 06:27:02 +00003052}
3053
Johannes Doerfertb164c792014-09-18 11:17:17 +00003054void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003055 int noOfGroups = 0;
3056 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003057 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003058 noOfGroups += 1;
3059 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003060 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003061 }
3062
Tobias Grosserbb853c22015-07-25 12:31:03 +00003063 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003064 if (MinMaxAliasGroups.empty()) {
3065 OS.indent(8) << "n/a\n";
3066 return;
3067 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003068
Tobias Grosserbb853c22015-07-25 12:31:03 +00003069 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003070
3071 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003072 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003073 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003074 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003075 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3076 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003077 }
3078 OS << " ]]\n";
3079 }
3080
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003081 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003082 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003083 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003084 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003085 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3086 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003087 }
3088 OS << " ]]\n";
3089 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003090 }
3091}
3092
Tobias Grosser75805372011-04-29 06:27:02 +00003093void Scop::printStatements(raw_ostream &OS) const {
3094 OS << "Statements {\n";
3095
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003096 for (const ScopStmt &Stmt : *this)
3097 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003098
3099 OS.indent(4) << "}\n";
3100}
3101
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003102void Scop::printArrayInfo(raw_ostream &OS) const {
3103 OS << "Arrays {\n";
3104
Tobias Grosserab671442015-05-23 05:58:27 +00003105 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003106 Array.second->print(OS);
3107
3108 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003109
3110 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3111
3112 for (auto &Array : arrays())
3113 Array.second->print(OS, /* SizeAsPwAff */ true);
3114
3115 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003116}
3117
Tobias Grosser75805372011-04-29 06:27:02 +00003118void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00003119 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
3120 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003121 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003122 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003123 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003124 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003125 const auto &MAs = std::get<1>(IAClass);
3126 if (MAs.empty()) {
3127 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003128 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003129 MAs.front()->print(OS);
3130 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003131 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003132 }
3133 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003134 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003135 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003136 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003137 printStatements(OS.indent(4));
3138}
3139
3140void Scop::dump() const { print(dbgs()); }
3141
Tobias Grosser9a38ab82011-11-08 15:41:03 +00003142isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00003143
Johannes Doerfertcef616f2015-09-15 22:49:04 +00003144__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
3145 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003146}
3147
Tobias Grosser808cd692015-07-14 09:33:13 +00003148__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003149 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003150
Tobias Grosser808cd692015-07-14 09:33:13 +00003151 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003152 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003153
3154 return Domain;
3155}
3156
Tobias Grossere5a35142015-11-12 14:07:09 +00003157__isl_give isl_union_map *
3158Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3159 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003160
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003161 for (ScopStmt &Stmt : *this) {
3162 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003163 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003164 continue;
3165
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003166 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003167 isl_map *AccessDomain = MA->getAccessRelation();
3168 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003169 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003170 }
3171 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003172 return isl_union_map_coalesce(Accesses);
3173}
3174
3175__isl_give isl_union_map *Scop::getMustWrites() {
3176 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003177}
3178
3179__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003180 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003181}
3182
Tobias Grosser37eb4222014-02-20 21:43:54 +00003183__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003184 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003185}
3186
3187__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003188 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003189}
3190
Tobias Grosser2ac23382015-11-12 14:07:13 +00003191__isl_give isl_union_map *Scop::getAccesses() {
3192 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3193}
3194
Tobias Grosser808cd692015-07-14 09:33:13 +00003195__isl_give isl_union_map *Scop::getSchedule() const {
3196 auto Tree = getScheduleTree();
3197 auto S = isl_schedule_get_map(Tree);
3198 isl_schedule_free(Tree);
3199 return S;
3200}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003201
Tobias Grosser808cd692015-07-14 09:33:13 +00003202__isl_give isl_schedule *Scop::getScheduleTree() const {
3203 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3204 getDomains());
3205}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003206
Tobias Grosser808cd692015-07-14 09:33:13 +00003207void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3208 auto *S = isl_schedule_from_domain(getDomains());
3209 S = isl_schedule_insert_partial_schedule(
3210 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3211 isl_schedule_free(Schedule);
3212 Schedule = S;
3213}
3214
3215void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3216 isl_schedule_free(Schedule);
3217 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003218}
3219
3220bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3221 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003222 for (ScopStmt &Stmt : *this) {
3223 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003224 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3225 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3226
3227 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3228 isl_union_set_free(StmtDomain);
3229 isl_union_set_free(NewStmtDomain);
3230 continue;
3231 }
3232
3233 Changed = true;
3234
3235 isl_union_set_free(StmtDomain);
3236 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3237
3238 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003239 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003240 isl_union_set_free(NewStmtDomain);
3241 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003242 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003243 }
3244 isl_union_set_free(Domain);
3245 return Changed;
3246}
3247
Tobias Grosser75805372011-04-29 06:27:02 +00003248ScalarEvolution *Scop::getSE() const { return SE; }
3249
Johannes Doerfertf5673802015-10-01 23:48:18 +00003250bool Scop::isIgnored(RegionNode *RN) {
3251 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser75805372011-04-29 06:27:02 +00003252
Johannes Doerfertf5673802015-10-01 23:48:18 +00003253 // Check if there are accesses contained.
3254 bool ContainsAccesses = false;
3255 if (!RN->isSubRegion())
3256 ContainsAccesses = getAccessFunctions(BB);
3257 else
3258 for (BasicBlock *RBB : RN->getNodeAs<Region>()->blocks())
3259 ContainsAccesses |= (getAccessFunctions(RBB) != nullptr);
3260 if (!ContainsAccesses)
3261 return true;
3262
3263 // Check for reachability via non-error blocks.
3264 if (!DomainMap.count(BB))
3265 return true;
3266
3267 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003268 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003269 return true;
3270
3271 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003272}
3273
Tobias Grosser808cd692015-07-14 09:33:13 +00003274struct MapToDimensionDataTy {
3275 int N;
3276 isl_union_pw_multi_aff *Res;
3277};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003278
Tobias Grosser808cd692015-07-14 09:33:13 +00003279// @brief Create a function that maps the elements of 'Set' to its N-th
3280// dimension.
3281//
3282// The result is added to 'User->Res'.
3283//
3284// @param Set The input set.
3285// @param N The dimension to map to.
3286//
3287// @returns Zero if no error occurred, non-zero otherwise.
3288static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3289 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3290 int Dim;
3291 isl_space *Space;
3292 isl_pw_multi_aff *PMA;
3293
3294 Dim = isl_set_dim(Set, isl_dim_set);
3295 Space = isl_set_get_space(Set);
3296 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3297 Dim - Data->N);
3298 if (Data->N > 1)
3299 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3300 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3301
3302 isl_set_free(Set);
3303
3304 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003305}
3306
Tobias Grosser808cd692015-07-14 09:33:13 +00003307// @brief Create a function that maps the elements of Domain to their Nth
3308// dimension.
3309//
3310// @param Domain The set of elements to map.
3311// @param N The dimension to map to.
3312static __isl_give isl_multi_union_pw_aff *
3313mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003314 if (N <= 0 || isl_union_set_is_empty(Domain)) {
3315 isl_union_set_free(Domain);
3316 return nullptr;
3317 }
3318
Tobias Grosser808cd692015-07-14 09:33:13 +00003319 struct MapToDimensionDataTy Data;
3320 isl_space *Space;
3321
3322 Space = isl_union_set_get_space(Domain);
3323 Data.N = N;
3324 Data.Res = isl_union_pw_multi_aff_empty(Space);
3325 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
3326 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
3327
3328 isl_union_set_free(Domain);
3329 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3330}
3331
Tobias Grosser316b5b22015-11-11 19:28:14 +00003332void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003333 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003334 Stmts.emplace_back(*this, *BB);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003335 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003336 StmtMap[BB] = Stmt;
3337 } else {
3338 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003339 Stmts.emplace_back(*this, *R);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003340 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003341 for (BasicBlock *BB : R->blocks())
3342 StmtMap[BB] = Stmt;
3343 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003344}
3345
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003346void Scop::buildSchedule(
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003347 Region *R,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003348 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00003349
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003350 if (SD.isNonAffineSubRegion(R, &getRegion())) {
Johannes Doerfertc6987c12015-09-26 13:41:43 +00003351 Loop *L = getLoopSurroundingRegion(*R, LI);
3352 auto &LSchedulePair = LoopSchedules[L];
Michael Krusecac948e2015-10-02 13:53:07 +00003353 ScopStmt *Stmt = getStmtForBasicBlock(R->getEntry());
Michael Kruseafe06702015-10-02 16:33:27 +00003354 isl_set *Domain = Stmt->getDomain();
Michael Krusecac948e2015-10-02 13:53:07 +00003355 auto *UDomain = isl_union_set_from_set(Domain);
3356 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003357 LSchedulePair.first = StmtSchedule;
3358 return;
3359 }
3360
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003361 ReversePostOrderTraversal<Region *> RTraversal(R);
3362 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00003363
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003364 if (RN->isSubRegion()) {
3365 Region *SubRegion = RN->getNodeAs<Region>();
3366 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003367 buildSchedule(SubRegion, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003368 continue;
3369 }
Tobias Grosser75805372011-04-29 06:27:02 +00003370 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003371
3372 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert30c22652015-10-18 21:17:11 +00003373 if (!getRegion().contains(L))
3374 L = getLoopSurroundingRegion(getRegion(), LI);
3375
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003376 int LD = getRelativeLoopDepth(L);
3377 auto &LSchedulePair = LoopSchedules[L];
3378 LSchedulePair.second += getNumBlocksInRegionNode(RN);
3379
Michael Krusecac948e2015-10-02 13:53:07 +00003380 BasicBlock *BB = getRegionNodeBasicBlock(RN);
3381 ScopStmt *Stmt = getStmtForBasicBlock(BB);
3382 if (Stmt) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003383 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3384 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
3385 LSchedulePair.first =
3386 combineInSequence(LSchedulePair.first, StmtSchedule);
3387 }
3388
3389 unsigned NumVisited = LSchedulePair.second;
3390 while (L && NumVisited == L->getNumBlocks()) {
3391 auto *LDomain = isl_schedule_get_domain(LSchedulePair.first);
3392 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
3393 LSchedulePair.first =
3394 isl_schedule_insert_partial_schedule(LSchedulePair.first, MUPA);
3395
3396 auto *PL = L->getParentLoop();
Johannes Doerfertdca28372015-11-03 00:28:07 +00003397
3398 // Either we have a proper loop and we also build a schedule for the
3399 // parent loop or we have a infinite loop that does not have a proper
3400 // parent loop. In the former case this conditional will be skipped, in
3401 // the latter case however we will break here as we do not build a domain
3402 // nor a schedule for a infinite loop.
3403 assert(LoopSchedules.count(PL) || LSchedulePair.first == nullptr);
3404 if (!LoopSchedules.count(PL))
3405 break;
3406
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003407 auto &PSchedulePair = LoopSchedules[PL];
3408 PSchedulePair.first =
3409 combineInSequence(PSchedulePair.first, LSchedulePair.first);
3410 PSchedulePair.second += NumVisited;
3411
3412 L = PL;
3413 NumVisited = PSchedulePair.second;
3414 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003415 }
Tobias Grosser75805372011-04-29 06:27:02 +00003416}
3417
Johannes Doerfert7c494212014-10-31 23:13:39 +00003418ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003419 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003420 if (StmtMapIt == StmtMap.end())
3421 return nullptr;
3422 return StmtMapIt->second;
3423}
3424
Johannes Doerfert96425c22015-08-30 21:13:53 +00003425int Scop::getRelativeLoopDepth(const Loop *L) const {
3426 Loop *OuterLoop =
3427 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3428 if (!OuterLoop)
3429 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003430 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3431}
3432
Michael Krused868b5d2015-09-10 15:25:24 +00003433void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003434 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003435
3436 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3437 // true, are not modeled as ordinary PHI nodes as they are not part of the
3438 // region. However, we model the operands in the predecessor blocks that are
3439 // part of the region as regular scalar accesses.
3440
3441 // If we can synthesize a PHI we can skip it, however only if it is in
3442 // the region. If it is not it can only be in the exit block of the region.
3443 // In this case we model the operands but not the PHI itself.
3444 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3445 return;
3446
3447 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3448 // detection. Hence, the PHI is a load of a new memory location in which the
3449 // incoming value was written at the end of the incoming basic block.
3450 bool OnlyNonAffineSubRegionOperands = true;
3451 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3452 Value *Op = PHI->getIncomingValue(u);
3453 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3454
3455 // Do not build scalar dependences inside a non-affine subregion.
3456 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3457 continue;
3458
3459 OnlyNonAffineSubRegionOperands = false;
3460
3461 if (!R.contains(OpBB))
3462 continue;
3463
3464 Instruction *OpI = dyn_cast<Instruction>(Op);
3465 if (OpI) {
3466 BasicBlock *OpIBB = OpI->getParent();
3467 // As we pretend there is a use (or more precise a write) of OpI in OpBB
3468 // we have to insert a scalar dependence from the definition of OpI to
3469 // OpBB if the definition is not in OpBB.
Michael Kruse668af712015-10-15 14:45:48 +00003470 if (scop->getStmtForBasicBlock(OpIBB) !=
3471 scop->getStmtForBasicBlock(OpBB)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003472 addScalarReadAccess(OpI, PHI, OpBB);
3473 addScalarWriteAccess(OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003474 }
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003475 } else if (ModelReadOnlyScalars && !isa<Constant>(Op)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003476 addScalarReadAccess(Op, PHI, OpBB);
Michael Kruse7bf39442015-09-10 12:46:52 +00003477 }
3478
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003479 addPHIWriteAccess(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003480 }
3481
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003482 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3483 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003484 }
3485}
3486
Michael Krused868b5d2015-09-10 15:25:24 +00003487bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
3488 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003489 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
3490 if (isIgnoredIntrinsic(Inst))
3491 return false;
3492
3493 bool AnyCrossStmtUse = false;
3494 BasicBlock *ParentBB = Inst->getParent();
3495
3496 for (User *U : Inst->users()) {
3497 Instruction *UI = dyn_cast<Instruction>(U);
3498
3499 // Ignore the strange user
3500 if (UI == 0)
3501 continue;
3502
3503 BasicBlock *UseParent = UI->getParent();
3504
Tobias Grosserbaffa092015-10-24 20:55:27 +00003505 // Ignore basic block local uses. A value that is defined in a scop, but
3506 // used in a PHI node in the same basic block does not count as basic block
3507 // local, as for such cases a control flow edge is passed between definition
3508 // and use.
3509 if (UseParent == ParentBB && !isa<PHINode>(UI))
Michael Kruse7bf39442015-09-10 12:46:52 +00003510 continue;
3511
Michael Krusef714d472015-11-05 13:18:43 +00003512 // Uses by PHI nodes in the entry node count as external uses in case the
3513 // use is through an incoming block that is itself not contained in the
3514 // region.
3515 if (R->getEntry() == UseParent) {
3516 if (auto *PHI = dyn_cast<PHINode>(UI)) {
3517 bool ExternalUse = false;
3518 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
3519 if (PHI->getIncomingValue(i) == Inst &&
3520 !R->contains(PHI->getIncomingBlock(i))) {
3521 ExternalUse = true;
3522 break;
3523 }
3524 }
3525
3526 if (ExternalUse) {
3527 AnyCrossStmtUse = true;
3528 continue;
3529 }
3530 }
3531 }
3532
Michael Kruse7bf39442015-09-10 12:46:52 +00003533 // Do not build scalar dependences inside a non-affine subregion.
3534 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
3535 continue;
3536
Michael Kruse01cb3792015-10-17 21:07:08 +00003537 // Check for PHI nodes in the region exit and skip them, if they will be
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003538 // modeled as PHI nodes.
Michael Kruse01cb3792015-10-17 21:07:08 +00003539 //
3540 // PHI nodes in the region exit that have more than two incoming edges need
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003541 // to be modeled as PHI-Nodes to correctly model the fact that depending on
3542 // the control flow a different value will be assigned to the PHI node. In
3543 // case this is the case, there is no need to create an additional normal
3544 // scalar dependence. Hence, bail out before we register an "out-of-region"
3545 // use for this definition.
Michael Kruse01cb3792015-10-17 21:07:08 +00003546 if (isa<PHINode>(UI) && UI->getParent() == R->getExit() &&
3547 !R->getExitingBlock())
3548 continue;
3549
Michael Kruse7bf39442015-09-10 12:46:52 +00003550 // Check whether or not the use is in the SCoP.
Tobias Grosserc73d8b02015-10-23 22:36:22 +00003551 if (!R->contains(UseParent)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003552 AnyCrossStmtUse = true;
3553 continue;
3554 }
3555
3556 // If the instruction can be synthesized and the user is in the region
3557 // we do not need to add scalar dependences.
3558 if (canSynthesizeInst)
3559 continue;
3560
3561 // No need to translate these scalar dependences into polyhedral form,
3562 // because synthesizable scalars can be generated by the code generator.
3563 if (canSynthesize(UI, LI, SE, R))
3564 continue;
3565
3566 // Skip PHI nodes in the region as they handle their operands on their own.
3567 if (isa<PHINode>(UI))
3568 continue;
3569
3570 // Now U is used in another statement.
3571 AnyCrossStmtUse = true;
3572
3573 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00003574 // Use the def instruction as base address of the MemoryAccess, so that it
3575 // will become the name of the scalar access in the polyhedral form.
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003576 addScalarReadAccess(Inst, UI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003577 }
3578
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003579 if (ModelReadOnlyScalars && !isa<PHINode>(Inst)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003580 for (Value *Op : Inst->operands()) {
3581 if (canSynthesize(Op, LI, SE, R))
3582 continue;
3583
3584 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
3585 if (R->contains(OpInst))
3586 continue;
3587
3588 if (isa<Constant>(Op))
3589 continue;
3590
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003591 addScalarReadAccess(Op, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003592 }
3593 }
3594
3595 return AnyCrossStmtUse;
3596}
3597
3598extern MapInsnToMemAcc InsnToMemAcc;
3599
Michael Krusee2bccbb2015-09-18 19:59:43 +00003600void ScopInfo::buildMemoryAccess(
3601 Instruction *Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003602 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3603 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003604 unsigned Size;
3605 Type *SizeType;
3606 Value *Val;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003607 enum MemoryAccess::AccessType Type;
Michael Kruse7bf39442015-09-10 12:46:52 +00003608
3609 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
3610 SizeType = Load->getType();
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003611 Size = TD->getTypeAllocSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003612 Type = MemoryAccess::READ;
Michael Kruse7bf39442015-09-10 12:46:52 +00003613 Val = Load;
3614 } else {
3615 StoreInst *Store = cast<StoreInst>(Inst);
3616 SizeType = Store->getValueOperand()->getType();
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003617 Size = TD->getTypeAllocSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003618 Type = MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003619 Val = Store->getValueOperand();
3620 }
3621
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003622 auto Address = getPointerOperand(*Inst);
3623
3624 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003625 const SCEVUnknown *BasePointer =
3626 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3627
3628 assert(BasePointer && "Could not find base pointer");
3629 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
3630
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003631 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3632 auto NewAddress = Address;
3633 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3634 auto Src = BitCast->getOperand(0);
3635 auto SrcTy = Src->getType();
3636 auto DstTy = BitCast->getType();
3637 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3638 NewAddress = Src;
3639 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003640
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003641 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3642 std::vector<const SCEV *> Subscripts;
3643 std::vector<int> Sizes;
3644 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3645 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003646
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003647 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003648
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003649 bool AllAffineSubcripts = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003650 for (auto Subscript : Subscripts) {
3651 InvariantLoadsSetTy AccessILS;
3652 AllAffineSubcripts =
3653 isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS);
3654
3655 for (LoadInst *LInst : AccessILS)
3656 if (!ScopRIL.count(LInst))
3657 AllAffineSubcripts = false;
3658
3659 if (!AllAffineSubcripts)
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003660 break;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003661 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003662
3663 if (AllAffineSubcripts && Sizes.size() > 0) {
3664 for (auto V : Sizes)
3665 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3666 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003667 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003668 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003669
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003670 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3671 Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00003672 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003673 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003674 }
3675 }
3676
Michael Kruse7bf39442015-09-10 12:46:52 +00003677 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003678 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003679 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3680 AccItr->second.DelinearizedSubscripts,
3681 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003682 return;
3683 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003684
3685 // Check if the access depends on a loop contained in a non-affine subregion.
3686 bool isVariantInNonAffineLoop = false;
3687 if (BoxedLoops) {
3688 SetVector<const Loop *> Loops;
3689 findLoops(AccessFunction, Loops);
3690 for (const Loop *L : Loops)
3691 if (BoxedLoops->count(L))
3692 isVariantInNonAffineLoop = true;
3693 }
3694
Johannes Doerfert09e36972015-10-07 20:17:36 +00003695 InvariantLoadsSetTy AccessILS;
3696 bool IsAffine =
3697 !isVariantInNonAffineLoop &&
3698 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3699
3700 for (LoadInst *LInst : AccessILS)
3701 if (!ScopRIL.count(LInst))
3702 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003703
Michael Krusecaac2b62015-09-26 15:51:44 +00003704 // FIXME: Size of the number of bytes of an array element, not the number of
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003705 // elements as probably intended here.
Tobias Grossera43b6e92015-09-27 17:54:50 +00003706 const SCEV *SizeSCEV =
3707 SE->getConstant(TD->getIntPtrType(Inst->getContext()), Size);
Michael Kruse7bf39442015-09-10 12:46:52 +00003708
Michael Krusee2bccbb2015-09-18 19:59:43 +00003709 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3710 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003711
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003712 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, IsAffine,
3713 ArrayRef<const SCEV *>(AccessFunction),
3714 ArrayRef<const SCEV *>(SizeSCEV), Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003715}
3716
Michael Krused868b5d2015-09-10 15:25:24 +00003717void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003718
3719 if (SD->isNonAffineSubRegion(&SR, &R)) {
3720 for (BasicBlock *BB : SR.blocks())
3721 buildAccessFunctions(R, *BB, &SR);
3722 return;
3723 }
3724
3725 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3726 if (I->isSubRegion())
3727 buildAccessFunctions(R, *I->getNodeAs<Region>());
3728 else
3729 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
3730}
3731
Michael Krusecac948e2015-10-02 13:53:07 +00003732void ScopInfo::buildStmts(Region &SR) {
3733 Region *R = getRegion();
3734
3735 if (SD->isNonAffineSubRegion(&SR, R)) {
3736 scop->addScopStmt(nullptr, &SR);
3737 return;
3738 }
3739
3740 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3741 if (I->isSubRegion())
3742 buildStmts(*I->getNodeAs<Region>());
3743 else
3744 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
3745}
3746
Michael Krused868b5d2015-09-10 15:25:24 +00003747void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
3748 Region *NonAffineSubRegion,
3749 bool IsExitBlock) {
Tobias Grosser910cf262015-11-11 20:15:49 +00003750 // We do not build access functions for error blocks, as they may contain
3751 // instructions we can not model.
3752 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3753 if (isErrorBlock(BB, R, *LI, DT) && !IsExitBlock)
3754 return;
3755
Michael Kruse7bf39442015-09-10 12:46:52 +00003756 Loop *L = LI->getLoopFor(&BB);
3757
3758 // The set of loops contained in non-affine subregions that are part of R.
3759 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3760
Johannes Doerfert09e36972015-10-07 20:17:36 +00003761 // The set of loads that are required to be invariant.
3762 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
3763
Michael Kruse7bf39442015-09-10 12:46:52 +00003764 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00003765 Instruction *Inst = &*I;
Michael Kruse7bf39442015-09-10 12:46:52 +00003766
3767 PHINode *PHI = dyn_cast<PHINode>(Inst);
3768 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003769 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003770
3771 // For the exit block we stop modeling after the last PHI node.
3772 if (!PHI && IsExitBlock)
3773 break;
3774
Johannes Doerfert09e36972015-10-07 20:17:36 +00003775 // TODO: At this point we only know that elements of ScopRIL have to be
3776 // invariant and will be hoisted for the SCoP to be processed. Though,
3777 // there might be other invariant accesses that will be hoisted and
3778 // that would allow to make a non-affine access affine.
Michael Kruse7bf39442015-09-10 12:46:52 +00003779 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
Johannes Doerfert09e36972015-10-07 20:17:36 +00003780 buildMemoryAccess(Inst, L, &R, BoxedLoops, ScopRIL);
Michael Kruse7bf39442015-09-10 12:46:52 +00003781
3782 if (isIgnoredIntrinsic(Inst))
3783 continue;
3784
Johannes Doerfert09e36972015-10-07 20:17:36 +00003785 // Do not build scalar dependences for required invariant loads as we will
3786 // hoist them later on anyway or drop the SCoP if we cannot.
3787 if (ScopRIL.count(dyn_cast<LoadInst>(Inst)))
3788 continue;
3789
Michael Kruse7bf39442015-09-10 12:46:52 +00003790 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00003791 if (!isa<StoreInst>(Inst))
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003792 addScalarWriteAccess(Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003793 }
3794 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003795}
Michael Kruse7bf39442015-09-10 12:46:52 +00003796
Michael Kruse2d0ece92015-09-24 11:41:21 +00003797void ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3798 MemoryAccess::AccessType Type,
3799 Value *BaseAddress, unsigned ElemBytes,
3800 bool Affine, Value *AccessValue,
3801 ArrayRef<const SCEV *> Subscripts,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003802 ArrayRef<const SCEV *> Sizes,
3803 MemoryAccess::AccessOrigin Origin) {
Michael Krusecac948e2015-10-02 13:53:07 +00003804 ScopStmt *Stmt = scop->getStmtForBasicBlock(BB);
3805
3806 // Do not create a memory access for anything not in the SCoP. It would be
3807 // ignored anyway.
3808 if (!Stmt)
3809 return;
3810
Michael Krusee2bccbb2015-09-18 19:59:43 +00003811 AccFuncSetType &AccList = AccFuncMap[BB];
Michael Krusee2bccbb2015-09-18 19:59:43 +00003812 Value *BaseAddr = BaseAddress;
3813 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3814
Michael Krusecac948e2015-10-02 13:53:07 +00003815 bool isApproximated =
3816 Stmt->isRegionStmt() && (Stmt->getRegion()->getEntry() != BB);
3817 if (isApproximated && Type == MemoryAccess::MUST_WRITE)
3818 Type = MemoryAccess::MAY_WRITE;
3819
Tobias Grosserf1bfd752015-11-05 20:15:37 +00003820 AccList.emplace_back(Stmt, Inst, Type, BaseAddress, ElemBytes, Affine,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003821 Subscripts, Sizes, AccessValue, Origin, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00003822 Stmt->addAccess(&AccList.back());
Michael Kruse7bf39442015-09-10 12:46:52 +00003823}
3824
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003825void ScopInfo::addExplicitAccess(
3826 Instruction *MemAccInst, MemoryAccess::AccessType Type, Value *BaseAddress,
3827 unsigned ElemBytes, bool IsAffine, ArrayRef<const SCEV *> Subscripts,
3828 ArrayRef<const SCEV *> Sizes, Value *AccessValue) {
3829 assert(isa<LoadInst>(MemAccInst) || isa<StoreInst>(MemAccInst));
3830 assert(isa<LoadInst>(MemAccInst) == (Type == MemoryAccess::READ));
3831 addMemoryAccess(MemAccInst->getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003832 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
3833 MemoryAccess::EXPLICIT);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003834}
3835void ScopInfo::addScalarWriteAccess(Instruction *Value) {
3836 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
3837 true, Value, ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003838 ArrayRef<const SCEV *>(), MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003839}
3840void ScopInfo::addScalarReadAccess(Value *Value, Instruction *User) {
3841 assert(!isa<PHINode>(User));
3842 addMemoryAccess(User->getParent(), User, MemoryAccess::READ, Value, 1, true,
3843 Value, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003844 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003845}
3846void ScopInfo::addScalarReadAccess(Value *Value, PHINode *User,
3847 BasicBlock *UserBB) {
3848 addMemoryAccess(UserBB, User, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003849 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3850 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003851}
3852void ScopInfo::addPHIWriteAccess(PHINode *PHI, BasicBlock *IncomingBlock,
3853 Value *IncomingValue, bool IsExitBlock) {
3854 addMemoryAccess(IncomingBlock, IncomingBlock->getTerminator(),
3855 MemoryAccess::MUST_WRITE, PHI, 1, true, IncomingValue,
3856 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003857 IsExitBlock ? MemoryAccess::SCALAR : MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003858}
3859void ScopInfo::addPHIReadAccess(PHINode *PHI) {
3860 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003861 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3862 MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003863}
3864
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003865void ScopInfo::buildScop(Region &R, DominatorTree &DT, AssumptionCache &AC) {
Michael Kruse9d080092015-09-11 21:41:48 +00003866 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003867 scop = new Scop(R, AccFuncMap, *SD, *SE, DT, *LI, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00003868
Michael Krusecac948e2015-10-02 13:53:07 +00003869 buildStmts(R);
Michael Kruse7bf39442015-09-10 12:46:52 +00003870 buildAccessFunctions(R, R);
3871
3872 // In case the region does not have an exiting block we will later (during
3873 // code generation) split the exit block. This will move potential PHI nodes
3874 // from the current exit block into the new region exiting block. Hence, PHI
3875 // nodes that are at this point not part of the region will be.
3876 // To handle these PHI nodes later we will now model their operands as scalar
3877 // accesses. Note that we do not model anything in the exit block if we have
3878 // an exiting block in the region, as there will not be any splitting later.
3879 if (!R.getExitingBlock())
3880 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
3881
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003882 scop->init(*AA, AC);
Michael Kruse7bf39442015-09-10 12:46:52 +00003883}
3884
Michael Krused868b5d2015-09-10 15:25:24 +00003885void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00003886 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00003887 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00003888 return;
3889 }
3890
Michael Kruse9d080092015-09-11 21:41:48 +00003891 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00003892}
3893
Michael Krused868b5d2015-09-10 15:25:24 +00003894void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00003895 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00003896 if (scop) {
3897 delete scop;
3898 scop = 0;
3899 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003900}
3901
3902//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00003903ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00003904 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00003905 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00003906}
3907
3908ScopInfo::~ScopInfo() {
3909 clear();
3910 isl_ctx_free(ctx);
3911}
3912
Tobias Grosser75805372011-04-29 06:27:02 +00003913void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00003914 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00003915 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00003916 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00003917 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
3918 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003919 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003920 AU.addRequired<AssumptionCacheTracker>();
Tobias Grosser75805372011-04-29 06:27:02 +00003921 AU.setPreservesAll();
3922}
3923
3924bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00003925 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00003926
Michael Krused868b5d2015-09-10 15:25:24 +00003927 if (!SD->isMaxRegionInScop(*R))
3928 return false;
3929
3930 Function *F = R->getEntry()->getParent();
3931 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3932 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3933 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3934 TD = &F->getParent()->getDataLayout();
3935 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003936 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krused868b5d2015-09-10 15:25:24 +00003937
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00003938 DebugLoc Beg, End;
3939 getDebugLocations(R, Beg, End);
3940 std::string Msg = "SCoP begins here.";
3941 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg);
3942
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003943 buildScop(*R, DT, AC);
Tobias Grosser75805372011-04-29 06:27:02 +00003944
Tobias Grosserd6a50b32015-05-30 06:26:21 +00003945 DEBUG(scop->print(dbgs()));
3946
Michael Kruseafe06702015-10-02 16:33:27 +00003947 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00003948 Msg = "SCoP ends here but was dismissed.";
Johannes Doerfert43788c52015-08-20 05:58:56 +00003949 delete scop;
3950 scop = nullptr;
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00003951 } else {
3952 Msg = "SCoP ends here.";
3953 ++ScopFound;
3954 if (scop->getMaxLoopDepth() > 0)
3955 ++RichScopFound;
Johannes Doerfert43788c52015-08-20 05:58:56 +00003956 }
3957
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00003958 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg);
3959
Tobias Grosser75805372011-04-29 06:27:02 +00003960 return false;
3961}
3962
3963char ScopInfo::ID = 0;
3964
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003965Pass *polly::createScopInfoPass() { return new ScopInfo(); }
3966
Tobias Grosser73600b82011-10-08 00:30:40 +00003967INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
3968 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003969 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003970INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003971INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00003972INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00003973INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00003974INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003975INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003976INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00003977INITIALIZE_PASS_END(ScopInfo, "polly-scops",
3978 "Polly - Create polyhedral description of Scops", false,
3979 false)