blob: 83f797feb7ca1aac3610bff90a4f685d95af1724 [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,
167 Scop *S)
168 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), 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 {
219 return ElementType->getPrimitiveSizeInBits() / 8;
220}
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
Michael Krusee2bccbb2015-09-18 19:59:43 +0000604void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
605 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000606
Michael Krusee2bccbb2015-09-18 19:59:43 +0000607 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000608 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000609
Michael Krusee2bccbb2015-09-18 19:59:43 +0000610 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000611 // We overapproximate non-affine accesses with a possible access to the
612 // whole array. For read accesses it does not make a difference, if an
613 // access must or may happen. However, for write accesses it is important to
614 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000615 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000616 AccessRelation =
617 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000618
Michael Krusee2bccbb2015-09-18 19:59:43 +0000619 computeBoundsOnAccessRelation(getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000620 return;
621 }
622
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000623 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000624 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000625
Michael Krusee2bccbb2015-09-18 19:59:43 +0000626 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
627 isl_pw_aff *Affine = Statement->getPwAff(Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000628
Sebastian Pop422e33f2014-06-03 18:16:31 +0000629 if (Size == 1) {
630 // For the non delinearized arrays, divide the access function of the last
631 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000632 //
633 // A stride one array access in C expressed as A[i] is expressed in
634 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
635 // two subsequent values of 'i' index two values that are stored next to
636 // each other in memory. By this division we make this characteristic
637 // obvious again.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000638 isl_val *v = isl_val_int_from_si(Ctx, getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000639 Affine = isl_pw_aff_scale_down_val(Affine, v);
640 }
641
642 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
643
Tobias Grosser79baa212014-04-10 08:38:02 +0000644 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000645 }
646
Michael Krusee2bccbb2015-09-18 19:59:43 +0000647 if (Sizes.size() > 1 && !isa<SCEVConstant>(Sizes[0]))
648 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000649
Tobias Grosser79baa212014-04-10 08:38:02 +0000650 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000651 AccessRelation = isl_map_set_tuple_id(
652 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000653 AccessRelation =
654 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
655
Michael Krusee2bccbb2015-09-18 19:59:43 +0000656 assumeNoOutOfBound();
Tobias Grosseraa660a92015-03-30 00:07:50 +0000657 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000658 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000659}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000660
Michael Krusecac948e2015-10-02 13:53:07 +0000661MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000662 AccessType Type, Value *BaseAddress,
663 unsigned ElemBytes, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000664 ArrayRef<const SCEV *> Subscripts,
665 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Michael Kruse8d0b7342015-09-25 21:21:00 +0000666 AccessOrigin Origin, StringRef BaseName)
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000667 : Origin(Origin), AccType(Type), RedType(RT_NONE), Statement(Stmt),
Michael Krusecac948e2015-10-02 13:53:07 +0000668 BaseAddr(BaseAddress), BaseName(BaseName), ElemBytes(ElemBytes),
669 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
670 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000671 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000672 NewAccessRelation(nullptr) {
673
674 std::string IdName = "__polly_array_ref";
675 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
676}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000677
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000678void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000679 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000680 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000681}
682
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000683const std::string MemoryAccess::getReductionOperatorStr() const {
684 return MemoryAccess::getReductionOperatorStr(getReductionType());
685}
686
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000687__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
688
Johannes Doerfertf6183392014-07-01 20:52:51 +0000689raw_ostream &polly::operator<<(raw_ostream &OS,
690 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000691 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000692 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000693 else
694 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000695 return OS;
696}
697
Tobias Grosser75805372011-04-29 06:27:02 +0000698void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000699 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000700 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000701 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000702 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000703 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000704 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000705 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000706 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000707 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000708 break;
709 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000710 OS << "[Reduction Type: " << getReductionType() << "] ";
Michael Kruse8d0b7342015-09-25 21:21:00 +0000711 OS << "[Scalar: " << isImplicit() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000712 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000713 if (hasNewAccessRelation())
714 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000715}
716
Tobias Grosser74394f02013-01-14 22:40:23 +0000717void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000718
719// Create a map in the size of the provided set domain, that maps from the
720// one element of the provided set domain to another element of the provided
721// set domain.
722// The mapping is limited to all points that are equal in all but the last
723// dimension and for which the last dimension of the input is strict smaller
724// than the last dimension of the output.
725//
726// getEqualAndLarger(set[i0, i1, ..., iX]):
727//
728// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
729// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
730//
Tobias Grosserf5338802011-10-06 00:03:35 +0000731static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000732 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000733 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000734 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000735
736 // Set all but the last dimension to be equal for the input and output
737 //
738 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
739 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000740 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000741 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000742
743 // Set the last dimension of the input to be strict smaller than the
744 // last dimension of the output.
745 //
746 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000747 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
748 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000749 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000750}
751
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000752__isl_give isl_set *
753MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000754 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000755 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000756 isl_space *Space = isl_space_range(isl_map_get_space(S));
757 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000758
Sebastian Popa00a0292012-12-18 07:46:06 +0000759 S = isl_map_reverse(S);
760 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000761
Sebastian Popa00a0292012-12-18 07:46:06 +0000762 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
763 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
764 NextScatt = isl_map_apply_domain(NextScatt, S);
765 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000766
Sebastian Popa00a0292012-12-18 07:46:06 +0000767 isl_set *Deltas = isl_map_deltas(NextScatt);
768 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000769}
770
Sebastian Popa00a0292012-12-18 07:46:06 +0000771bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000772 int StrideWidth) const {
773 isl_set *Stride, *StrideX;
774 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000775
Sebastian Popa00a0292012-12-18 07:46:06 +0000776 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000777 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000778 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
779 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
780 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
781 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000782 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000783
Tobias Grosser28dd4862012-01-24 16:42:16 +0000784 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000785 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000786
Tobias Grosser28dd4862012-01-24 16:42:16 +0000787 return IsStrideX;
788}
789
Sebastian Popa00a0292012-12-18 07:46:06 +0000790bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
791 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000792}
793
Sebastian Popa00a0292012-12-18 07:46:06 +0000794bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
795 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000796}
797
Tobias Grosser166c4222015-09-05 07:46:40 +0000798void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
799 isl_map_free(NewAccessRelation);
800 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000801}
Tobias Grosser75805372011-04-29 06:27:02 +0000802
803//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000804
Tobias Grosser808cd692015-07-14 09:33:13 +0000805isl_map *ScopStmt::getSchedule() const {
806 isl_set *Domain = getDomain();
807 if (isl_set_is_empty(Domain)) {
808 isl_set_free(Domain);
809 return isl_map_from_aff(
810 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
811 }
812 auto *Schedule = getParent()->getSchedule();
813 Schedule = isl_union_map_intersect_domain(
814 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
815 if (isl_union_map_is_empty(Schedule)) {
816 isl_set_free(Domain);
817 isl_union_map_free(Schedule);
818 return isl_map_from_aff(
819 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
820 }
821 auto *M = isl_map_from_union_map(Schedule);
822 M = isl_map_coalesce(M);
823 M = isl_map_gist_domain(M, Domain);
824 M = isl_map_coalesce(M);
825 return M;
826}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000827
Johannes Doerfert574182d2015-08-12 10:19:50 +0000828__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000829 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
830 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000831}
832
Tobias Grosser37eb4222014-02-20 21:43:54 +0000833void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
834 assert(isl_set_is_subset(NewDomain, Domain) &&
835 "New domain is not a subset of old domain!");
836 isl_set_free(Domain);
837 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000838}
839
Michael Krusecac948e2015-10-02 13:53:07 +0000840void ScopStmt::buildAccessRelations() {
841 for (MemoryAccess *Access : MemAccs) {
842 Type *ElementType = Access->getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000843
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000844 ScopArrayInfo::ARRAYKIND Ty;
845 if (Access->isPHI())
846 Ty = ScopArrayInfo::KIND_PHI;
847 else if (Access->isImplicit())
848 Ty = ScopArrayInfo::KIND_SCALAR;
849 else
850 Ty = ScopArrayInfo::KIND_ARRAY;
851
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000852 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000853 Access->getBaseAddr(), ElementType, Access->Sizes, Ty);
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000854
Michael Krusecac948e2015-10-02 13:53:07 +0000855 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +0000856 }
857}
858
Michael Krusecac948e2015-10-02 13:53:07 +0000859void ScopStmt::addAccess(MemoryAccess *Access) {
860 Instruction *AccessInst = Access->getAccessInstruction();
861
862 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
863 if (!MAL)
864 MAL = new MemoryAccessList();
865 MAL->emplace_front(Access);
866 MemAccs.push_back(MAL->front());
867}
868
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000869void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000870 for (MemoryAccess *MA : *this)
871 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000872
873 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000874}
875
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000876/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
877static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
878 void *User) {
879 isl_set **BoundedParts = static_cast<isl_set **>(User);
880 if (isl_basic_set_is_bounded(BSet))
881 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
882 else
883 isl_basic_set_free(BSet);
884 return isl_stat_ok;
885}
886
887/// @brief Return the bounded parts of @p S.
888static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
889 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
890 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
891 isl_set_free(S);
892 return BoundedParts;
893}
894
895/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
896///
897/// @returns A separation of @p S into first an unbounded then a bounded subset,
898/// both with regards to the dimension @p Dim.
899static std::pair<__isl_give isl_set *, __isl_give isl_set *>
900partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
901
902 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000903 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000904
905 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000906 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000907
908 // Remove dimensions that are greater than Dim as they are not interesting.
909 assert(NumDimsS >= Dim + 1);
910 OnlyDimS =
911 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
912
913 // Create artificial parametric upper bounds for dimensions smaller than Dim
914 // as we are not interested in them.
915 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
916 for (unsigned u = 0; u < Dim; u++) {
917 isl_constraint *C = isl_inequality_alloc(
918 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
919 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
920 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
921 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
922 }
923
924 // Collect all bounded parts of OnlyDimS.
925 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
926
927 // Create the dimensions greater than Dim again.
928 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
929 NumDimsS - Dim - 1);
930
931 // Remove the artificial upper bound parameters again.
932 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
933
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000934 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000935 return std::make_pair(UnboundedParts, BoundedParts);
936}
937
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000938/// @brief Set the dimension Ids from @p From in @p To.
939static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
940 __isl_take isl_set *To) {
941 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
942 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
943 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
944 }
945 return To;
946}
947
948/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000949static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000950 __isl_take isl_pw_aff *L,
951 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +0000952 switch (Pred) {
953 case ICmpInst::ICMP_EQ:
954 return isl_pw_aff_eq_set(L, R);
955 case ICmpInst::ICMP_NE:
956 return isl_pw_aff_ne_set(L, R);
957 case ICmpInst::ICMP_SLT:
958 return isl_pw_aff_lt_set(L, R);
959 case ICmpInst::ICMP_SLE:
960 return isl_pw_aff_le_set(L, R);
961 case ICmpInst::ICMP_SGT:
962 return isl_pw_aff_gt_set(L, R);
963 case ICmpInst::ICMP_SGE:
964 return isl_pw_aff_ge_set(L, R);
965 case ICmpInst::ICMP_ULT:
966 return isl_pw_aff_lt_set(L, R);
967 case ICmpInst::ICMP_UGT:
968 return isl_pw_aff_gt_set(L, R);
969 case ICmpInst::ICMP_ULE:
970 return isl_pw_aff_le_set(L, R);
971 case ICmpInst::ICMP_UGE:
972 return isl_pw_aff_ge_set(L, R);
973 default:
974 llvm_unreachable("Non integer predicate not supported");
975 }
976}
977
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000978/// @brief Create the conditions under which @p L @p Pred @p R is true.
979///
980/// Helper function that will make sure the dimensions of the result have the
981/// same isl_id's as the @p Domain.
982static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
983 __isl_take isl_pw_aff *L,
984 __isl_take isl_pw_aff *R,
985 __isl_keep isl_set *Domain) {
986 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
987 return setDimensionIds(Domain, ConsequenceCondSet);
988}
989
990/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000991///
992/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000993/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
994/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000995static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000996buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +0000997 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
998
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000999 Value *Condition = getConditionFromTerminator(SI);
1000 assert(Condition && "No condition for switch");
1001
1002 ScalarEvolution &SE = *S.getSE();
1003 BasicBlock *BB = SI->getParent();
1004 isl_pw_aff *LHS, *RHS;
1005 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
1006
1007 unsigned NumSuccessors = SI->getNumSuccessors();
1008 ConditionSets.resize(NumSuccessors);
1009 for (auto &Case : SI->cases()) {
1010 unsigned Idx = Case.getSuccessorIndex();
1011 ConstantInt *CaseValue = Case.getCaseValue();
1012
1013 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
1014 isl_set *CaseConditionSet =
1015 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1016 ConditionSets[Idx] = isl_set_coalesce(
1017 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1018 }
1019
1020 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1021 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1022 for (unsigned u = 2; u < NumSuccessors; u++)
1023 ConditionSetUnion =
1024 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1025 ConditionSets[0] = setDimensionIds(
1026 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1027
1028 S.markAsOptimized();
1029 isl_pw_aff_free(LHS);
1030}
1031
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001032/// @brief Build the conditions sets for the branch condition @p Condition in
1033/// the @p Domain.
1034///
1035/// This will fill @p ConditionSets with the conditions under which control
1036/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001037/// have as many elements as @p TI has successors. If @p TI is nullptr the
1038/// context under which @p Condition is true/false will be returned as the
1039/// new elements of @p ConditionSets.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001040static void
1041buildConditionSets(Scop &S, Value *Condition, TerminatorInst *TI, Loop *L,
1042 __isl_keep isl_set *Domain,
1043 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1044
1045 isl_set *ConsequenceCondSet = nullptr;
1046 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1047 if (CCond->isZero())
1048 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1049 else
1050 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1051 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1052 auto Opcode = BinOp->getOpcode();
1053 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1054
1055 buildConditionSets(S, BinOp->getOperand(0), TI, L, Domain, ConditionSets);
1056 buildConditionSets(S, BinOp->getOperand(1), TI, L, Domain, ConditionSets);
1057
1058 isl_set_free(ConditionSets.pop_back_val());
1059 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1060 isl_set_free(ConditionSets.pop_back_val());
1061 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1062
1063 if (Opcode == Instruction::And)
1064 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1065 else
1066 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1067 } else {
1068 auto *ICond = dyn_cast<ICmpInst>(Condition);
1069 assert(ICond &&
1070 "Condition of exiting branch was neither constant nor ICmp!");
1071
1072 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001073 BasicBlock *BB = TI ? TI->getParent() : nullptr;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001074 isl_pw_aff *LHS, *RHS;
1075 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1076 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
1077 ConsequenceCondSet =
1078 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1079 }
1080
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001081 // If no terminator was given we are only looking for parameter constraints
1082 // under which @p Condition is true/false.
1083 if (!TI)
1084 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
1085
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001086 assert(ConsequenceCondSet);
1087 isl_set *AlternativeCondSet =
1088 isl_set_complement(isl_set_copy(ConsequenceCondSet));
1089
1090 ConditionSets.push_back(isl_set_coalesce(
1091 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
1092 ConditionSets.push_back(isl_set_coalesce(
1093 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
1094}
1095
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001096/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1097///
1098/// This will fill @p ConditionSets with the conditions under which control
1099/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1100/// have as many elements as @p TI has successors.
1101static void
1102buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1103 __isl_keep isl_set *Domain,
1104 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1105
1106 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1107 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1108
1109 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1110
1111 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001112 ConditionSets.push_back(isl_set_copy(Domain));
1113 return;
1114 }
1115
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001116 Value *Condition = getConditionFromTerminator(TI);
1117 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001118
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001119 return buildConditionSets(S, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001120}
1121
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001122void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +00001123 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +00001124
Tobias Grosser084d8f72012-05-29 09:29:44 +00001125 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1126
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001127 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001128 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001129}
1130
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001131void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001132 isl_ctx *Ctx = Parent.getIslCtx();
1133 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1134 Type *Ty = GEP->getPointerOperandType();
1135 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001136 ScopDetection &SD = Parent.getSD();
1137
1138 // The set of loads that are required to be invariant.
1139 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001140
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001141 std::vector<const SCEV *> Subscripts;
1142 std::vector<int> Sizes;
1143
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001144 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001145
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001146 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001147 Ty = PtrTy->getElementType();
1148 }
1149
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001150 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001151
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001152 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001153
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001154 for (size_t i = 0; i < Sizes.size(); i++) {
1155 auto Expr = Subscripts[i + IndexOffset];
1156 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001157
Johannes Doerfert09e36972015-10-07 20:17:36 +00001158 InvariantLoadsSetTy AccessILS;
1159 if (!isAffineExpr(&Parent.getRegion(), Expr, SE, nullptr, &AccessILS))
1160 continue;
1161
1162 bool NonAffine = false;
1163 for (LoadInst *LInst : AccessILS)
1164 if (!ScopRIL.count(LInst))
1165 NonAffine = true;
1166
1167 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001168 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001169
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001170 isl_pw_aff *AccessOffset = getPwAff(Expr);
1171 AccessOffset =
1172 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001173
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001174 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1175 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001176
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001177 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1178 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1179 OutOfBound = isl_set_params(OutOfBound);
1180 isl_set *InBound = isl_set_complement(OutOfBound);
1181 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001182
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001183 // A => B == !A or B
1184 isl_set *InBoundIfExecuted =
1185 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001186
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001187 Parent.addAssumption(INBOUNDS, InBoundIfExecuted, GEP->getDebugLoc());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001188 }
1189
1190 isl_local_space_free(LSpace);
1191}
1192
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001193void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1194 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001195 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1196 deriveAssumptionsFromGEP(GEP);
1197}
1198
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001199void ScopStmt::collectSurroundingLoops() {
1200 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1201 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1202 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1203 isl_id_free(DimId);
1204 }
1205}
1206
Michael Kruse9d080092015-09-11 21:41:48 +00001207ScopStmt::ScopStmt(Scop &parent, Region &R)
Michael Krusecac948e2015-10-02 13:53:07 +00001208 : Parent(parent), Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001209
Tobias Grosser16c44032015-07-09 07:31:45 +00001210 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001211}
1212
Michael Kruse9d080092015-09-11 21:41:48 +00001213ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Michael Krusecac948e2015-10-02 13:53:07 +00001214 : Parent(parent), Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001215
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001216 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001217}
1218
1219void ScopStmt::init() {
1220 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001221
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001222 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001223 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001224 buildAccessRelations();
1225
1226 if (BB) {
1227 deriveAssumptions(BB);
1228 } else {
1229 for (BasicBlock *Block : R->blocks()) {
1230 deriveAssumptions(Block);
1231 }
1232 }
1233
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001234 if (DetectReductions)
1235 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001236}
1237
Johannes Doerferte58a0122014-06-27 20:31:28 +00001238/// @brief Collect loads which might form a reduction chain with @p StoreMA
1239///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001240/// Check if the stored value for @p StoreMA is a binary operator with one or
1241/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001242/// used only once (by @p StoreMA) and its load operands are also used only
1243/// once, we have found a possible reduction chain. It starts at an operand
1244/// load and includes the binary operator and @p StoreMA.
1245///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001246/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001247/// escape this block or into any other store except @p StoreMA.
1248void ScopStmt::collectCandiateReductionLoads(
1249 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1250 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1251 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001252 return;
1253
1254 // Skip if there is not one binary operator between the load and the store
1255 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001256 if (!BinOp)
1257 return;
1258
1259 // Skip if the binary operators has multiple uses
1260 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001261 return;
1262
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001263 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001264 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1265 return;
1266
Johannes Doerfert9890a052014-07-01 00:32:29 +00001267 // Skip if the binary operator is outside the current SCoP
1268 if (BinOp->getParent() != Store->getParent())
1269 return;
1270
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001271 // Skip if it is a multiplicative reduction and we disabled them
1272 if (DisableMultiplicativeReductions &&
1273 (BinOp->getOpcode() == Instruction::Mul ||
1274 BinOp->getOpcode() == Instruction::FMul))
1275 return;
1276
Johannes Doerferte58a0122014-06-27 20:31:28 +00001277 // Check the binary operator operands for a candidate load
1278 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1279 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1280 if (!PossibleLoad0 && !PossibleLoad1)
1281 return;
1282
1283 // A load is only a candidate if it cannot escape (thus has only this use)
1284 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001285 if (PossibleLoad0->getParent() == Store->getParent())
1286 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001287 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001288 if (PossibleLoad1->getParent() == Store->getParent())
1289 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001290}
1291
1292/// @brief Check for reductions in this ScopStmt
1293///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001294/// Iterate over all store memory accesses and check for valid binary reduction
1295/// like chains. For all candidates we check if they have the same base address
1296/// and there are no other accesses which overlap with them. The base address
1297/// check rules out impossible reductions candidates early. The overlap check,
1298/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001299/// guarantees that none of the intermediate results will escape during
1300/// execution of the loop nest. We basically check here that no other memory
1301/// access can access the same memory as the potential reduction.
1302void ScopStmt::checkForReductions() {
1303 SmallVector<MemoryAccess *, 2> Loads;
1304 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1305
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001306 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001307 // stores and collecting possible reduction loads.
1308 for (MemoryAccess *StoreMA : MemAccs) {
1309 if (StoreMA->isRead())
1310 continue;
1311
1312 Loads.clear();
1313 collectCandiateReductionLoads(StoreMA, Loads);
1314 for (MemoryAccess *LoadMA : Loads)
1315 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1316 }
1317
1318 // Then check each possible candidate pair.
1319 for (const auto &CandidatePair : Candidates) {
1320 bool Valid = true;
1321 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1322 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1323
1324 // Skip those with obviously unequal base addresses.
1325 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1326 isl_map_free(LoadAccs);
1327 isl_map_free(StoreAccs);
1328 continue;
1329 }
1330
1331 // And check if the remaining for overlap with other memory accesses.
1332 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1333 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1334 isl_set *AllAccs = isl_map_range(AllAccsRel);
1335
1336 for (MemoryAccess *MA : MemAccs) {
1337 if (MA == CandidatePair.first || MA == CandidatePair.second)
1338 continue;
1339
1340 isl_map *AccRel =
1341 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1342 isl_set *Accs = isl_map_range(AccRel);
1343
1344 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1345 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1346 Valid = Valid && isl_set_is_empty(OverlapAccs);
1347 isl_set_free(OverlapAccs);
1348 }
1349 }
1350
1351 isl_set_free(AllAccs);
1352 if (!Valid)
1353 continue;
1354
Johannes Doerfertf6183392014-07-01 20:52:51 +00001355 const LoadInst *Load =
1356 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1357 MemoryAccess::ReductionType RT =
1358 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1359
Johannes Doerferte58a0122014-06-27 20:31:28 +00001360 // If no overlapping access was found we mark the load and store as
1361 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001362 CandidatePair.first->markAsReductionLike(RT);
1363 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001364 }
Tobias Grosser75805372011-04-29 06:27:02 +00001365}
1366
Tobias Grosser74394f02013-01-14 22:40:23 +00001367std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001368
Tobias Grosser54839312015-04-21 11:37:25 +00001369std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001370 auto *S = getSchedule();
1371 auto Str = stringFromIslObj(S);
1372 isl_map_free(S);
1373 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001374}
1375
Tobias Grosser74394f02013-01-14 22:40:23 +00001376unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001377
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001378unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001379
Tobias Grosser75805372011-04-29 06:27:02 +00001380const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1381
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001382const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001383 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001384}
1385
Tobias Grosser74394f02013-01-14 22:40:23 +00001386isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001387
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001388__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001389
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001390__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001391 return isl_set_get_space(Domain);
1392}
1393
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001394__isl_give isl_id *ScopStmt::getDomainId() const {
1395 return isl_set_get_tuple_id(Domain);
1396}
Tobias Grossercd95b772012-08-30 11:49:38 +00001397
Tobias Grosser75805372011-04-29 06:27:02 +00001398ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001399 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001400 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001401}
1402
1403void ScopStmt::print(raw_ostream &OS) const {
1404 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001405 OS.indent(12) << "Domain :=\n";
1406
1407 if (Domain) {
1408 OS.indent(16) << getDomainStr() << ";\n";
1409 } else
1410 OS.indent(16) << "n/a\n";
1411
Tobias Grosser54839312015-04-21 11:37:25 +00001412 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001413
1414 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001415 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001416 } else
1417 OS.indent(16) << "n/a\n";
1418
Tobias Grosser083d3d32014-06-28 08:59:45 +00001419 for (MemoryAccess *Access : MemAccs)
1420 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001421}
1422
1423void ScopStmt::dump() const { print(dbgs()); }
1424
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001425void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001426
1427 // Remove all memory accesses in @p InvMAs from this statement together
1428 // with all scalar accesses that were caused by them. The tricky iteration
1429 // order uses is needed because the MemAccs is a vector and the order in
1430 // which the accesses of each memory access list (MAL) are stored in this
1431 // vector is reversed.
1432 for (MemoryAccess *MA : InvMAs) {
1433 auto &MAL = *lookupAccessesFor(MA->getAccessInstruction());
1434 MAL.reverse();
1435
1436 auto MALIt = MAL.begin();
1437 auto MALEnd = MAL.end();
1438 auto MemAccsIt = MemAccs.begin();
1439 while (MALIt != MALEnd) {
1440 while (*MemAccsIt != *MALIt)
1441 MemAccsIt++;
1442
1443 MALIt++;
1444 MemAccs.erase(MemAccsIt);
1445 }
1446
1447 InstructionToAccess.erase(MA->getAccessInstruction());
1448 delete &MAL;
1449 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001450}
1451
Tobias Grosser75805372011-04-29 06:27:02 +00001452//===----------------------------------------------------------------------===//
1453/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001454
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001455void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001456 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1457 isl_set_free(Context);
1458 Context = NewContext;
1459}
1460
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001461/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1462struct SCEVSensitiveParameterRewriter
1463 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1464 ValueToValueMap &VMap;
1465 ScalarEvolution &SE;
1466
1467public:
1468 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1469 : VMap(VMap), SE(SE) {}
1470
1471 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1472 ValueToValueMap &VMap) {
1473 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1474 return SSPR.visit(E);
1475 }
1476
1477 const SCEV *visit(const SCEV *E) {
1478 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1479 }
1480
1481 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1482
1483 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1484 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1485 }
1486
1487 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1488 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1489 }
1490
1491 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1492 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1493 }
1494
1495 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1496 SmallVector<const SCEV *, 4> Operands;
1497 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1498 Operands.push_back(visit(E->getOperand(i)));
1499 return SE.getAddExpr(Operands);
1500 }
1501
1502 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1503 SmallVector<const SCEV *, 4> Operands;
1504 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1505 Operands.push_back(visit(E->getOperand(i)));
1506 return SE.getMulExpr(Operands);
1507 }
1508
1509 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1510 SmallVector<const SCEV *, 4> Operands;
1511 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1512 Operands.push_back(visit(E->getOperand(i)));
1513 return SE.getSMaxExpr(Operands);
1514 }
1515
1516 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1517 SmallVector<const SCEV *, 4> Operands;
1518 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1519 Operands.push_back(visit(E->getOperand(i)));
1520 return SE.getUMaxExpr(Operands);
1521 }
1522
1523 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1524 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1525 }
1526
1527 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1528 auto *Start = visit(E->getStart());
1529 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1530 visit(E->getStepRecurrence(SE)),
1531 E->getLoop(), SCEV::FlagAnyWrap);
1532 return SE.getAddExpr(Start, AddRec);
1533 }
1534
1535 const SCEV *visitUnknown(const SCEVUnknown *E) {
1536 if (auto *NewValue = VMap.lookup(E->getValue()))
1537 return SE.getUnknown(NewValue);
1538 return E;
1539 }
1540};
1541
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001542const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001543 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001544}
1545
Tobias Grosserabfbe632013-02-05 12:09:06 +00001546void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001547 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001548 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001549
1550 // Normalize the SCEV to get the representing element for an invariant load.
1551 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1552
Tobias Grosser60b54f12011-11-08 15:41:28 +00001553 if (ParameterIds.find(Parameter) != ParameterIds.end())
1554 continue;
1555
1556 int dimension = Parameters.size();
1557
1558 Parameters.push_back(Parameter);
1559 ParameterIds[Parameter] = dimension;
1560 }
1561}
1562
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001563__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001564 // Normalize the SCEV to get the representing element for an invariant load.
1565 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1566
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001567 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001568
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001569 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001570 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001571
Tobias Grosser8f99c162011-11-15 11:38:55 +00001572 std::string ParameterName;
1573
1574 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1575 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001576 ParameterName = Val->getName();
Johannes Doerferte071f6d2015-11-03 16:49:59 +00001577 if (!Val->hasName())
1578 if (LoadInst *LI = dyn_cast<LoadInst>(Val))
1579 ParameterName =
1580 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001581 }
1582
1583 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001584 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001585
Tobias Grosser20532b82014-04-11 17:56:49 +00001586 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1587 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001588}
Tobias Grosser75805372011-04-29 06:27:02 +00001589
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001590isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1591 isl_set *DomainContext = isl_union_set_params(getDomains());
1592 return isl_set_intersect_params(C, DomainContext);
1593}
1594
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001595void Scop::buildBoundaryContext() {
1596 BoundaryContext = Affinator.getWrappingContext();
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001597
1598 // The isl_set_complement operation used to create the boundary context
1599 // can possibly become very expensive. We bound the compile time of
1600 // this operation by setting a compute out.
1601 //
1602 // TODO: We can probably get around using isl_set_complement and directly
1603 // AST generate BoundaryContext.
1604 long MaxOpsOld = isl_ctx_get_max_operations(getIslCtx());
1605 isl_ctx_set_max_operations(getIslCtx(), 300000);
1606 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_CONTINUE);
1607
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001608 BoundaryContext = isl_set_complement(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001609
Tobias Grossera52b4da2015-11-11 17:59:53 +00001610 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
1611 isl_set_free(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001612 BoundaryContext = isl_set_empty(getParamSpace());
Tobias Grossera52b4da2015-11-11 17:59:53 +00001613 }
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001614
1615 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
1616 isl_ctx_reset_operations(getIslCtx());
1617 isl_ctx_set_max_operations(getIslCtx(), MaxOpsOld);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001618 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001619 trackAssumption(WRAPPING, BoundaryContext, DebugLoc());
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001620}
1621
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001622void Scop::addUserAssumptions(AssumptionCache &AC) {
1623 auto *R = &getRegion();
1624 auto &F = *R->getEntry()->getParent();
1625 for (auto &Assumption : AC.assumptions()) {
1626 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1627 if (!CI || CI->getNumArgOperands() != 1)
1628 continue;
1629 if (!DT.dominates(CI->getParent(), R->getEntry()))
1630 continue;
1631
1632 auto *Val = CI->getArgOperand(0);
1633 std::vector<const SCEV *> Params;
1634 if (!isAffineParamConstraint(Val, R, *SE, Params)) {
1635 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1636 CI->getDebugLoc(),
1637 "Non-affine user assumption ignored.");
1638 continue;
1639 }
1640
1641 addParams(Params);
1642
1643 auto *L = LI.getLoopFor(CI->getParent());
1644 SmallVector<isl_set *, 2> ConditionSets;
1645 buildConditionSets(*this, Val, nullptr, L, Context, ConditionSets);
1646 assert(ConditionSets.size() == 2);
1647 isl_set_free(ConditionSets[1]);
1648
1649 auto *AssumptionCtx = ConditionSets[0];
1650 emitOptimizationRemarkAnalysis(
1651 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1652 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1653 Context = isl_set_intersect(Context, AssumptionCtx);
1654 }
1655}
1656
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001657void Scop::addUserContext() {
1658 if (UserContextStr.empty())
1659 return;
1660
1661 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1662 isl_space *Space = getParamSpace();
1663 if (isl_space_dim(Space, isl_dim_param) !=
1664 isl_set_dim(UserContext, isl_dim_param)) {
1665 auto SpaceStr = isl_space_to_str(Space);
1666 errs() << "Error: the context provided in -polly-context has not the same "
1667 << "number of dimensions than the computed context. Due to this "
1668 << "mismatch, the -polly-context option is ignored. Please provide "
1669 << "the context in the parameter space: " << SpaceStr << ".\n";
1670 free(SpaceStr);
1671 isl_set_free(UserContext);
1672 isl_space_free(Space);
1673 return;
1674 }
1675
1676 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1677 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1678 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1679
1680 if (strcmp(NameContext, NameUserContext) != 0) {
1681 auto SpaceStr = isl_space_to_str(Space);
1682 errs() << "Error: the name of dimension " << i
1683 << " provided in -polly-context "
1684 << "is '" << NameUserContext << "', but the name in the computed "
1685 << "context is '" << NameContext
1686 << "'. Due to this name mismatch, "
1687 << "the -polly-context option is ignored. Please provide "
1688 << "the context in the parameter space: " << SpaceStr << ".\n";
1689 free(SpaceStr);
1690 isl_set_free(UserContext);
1691 isl_space_free(Space);
1692 return;
1693 }
1694
1695 UserContext =
1696 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1697 isl_space_get_dim_id(Space, isl_dim_param, i));
1698 }
1699
1700 Context = isl_set_intersect(Context, UserContext);
1701 isl_space_free(Space);
1702}
1703
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001704void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001705 DenseMap<const SCEV *, LoadInst *> EquivClasses;
1706
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001707 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001708 for (LoadInst *LInst : RIL) {
1709 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1710
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001711 LoadInst *&ClassRep = EquivClasses[PointerSCEV];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001712 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001713 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001714 continue;
1715 }
1716
1717 ClassRep = LInst;
1718 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(),
1719 nullptr);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001720 }
1721}
1722
Tobias Grosser6be480c2011-11-08 15:41:13 +00001723void Scop::buildContext() {
1724 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001725 Context = isl_set_universe(isl_space_copy(Space));
1726 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001727}
1728
Tobias Grosser18daaca2012-05-22 10:47:27 +00001729void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001730 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001731 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001732
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001733 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001734
Johannes Doerferte7044942015-02-24 11:58:30 +00001735 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001736 }
1737}
1738
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001739void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001740 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001741 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001742
Tobias Grosser083d3d32014-06-28 08:59:45 +00001743 for (const auto &ParamID : ParameterIds) {
1744 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001745 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001746 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001747 }
1748
1749 // Align the parameters of all data structures to the model.
1750 Context = isl_set_align_params(Context, Space);
1751
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001752 for (ScopStmt &Stmt : *this)
1753 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001754}
1755
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001756static __isl_give isl_set *
1757simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1758 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001759 // If we modelt all blocks in the SCoP that have side effects we can simplify
1760 // the context with the constraints that are needed for anything to be
1761 // executed at all. However, if we have error blocks in the SCoP we already
1762 // assumed some parameter combinations cannot occure and removed them from the
1763 // domains, thus we cannot use the remaining domain to simplify the
1764 // assumptions.
1765 if (!S.hasErrorBlock()) {
1766 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1767 AssumptionContext =
1768 isl_set_gist_params(AssumptionContext, DomainParameters);
1769 }
1770
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001771 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1772 return AssumptionContext;
1773}
1774
1775void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001776 // The parameter constraints of the iteration domains give us a set of
1777 // constraints that need to hold for all cases where at least a single
1778 // statement iteration is executed in the whole scop. We now simplify the
1779 // assumed context under the assumption that such constraints hold and at
1780 // least a single statement iteration is executed. For cases where no
1781 // statement instances are executed, the assumptions we have taken about
1782 // the executed code do not matter and can be changed.
1783 //
1784 // WARNING: This only holds if the assumptions we have taken do not reduce
1785 // the set of statement instances that are executed. Otherwise we
1786 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001787 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001788 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001789 // performed. In such a case, modifying the run-time conditions and
1790 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001791 // to not be executed.
1792 //
1793 // Example:
1794 //
1795 // When delinearizing the following code:
1796 //
1797 // for (long i = 0; i < 100; i++)
1798 // for (long j = 0; j < m; j++)
1799 // A[i+p][j] = 1.0;
1800 //
1801 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001802 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001803 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001804 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1805 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001806}
1807
Johannes Doerfertb164c792014-09-18 11:17:17 +00001808/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001809static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001810 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1811 isl_pw_multi_aff *MinPMA, *MaxPMA;
1812 isl_pw_aff *LastDimAff;
1813 isl_aff *OneAff;
1814 unsigned Pos;
1815
Johannes Doerfert9143d672014-09-27 11:02:39 +00001816 // Restrict the number of parameters involved in the access as the lexmin/
1817 // lexmax computation will take too long if this number is high.
1818 //
1819 // Experiments with a simple test case using an i7 4800MQ:
1820 //
1821 // #Parameters involved | Time (in sec)
1822 // 6 | 0.01
1823 // 7 | 0.04
1824 // 8 | 0.12
1825 // 9 | 0.40
1826 // 10 | 1.54
1827 // 11 | 6.78
1828 // 12 | 30.38
1829 //
1830 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1831 unsigned InvolvedParams = 0;
1832 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1833 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1834 InvolvedParams++;
1835
1836 if (InvolvedParams > RunTimeChecksMaxParameters) {
1837 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001838 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001839 }
1840 }
1841
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001842 Set = isl_set_remove_divs(Set);
1843
Johannes Doerfertb164c792014-09-18 11:17:17 +00001844 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1845 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1846
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001847 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1848 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1849
Johannes Doerfertb164c792014-09-18 11:17:17 +00001850 // Adjust the last dimension of the maximal access by one as we want to
1851 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1852 // we test during code generation might now point after the end of the
1853 // allocated array but we will never dereference it anyway.
1854 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1855 "Assumed at least one output dimension");
1856 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1857 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1858 OneAff = isl_aff_zero_on_domain(
1859 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1860 OneAff = isl_aff_add_constant_si(OneAff, 1);
1861 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1862 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1863
1864 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1865
1866 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001867 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001868}
1869
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001870static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1871 isl_set *Domain = MA->getStatement()->getDomain();
1872 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1873 return isl_set_reset_tuple_id(Domain);
1874}
1875
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001876/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1877static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001878 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001879 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001880
1881 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1882 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001883 Locations = isl_union_set_coalesce(Locations);
1884 Locations = isl_union_set_detect_equalities(Locations);
1885 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001886 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001887 isl_union_set_free(Locations);
1888 return Valid;
1889}
1890
Johannes Doerfert96425c22015-08-30 21:13:53 +00001891/// @brief Helper to treat non-affine regions and basic blocks the same.
1892///
1893///{
1894
1895/// @brief Return the block that is the representing block for @p RN.
1896static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1897 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1898 : RN->getNodeAs<BasicBlock>();
1899}
1900
1901/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001902static inline BasicBlock *
1903getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001904 if (RN->isSubRegion()) {
1905 assert(idx == 0);
1906 return RN->getNodeAs<Region>()->getExit();
1907 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001908 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001909}
1910
1911/// @brief Return the smallest loop surrounding @p RN.
1912static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1913 if (!RN->isSubRegion())
1914 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1915
1916 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1917 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1918 while (L && NonAffineSubRegion->contains(L))
1919 L = L->getParentLoop();
1920 return L;
1921}
1922
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001923static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1924 if (!RN->isSubRegion())
1925 return 1;
1926
1927 unsigned NumBlocks = 0;
1928 Region *R = RN->getNodeAs<Region>();
1929 for (auto BB : R->blocks()) {
1930 (void)BB;
1931 NumBlocks++;
1932 }
1933 return NumBlocks;
1934}
1935
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001936static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
1937 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00001938 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001939 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00001940 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001941 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00001942 return true;
1943 return false;
1944}
1945
Johannes Doerfert96425c22015-08-30 21:13:53 +00001946///}
1947
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001948static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1949 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001950 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001951 isl_id *DimId =
1952 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
1953 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
1954}
1955
Johannes Doerfert96425c22015-08-30 21:13:53 +00001956isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1957 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1958 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00001959 return getDomainConditions(BB);
1960}
1961
1962isl_set *Scop::getDomainConditions(BasicBlock *BB) {
1963 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001964 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001965}
1966
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001967void Scop::buildDomains(Region *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001968
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001969 auto *EntryBB = R->getEntry();
1970 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
1971 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001972
1973 Loop *L = LI.getLoopFor(EntryBB);
1974 while (LD-- >= 0) {
1975 S = addDomainDimId(S, LD + 1, L);
1976 L = L->getParentLoop();
1977 }
1978
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001979 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001980
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00001981 if (SD.isNonAffineSubRegion(R, R))
1982 return;
1983
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001984 buildDomainsWithBranchConstraints(R);
1985 propagateDomainConstraints(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001986}
1987
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001988void Scop::buildDomainsWithBranchConstraints(Region *R) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001989 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00001990
1991 // To create the domain for each block in R we iterate over all blocks and
1992 // subregions in R and propagate the conditions under which the current region
1993 // element is executed. To this end we iterate in reverse post order over R as
1994 // it ensures that we first visit all predecessors of a region node (either a
1995 // basic block or a subregion) before we visit the region node itself.
1996 // Initially, only the domain for the SCoP region entry block is set and from
1997 // there we propagate the current domain to all successors, however we add the
1998 // condition that the successor is actually executed next.
1999 // As we are only interested in non-loop carried constraints here we can
2000 // simply skip loop back edges.
2001
2002 ReversePostOrderTraversal<Region *> RTraversal(R);
2003 for (auto *RN : RTraversal) {
2004
2005 // Recurse for affine subregions but go on for basic blocks and non-affine
2006 // subregions.
2007 if (RN->isSubRegion()) {
2008 Region *SubRegion = RN->getNodeAs<Region>();
2009 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002010 buildDomainsWithBranchConstraints(SubRegion);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002011 continue;
2012 }
2013 }
2014
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002015 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002016 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002017
Johannes Doerfert96425c22015-08-30 21:13:53 +00002018 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002019 TerminatorInst *TI = BB->getTerminator();
2020
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002021 if (isa<UnreachableInst>(TI))
2022 continue;
2023
Johannes Doerfertf5673802015-10-01 23:48:18 +00002024 isl_set *Domain = DomainMap.lookup(BB);
2025 if (!Domain) {
2026 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2027 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002028 continue;
2029 }
2030
Johannes Doerfert96425c22015-08-30 21:13:53 +00002031 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002032
2033 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2034 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2035
2036 // Build the condition sets for the successor nodes of the current region
2037 // node. If it is a non-affine subregion we will always execute the single
2038 // exit node, hence the single entry node domain is the condition set. For
2039 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002040 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002041 if (RN->isSubRegion())
2042 ConditionSets.push_back(isl_set_copy(Domain));
2043 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002044 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002045
2046 // Now iterate over the successors and set their initial domain based on
2047 // their condition set. We skip back edges here and have to be careful when
2048 // we leave a loop not to keep constraints over a dimension that doesn't
2049 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002050 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002051 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002052 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002053 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002054
2055 // Skip back edges.
2056 if (DT.dominates(SuccBB, BB)) {
2057 isl_set_free(CondSet);
2058 continue;
2059 }
2060
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002061 // Do not adjust the number of dimensions if we enter a boxed loop or are
2062 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002063 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002064 Region *SuccRegion = RI.getRegionFor(SuccBB);
Johannes Doerfert634909c2015-10-04 14:57:41 +00002065 if (SD.isNonAffineSubRegion(SuccRegion, &getRegion()))
2066 while (SuccBBLoop && SuccRegion->contains(SuccBBLoop))
2067 SuccBBLoop = SuccBBLoop->getParentLoop();
2068
2069 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002070
2071 // Check if the edge to SuccBB is a loop entry or exit edge. If so
2072 // adjust the dimensionality accordingly. Lastly, if we leave a loop
2073 // and enter a new one we need to drop the old constraints.
2074 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002075 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002076 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002077 CondSet = isl_set_project_out(CondSet, isl_dim_set,
2078 isl_set_n_dim(CondSet) - LoopDepthDiff,
2079 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002080 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002081 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002082 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002083 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002084 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002085 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002086 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
2087 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002088 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002089 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002090 }
2091
2092 // Set the domain for the successor or merge it with an existing domain in
2093 // case there are multiple paths (without loop back edges) to the
2094 // successor block.
2095 isl_set *&SuccDomain = DomainMap[SuccBB];
2096 if (!SuccDomain)
2097 SuccDomain = CondSet;
2098 else
2099 SuccDomain = isl_set_union(SuccDomain, CondSet);
2100
2101 SuccDomain = isl_set_coalesce(SuccDomain);
Johannes Doerfert634909c2015-10-04 14:57:41 +00002102 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
2103 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002104 }
2105 }
2106}
2107
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002108/// @brief Return the domain for @p BB wrt @p DomainMap.
2109///
2110/// This helper function will lookup @p BB in @p DomainMap but also handle the
2111/// case where @p BB is contained in a non-affine subregion using the region
2112/// tree obtained by @p RI.
2113static __isl_give isl_set *
2114getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
2115 RegionInfo &RI) {
2116 auto DIt = DomainMap.find(BB);
2117 if (DIt != DomainMap.end())
2118 return isl_set_copy(DIt->getSecond());
2119
2120 Region *R = RI.getRegionFor(BB);
2121 while (R->getEntry() == BB)
2122 R = R->getParent();
2123 return getDomainForBlock(R->getEntry(), DomainMap, RI);
2124}
2125
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002126void Scop::propagateDomainConstraints(Region *R) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002127 // Iterate over the region R and propagate the domain constrains from the
2128 // predecessors to the current node. In contrast to the
2129 // buildDomainsWithBranchConstraints function, this one will pull the domain
2130 // information from the predecessors instead of pushing it to the successors.
2131 // Additionally, we assume the domains to be already present in the domain
2132 // map here. However, we iterate again in reverse post order so we know all
2133 // predecessors have been visited before a block or non-affine subregion is
2134 // visited.
2135
2136 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2137 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2138
2139 ReversePostOrderTraversal<Region *> RTraversal(R);
2140 for (auto *RN : RTraversal) {
2141
2142 // Recurse for affine subregions but go on for basic blocks and non-affine
2143 // subregions.
2144 if (RN->isSubRegion()) {
2145 Region *SubRegion = RN->getNodeAs<Region>();
2146 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002147 propagateDomainConstraints(SubRegion);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002148 continue;
2149 }
2150 }
2151
Johannes Doerfertf5673802015-10-01 23:48:18 +00002152 // Get the domain for the current block and check if it was initialized or
2153 // not. The only way it was not is if this block is only reachable via error
2154 // blocks, thus will not be executed under the assumptions we make. Such
2155 // blocks have to be skipped as their predecessors might not have domains
2156 // either. It would not benefit us to compute the domain anyway, only the
2157 // domains of the error blocks that are reachable from non-error blocks
2158 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002159 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002160 isl_set *&Domain = DomainMap[BB];
2161 if (!Domain) {
2162 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2163 << ", it is only reachable from error blocks.\n");
2164 DomainMap.erase(BB);
2165 continue;
2166 }
2167 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
2168
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002169 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2170 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2171
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002172 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2173 for (auto *PredBB : predecessors(BB)) {
2174
2175 // Skip backedges
2176 if (DT.dominates(BB, PredBB))
2177 continue;
2178
2179 isl_set *PredBBDom = nullptr;
2180
2181 // Handle the SCoP entry block with its outside predecessors.
2182 if (!getRegion().contains(PredBB))
2183 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
2184
2185 if (!PredBBDom) {
2186 // Determine the loop depth of the predecessor and adjust its domain to
2187 // the domain of the current block. This can mean we have to:
2188 // o) Drop a dimension if this block is the exit of a loop, not the
2189 // header of a new loop and the predecessor was part of the loop.
2190 // o) Add an unconstrainted new dimension if this block is the header
2191 // of a loop and the predecessor is not part of it.
2192 // o) Drop the information about the innermost loop dimension when the
2193 // predecessor and the current block are surrounded by different
2194 // loops in the same depth.
2195 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2196 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2197 while (BoxedLoops.count(PredBBLoop))
2198 PredBBLoop = PredBBLoop->getParentLoop();
2199
2200 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002201 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002202 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002203 PredBBDom = isl_set_project_out(
2204 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2205 LoopDepthDiff);
2206 else if (PredBBLoopDepth < BBLoopDepth) {
2207 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002208 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002209 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2210 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002211 PredBBDom = isl_set_drop_constraints_involving_dims(
2212 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002213 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002214 }
2215
2216 PredDom = isl_set_union(PredDom, PredBBDom);
2217 }
2218
2219 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002220 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002221
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002222 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002223 addLoopBoundsToHeaderDomain(BBLoop);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002224
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002225 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002226 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002227 IsOptimized = true;
2228 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002229 addAssumption(ERRORBLOCK, isl_set_complement(DomPar),
2230 BB->getTerminator()->getDebugLoc());
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002231 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002232 }
2233}
2234
2235/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2236/// is incremented by one and all other dimensions are equal, e.g.,
2237/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2238/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2239static __isl_give isl_map *
2240createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2241 auto *MapSpace = isl_space_map_from_set(SetSpace);
2242 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2243 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2244 if (u != Dim)
2245 NextIterationMap =
2246 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2247 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2248 C = isl_constraint_set_constant_si(C, 1);
2249 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2250 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2251 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2252 return NextIterationMap;
2253}
2254
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002255void Scop::addLoopBoundsToHeaderDomain(Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002256 int LoopDepth = getRelativeLoopDepth(L);
2257 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002258
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002259 BasicBlock *HeaderBB = L->getHeader();
2260 assert(DomainMap.count(HeaderBB));
2261 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002262
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002263 isl_map *NextIterationMap =
2264 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002265
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002266 isl_set *UnionBackedgeCondition =
2267 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002268
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002269 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2270 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002271
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002272 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002273
2274 // If the latch is only reachable via error statements we skip it.
2275 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2276 if (!LatchBBDom)
2277 continue;
2278
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002279 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002280
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002281 TerminatorInst *TI = LatchBB->getTerminator();
2282 BranchInst *BI = dyn_cast<BranchInst>(TI);
2283 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002284 BackedgeCondition = isl_set_copy(LatchBBDom);
2285 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002286 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002287 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002288 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002289
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002290 // Free the non back edge condition set as we do not need it.
2291 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002292
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002293 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002294 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002295
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002296 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2297 assert(LatchLoopDepth >= LoopDepth);
2298 BackedgeCondition =
2299 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2300 LatchLoopDepth - LoopDepth);
2301 UnionBackedgeCondition =
2302 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002303 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002304
2305 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2306 for (int i = 0; i < LoopDepth; i++)
2307 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2308
2309 isl_set *UnionBackedgeConditionComplement =
2310 isl_set_complement(UnionBackedgeCondition);
2311 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2312 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2313 UnionBackedgeConditionComplement =
2314 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2315 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2316 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2317
2318 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2319 HeaderBBDom = Parts.second;
2320
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002321 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2322 // the bounded assumptions to the context as they are already implied by the
2323 // <nsw> tag.
2324 if (Affinator.hasNSWAddRecForLoop(L)) {
2325 isl_set_free(Parts.first);
2326 return;
2327 }
2328
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002329 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2330 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002331 addAssumption(INFINITELOOP, BoundedCtx,
2332 HeaderBB->getTerminator()->getDebugLoc());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002333}
2334
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002335void Scop::buildAliasChecks(AliasAnalysis &AA) {
2336 if (!PollyUseRuntimeAliasChecks)
2337 return;
2338
2339 if (buildAliasGroups(AA))
2340 return;
2341
2342 // If a problem occurs while building the alias groups we need to delete
2343 // this SCoP and pretend it wasn't valid in the first place. To this end
2344 // we make the assumed context infeasible.
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002345 addAssumption(ALIASING, isl_set_empty(getParamSpace()), DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002346
2347 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2348 << " could not be created as the number of parameters involved "
2349 "is too high. The SCoP will be "
2350 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2351 "the maximal number of parameters but be advised that the "
2352 "compile time might increase exponentially.\n\n");
2353}
2354
Johannes Doerfert9143d672014-09-27 11:02:39 +00002355bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002356 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002357 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002358 // for all memory accesses inside the SCoP.
2359 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002360 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002361 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002362 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002363 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002364 // if their access domains intersect, otherwise they are in different
2365 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002366 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002367 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002368 // and maximal accesses to each array of a group in read only and non
2369 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002370 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2371
2372 AliasSetTracker AST(AA);
2373
2374 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002375 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002376 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002377
2378 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002379 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002380 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2381 isl_set_free(StmtDomain);
2382 if (StmtDomainEmpty)
2383 continue;
2384
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002385 for (MemoryAccess *MA : Stmt) {
Michael Kruse8d0b7342015-09-25 21:21:00 +00002386 if (MA->isImplicit())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002387 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002388 if (!MA->isRead())
2389 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002390 Instruction *Acc = MA->getAccessInstruction();
2391 PtrToAcc[getPointerOperand(*Acc)] = MA;
2392 AST.add(Acc);
2393 }
2394 }
2395
2396 SmallVector<AliasGroupTy, 4> AliasGroups;
2397 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002398 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002399 continue;
2400 AliasGroupTy AG;
2401 for (auto PR : AS)
2402 AG.push_back(PtrToAcc[PR.getValue()]);
2403 assert(AG.size() > 1 &&
2404 "Alias groups should contain at least two accesses");
2405 AliasGroups.push_back(std::move(AG));
2406 }
2407
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002408 // Split the alias groups based on their domain.
2409 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2410 AliasGroupTy NewAG;
2411 AliasGroupTy &AG = AliasGroups[u];
2412 AliasGroupTy::iterator AGI = AG.begin();
2413 isl_set *AGDomain = getAccessDomain(*AGI);
2414 while (AGI != AG.end()) {
2415 MemoryAccess *MA = *AGI;
2416 isl_set *MADomain = getAccessDomain(MA);
2417 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2418 NewAG.push_back(MA);
2419 AGI = AG.erase(AGI);
2420 isl_set_free(MADomain);
2421 } else {
2422 AGDomain = isl_set_union(AGDomain, MADomain);
2423 AGI++;
2424 }
2425 }
2426 if (NewAG.size() > 1)
2427 AliasGroups.push_back(std::move(NewAG));
2428 isl_set_free(AGDomain);
2429 }
2430
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002431 auto &F = *getRegion().getEntry()->getParent();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002432 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002433 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2434 for (AliasGroupTy &AG : AliasGroups) {
2435 NonReadOnlyBaseValues.clear();
2436 ReadOnlyPairs.clear();
2437
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002438 if (AG.size() < 2) {
2439 AG.clear();
2440 continue;
2441 }
2442
Johannes Doerfert13771732014-10-01 12:40:46 +00002443 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002444 emitOptimizationRemarkAnalysis(
2445 F.getContext(), DEBUG_TYPE, F,
2446 (*II)->getAccessInstruction()->getDebugLoc(),
2447 "Possibly aliasing pointer, use restrict keyword.");
2448
Johannes Doerfert13771732014-10-01 12:40:46 +00002449 Value *BaseAddr = (*II)->getBaseAddr();
2450 if (HasWriteAccess.count(BaseAddr)) {
2451 NonReadOnlyBaseValues.insert(BaseAddr);
2452 II++;
2453 } else {
2454 ReadOnlyPairs[BaseAddr].insert(*II);
2455 II = AG.erase(II);
2456 }
2457 }
2458
2459 // If we don't have read only pointers check if there are at least two
2460 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002461 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002462 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002463 continue;
2464 }
2465
2466 // If we don't have non read only pointers clear the alias group.
2467 if (NonReadOnlyBaseValues.empty()) {
2468 AG.clear();
2469 continue;
2470 }
2471
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002472 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002473 MinMaxAliasGroups.emplace_back();
2474 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2475 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2476 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2477 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002478
2479 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002480
2481 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002482 for (MemoryAccess *MA : AG)
2483 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002484
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002485 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2486 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002487
2488 // Bail out if the number of values we need to compare is too large.
2489 // This is important as the number of comparisions grows quadratically with
2490 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002491 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2492 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002493 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002494
2495 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002496 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002497 Accesses = isl_union_map_empty(getParamSpace());
2498
2499 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2500 for (MemoryAccess *MA : ReadOnlyPair.second)
2501 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2502
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002503 Valid =
2504 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002505
2506 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002507 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002508 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002509
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002510 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002511}
2512
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002513static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
2514 Loop *L = LI.getLoopFor(R.getEntry());
2515 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2516}
2517
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002518static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2519 ScopDetection &SD) {
2520
2521 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2522
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002523 unsigned MinLD = INT_MAX, MaxLD = 0;
2524 for (BasicBlock *BB : R.blocks()) {
2525 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002526 if (!R.contains(L))
2527 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002528 if (BoxedLoops && BoxedLoops->count(L))
2529 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002530 unsigned LD = L->getLoopDepth();
2531 MinLD = std::min(MinLD, LD);
2532 MaxLD = std::max(MaxLD, LD);
2533 }
2534 }
2535
2536 // Handle the case that there is no loop in the SCoP first.
2537 if (MaxLD == 0)
2538 return 1;
2539
2540 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2541 assert(MaxLD >= MinLD &&
2542 "Maximal loop depth was smaller than mininaml loop depth?");
2543 return MaxLD - MinLD + 1;
2544}
2545
Johannes Doerfert478a7de2015-10-02 13:09:31 +00002546Scop::Scop(Region &R, AccFuncMapType &AccFuncMap, ScopDetection &SD,
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002547 ScalarEvolution &ScalarEvolution, DominatorTree &DT, LoopInfo &LI,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002548 isl_ctx *Context, unsigned MaxLoopDepth)
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002549 : LI(LI), DT(DT), SE(&ScalarEvolution), SD(SD), R(R),
2550 AccFuncMap(AccFuncMap), IsOptimized(false),
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002551 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
2552 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Context(nullptr),
2553 Affinator(this), AssumedContext(nullptr), BoundaryContext(nullptr),
2554 Schedule(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002555
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002556void Scop::init(AliasAnalysis &AA, AssumptionCache &AC) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002557 buildContext();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002558 addUserAssumptions(AC);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002559 buildInvariantEquivalenceClasses();
2560
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002561 buildDomains(&R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002562
Michael Krusecac948e2015-10-02 13:53:07 +00002563 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002564 // Exit early in case there are no executable statements left in this scop.
Michael Krusecac948e2015-10-02 13:53:07 +00002565 simplifySCoP(true);
Michael Kruseafe06702015-10-02 16:33:27 +00002566 if (Stmts.empty())
2567 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002568
Michael Krusecac948e2015-10-02 13:53:07 +00002569 // The ScopStmts now have enough information to initialize themselves.
2570 for (ScopStmt &Stmt : Stmts)
2571 Stmt.init();
2572
2573 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002574 Loop *L = getLoopSurroundingRegion(R, LI);
2575 LoopSchedules[L];
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002576 buildSchedule(&R, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002577 Schedule = LoopSchedules[L].first;
Tobias Grosser75805372011-04-29 06:27:02 +00002578
Tobias Grosser8286b832015-11-02 11:29:32 +00002579 if (isl_set_is_empty(AssumedContext))
2580 return;
2581
2582 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002583 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002584 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002585 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002586 buildBoundaryContext();
2587 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002588 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002589
2590 hoistInvariantLoads();
Michael Krusecac948e2015-10-02 13:53:07 +00002591 simplifySCoP(false);
Tobias Grosser75805372011-04-29 06:27:02 +00002592}
2593
2594Scop::~Scop() {
2595 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002596 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002597 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002598 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002599
Johannes Doerfert96425c22015-08-30 21:13:53 +00002600 for (auto It : DomainMap)
2601 isl_set_free(It.second);
2602
Johannes Doerfertb164c792014-09-18 11:17:17 +00002603 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002604 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002605 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002606 isl_pw_multi_aff_free(MMA.first);
2607 isl_pw_multi_aff_free(MMA.second);
2608 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002609 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002610 isl_pw_multi_aff_free(MMA.first);
2611 isl_pw_multi_aff_free(MMA.second);
2612 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002613 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002614
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002615 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002616 isl_set_free(std::get<2>(IAClass));
Tobias Grosser75805372011-04-29 06:27:02 +00002617}
2618
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002619void Scop::updateAccessDimensionality() {
2620 for (auto &Stmt : *this)
2621 for (auto &Access : Stmt)
2622 Access->updateDimensionality();
2623}
2624
Michael Krusecac948e2015-10-02 13:53:07 +00002625void Scop::simplifySCoP(bool RemoveIgnoredStmts) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002626 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2627 ScopStmt &Stmt = *StmtIt;
Michael Krusecac948e2015-10-02 13:53:07 +00002628 RegionNode *RN = Stmt.isRegionStmt()
2629 ? Stmt.getRegion()->getNode()
2630 : getRegion().getBBNode(Stmt.getBasicBlock());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002631
Johannes Doerferteca9e892015-11-03 16:54:49 +00002632 bool RemoveStmt = StmtIt->isEmpty();
2633 if (!RemoveStmt)
2634 RemoveStmt = isl_set_is_empty(DomainMap[getRegionNodeBasicBlock(RN)]);
2635 if (!RemoveStmt)
2636 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002637
Johannes Doerferteca9e892015-11-03 16:54:49 +00002638 // Remove read only statements only after invariant loop hoisting.
2639 if (!RemoveStmt && !RemoveIgnoredStmts) {
2640 bool OnlyRead = true;
2641 for (MemoryAccess *MA : Stmt) {
2642 if (MA->isRead())
2643 continue;
2644
2645 OnlyRead = false;
2646 break;
2647 }
2648
2649 RemoveStmt = OnlyRead;
2650 }
2651
2652 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00002653 // Remove the statement because it is unnecessary.
2654 if (Stmt.isRegionStmt())
2655 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2656 StmtMap.erase(BB);
2657 else
2658 StmtMap.erase(Stmt.getBasicBlock());
2659
2660 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002661 continue;
2662 }
2663
Michael Krusecac948e2015-10-02 13:53:07 +00002664 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002665 }
2666}
2667
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002668const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2669 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2670 if (!LInst)
2671 return nullptr;
2672
2673 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2674 LInst = cast<LoadInst>(Rep);
2675
2676 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2677 for (auto &IAClass : InvariantEquivClasses)
2678 if (PointerSCEV == std::get<0>(IAClass))
2679 return &IAClass;
2680
2681 return nullptr;
2682}
2683
2684void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2685
2686 // Get the context under which the statement is executed.
2687 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2688 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2689 DomainCtx = isl_set_detect_equalities(DomainCtx);
2690 DomainCtx = isl_set_coalesce(DomainCtx);
2691
2692 // Project out all parameters that relate to loads in the statement. Otherwise
2693 // we could have cyclic dependences on the constraints under which the
2694 // hoisted loads are executed and we could not determine an order in which to
2695 // pre-load them. This happens because not only lower bounds are part of the
2696 // domain but also upper bounds.
2697 for (MemoryAccess *MA : InvMAs) {
2698 Instruction *AccInst = MA->getAccessInstruction();
2699 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00002700 SetVector<Value *> Values;
2701 for (const SCEV *Parameter : Parameters) {
2702 Values.clear();
2703 findValues(Parameter, Values);
2704 if (!Values.count(AccInst))
2705 continue;
2706
2707 if (isl_id *ParamId = getIdForParam(Parameter)) {
2708 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2709 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2710 isl_id_free(ParamId);
2711 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002712 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002713 }
2714 }
2715
2716 for (MemoryAccess *MA : InvMAs) {
2717 // Check for another invariant access that accesses the same location as
2718 // MA and if found consolidate them. Otherwise create a new equivalence
2719 // class at the end of InvariantEquivClasses.
2720 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
2721 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2722
2723 bool Consolidated = false;
2724 for (auto &IAClass : InvariantEquivClasses) {
2725 if (PointerSCEV != std::get<0>(IAClass))
2726 continue;
2727
2728 Consolidated = true;
2729
2730 // Add MA to the list of accesses that are in this class.
2731 auto &MAs = std::get<1>(IAClass);
2732 MAs.push_front(MA);
2733
2734 // Unify the execution context of the class and this statement.
2735 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002736 if (IAClassDomainCtx)
2737 IAClassDomainCtx = isl_set_coalesce(
2738 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
2739 else
2740 IAClassDomainCtx = isl_set_copy(DomainCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002741 break;
2742 }
2743
2744 if (Consolidated)
2745 continue;
2746
2747 // If we did not consolidate MA, thus did not find an equivalence class
2748 // for it, we create a new one.
2749 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
2750 isl_set_copy(DomainCtx));
2751 }
2752
2753 isl_set_free(DomainCtx);
2754}
2755
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002756void Scop::hoistInvariantLoads() {
2757 isl_union_map *Writes = getWrites();
2758 for (ScopStmt &Stmt : *this) {
2759
2760 // TODO: Loads that are not loop carried, hence are in a statement with
2761 // zero iterators, are by construction invariant, though we
Johannes Doerfert09e36972015-10-07 20:17:36 +00002762 // currently "hoist" them anyway. This is necessary because we allow
2763 // them to be treated as parameters (e.g., in conditions) and our code
2764 // generation would otherwise use the old value.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002765
Johannes Doerfert8930f482015-10-02 14:51:00 +00002766 BasicBlock *BB = Stmt.isBlockStmt() ? Stmt.getBasicBlock()
2767 : Stmt.getRegion()->getEntry();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002768 isl_set *Domain = Stmt.getDomain();
2769 MemoryAccessList InvMAs;
2770
2771 for (MemoryAccess *MA : Stmt) {
2772 if (MA->isImplicit() || MA->isWrite() || !MA->isAffine())
2773 continue;
2774
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002775 // Skip accesses that have an invariant base pointer which is defined but
2776 // not loaded inside the SCoP. This can happened e.g., if a readnone call
2777 // returns a pointer that is used as a base address. However, as we want
2778 // to hoist indirect pointers, we allow the base pointer to be defined in
Johannes Doerfert654c3282015-10-21 22:14:57 +00002779 // the region if it is also a memory access. Each ScopArrayInfo object
2780 // that has a base pointer origin has a base pointer that is loaded and
2781 // that it is invariant, thus it will be hoisted too. However, if there is
Tobias Grosser27e19a02015-10-25 12:05:14 +00002782 // no base pointer origin we check that the base pointer is defined
Johannes Doerfert654c3282015-10-21 22:14:57 +00002783 // outside the region.
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002784 const ScopArrayInfo *SAI = MA->getScopArrayInfo();
Johannes Doerfert654c3282015-10-21 22:14:57 +00002785 while (auto *BasePtrOriginSAI = SAI->getBasePtrOriginSAI())
2786 SAI = BasePtrOriginSAI;
2787
2788 if (auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr()))
2789 if (R.contains(BasePtrInst))
2790 continue;
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002791
Johannes Doerfert8930f482015-10-02 14:51:00 +00002792 // Skip accesses in non-affine subregions as they might not be executed
2793 // under the same condition as the entry of the non-affine subregion.
2794 if (BB != MA->getAccessInstruction()->getParent())
2795 continue;
2796
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002797 isl_map *AccessRelation = MA->getAccessRelation();
Johannes Doerfertb864c2c2015-10-18 19:50:18 +00002798
2799 // Skip accesses that have an empty access relation. These can be caused
2800 // by multiple offsets with a type cast in-between that cause the overall
2801 // byte offset to be not divisible by the new types sizes.
2802 if (isl_map_is_empty(AccessRelation)) {
2803 isl_map_free(AccessRelation);
2804 continue;
2805 }
2806
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002807 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
2808 Stmt.getNumIterators())) {
2809 isl_map_free(AccessRelation);
2810 continue;
2811 }
2812
2813 AccessRelation =
2814 isl_map_intersect_domain(AccessRelation, isl_set_copy(Domain));
2815 isl_set *AccessRange = isl_map_range(AccessRelation);
2816
2817 isl_union_map *Written = isl_union_map_intersect_range(
2818 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
2819 bool IsWritten = !isl_union_map_is_empty(Written);
2820 isl_union_map_free(Written);
2821
2822 if (IsWritten)
2823 continue;
2824
2825 InvMAs.push_front(MA);
2826 }
2827
2828 // We inserted invariant accesses always in the front but need them to be
2829 // sorted in a "natural order". The statements are already sorted in reverse
2830 // post order and that suffices for the accesses too. The reason we require
2831 // an order in the first place is the dependences between invariant loads
2832 // that can be caused by indirect loads.
2833 InvMAs.reverse();
2834
2835 // Transfer the memory access from the statement to the SCoP.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002836 Stmt.removeMemoryAccesses(InvMAs);
2837 addInvariantLoads(Stmt, InvMAs);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002838
2839 isl_set_free(Domain);
2840 }
2841 isl_union_map_free(Writes);
2842
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002843 auto &ScopRIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert09e36972015-10-07 20:17:36 +00002844 // Check required invariant loads that were tagged during SCoP detection.
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002845 for (LoadInst *LI : ScopRIL) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00002846 assert(LI && getRegion().contains(LI));
2847 ScopStmt *Stmt = getStmtForBasicBlock(LI->getParent());
2848 if (Stmt && Stmt->lookupAccessesFor(LI) != nullptr) {
2849 DEBUG(dbgs() << "\n\nWARNING: Load (" << *LI
2850 << ") is required to be invariant but was not marked as "
2851 "such. SCoP for "
2852 << getRegion() << " will be dropped\n\n");
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002853 addAssumption(INVARIANTLOAD, isl_set_empty(getParamSpace()),
2854 LI->getDebugLoc());
Johannes Doerfert09e36972015-10-07 20:17:36 +00002855 return;
2856 }
2857 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002858}
2859
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002860const ScopArrayInfo *
2861Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002862 ArrayRef<const SCEV *> Sizes,
2863 ScopArrayInfo::ARRAYKIND Kind) {
2864 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002865 if (!SAI) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002866 SAI.reset(
2867 new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, Kind, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002868 } else {
Tobias Grosser8286b832015-11-02 11:29:32 +00002869 // In case of mismatching array sizes, we bail out by setting the run-time
2870 // context to false.
2871 if (!SAI->updateSizes(Sizes))
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002872 addAssumption(DELINEARIZATION, isl_set_empty(getParamSpace()),
2873 DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002874 }
Tobias Grosserab671442015-05-23 05:58:27 +00002875 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002876}
2877
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002878const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
2879 ScopArrayInfo::ARRAYKIND Kind) {
2880 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002881 assert(SAI && "No ScopArrayInfo available for this base pointer");
2882 return SAI;
2883}
2884
Tobias Grosser74394f02013-01-14 22:40:23 +00002885std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002886std::string Scop::getAssumedContextStr() const {
2887 return stringFromIslObj(AssumedContext);
2888}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002889std::string Scop::getBoundaryContextStr() const {
2890 return stringFromIslObj(BoundaryContext);
2891}
Tobias Grosser75805372011-04-29 06:27:02 +00002892
2893std::string Scop::getNameStr() const {
2894 std::string ExitName, EntryName;
2895 raw_string_ostream ExitStr(ExitName);
2896 raw_string_ostream EntryStr(EntryName);
2897
Tobias Grosserf240b482014-01-09 10:42:15 +00002898 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002899 EntryStr.str();
2900
2901 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00002902 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002903 ExitStr.str();
2904 } else
2905 ExitName = "FunctionExit";
2906
2907 return EntryName + "---" + ExitName;
2908}
2909
Tobias Grosser74394f02013-01-14 22:40:23 +00002910__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00002911__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002912 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00002913}
2914
Tobias Grossere86109f2013-10-29 21:05:49 +00002915__isl_give isl_set *Scop::getAssumedContext() const {
2916 return isl_set_copy(AssumedContext);
2917}
2918
Johannes Doerfert43788c52015-08-20 05:58:56 +00002919__isl_give isl_set *Scop::getRuntimeCheckContext() const {
2920 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002921 RuntimeCheckContext =
2922 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
2923 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002924 return RuntimeCheckContext;
2925}
2926
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002927bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002928 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002929 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002930 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
2931 isl_set_free(RuntimeCheckContext);
2932 return IsFeasible;
2933}
2934
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002935static std::string toString(AssumptionKind Kind) {
2936 switch (Kind) {
2937 case ALIASING:
2938 return "No-aliasing";
2939 case INBOUNDS:
2940 return "Inbounds";
2941 case WRAPPING:
2942 return "No-overflows";
2943 case ERRORBLOCK:
2944 return "No-error";
2945 case INFINITELOOP:
2946 return "Finite loop";
2947 case INVARIANTLOAD:
2948 return "Invariant load";
2949 case DELINEARIZATION:
2950 return "Delinearization";
2951 }
2952 llvm_unreachable("Unknown AssumptionKind!");
2953}
2954
2955void Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
2956 DebugLoc Loc) {
2957 if (isl_set_is_subset(Context, Set))
2958 return;
2959
2960 if (isl_set_is_subset(AssumedContext, Set))
2961 return;
2962
2963 auto &F = *getRegion().getEntry()->getParent();
2964 std::string Msg = toString(Kind) + " assumption:\t" + stringFromIslObj(Set);
2965 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
2966}
2967
2968void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
2969 DebugLoc Loc) {
2970 trackAssumption(Kind, Set, Loc);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002971 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00002972
Johannes Doerfert9d7899e2015-11-11 20:01:31 +00002973 int NSets = isl_set_n_basic_set(AssumedContext);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00002974 if (NSets >= MaxDisjunctsAssumed) {
2975 isl_space *Space = isl_set_get_space(AssumedContext);
2976 isl_set_free(AssumedContext);
Tobias Grossere19fca42015-11-11 20:21:39 +00002977 AssumedContext = isl_set_empty(Space);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00002978 }
2979
Tobias Grosser7b50bee2014-11-25 10:51:12 +00002980 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002981}
2982
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002983__isl_give isl_set *Scop::getBoundaryContext() const {
2984 return isl_set_copy(BoundaryContext);
2985}
2986
Tobias Grosser75805372011-04-29 06:27:02 +00002987void Scop::printContext(raw_ostream &OS) const {
2988 OS << "Context:\n";
2989
2990 if (!Context) {
2991 OS.indent(4) << "n/a\n\n";
2992 return;
2993 }
2994
2995 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00002996
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002997 OS.indent(4) << "Assumed Context:\n";
2998 if (!AssumedContext) {
2999 OS.indent(4) << "n/a\n\n";
3000 return;
3001 }
3002
3003 OS.indent(4) << getAssumedContextStr() << "\n";
3004
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003005 OS.indent(4) << "Boundary Context:\n";
3006 if (!BoundaryContext) {
3007 OS.indent(4) << "n/a\n\n";
3008 return;
3009 }
3010
3011 OS.indent(4) << getBoundaryContextStr() << "\n";
3012
Tobias Grosser083d3d32014-06-28 08:59:45 +00003013 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00003014 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00003015 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
3016 }
Tobias Grosser75805372011-04-29 06:27:02 +00003017}
3018
Johannes Doerfertb164c792014-09-18 11:17:17 +00003019void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003020 int noOfGroups = 0;
3021 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003022 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003023 noOfGroups += 1;
3024 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003025 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003026 }
3027
Tobias Grosserbb853c22015-07-25 12:31:03 +00003028 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003029 if (MinMaxAliasGroups.empty()) {
3030 OS.indent(8) << "n/a\n";
3031 return;
3032 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003033
Tobias Grosserbb853c22015-07-25 12:31:03 +00003034 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003035
3036 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003037 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003038 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003039 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003040 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3041 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003042 }
3043 OS << " ]]\n";
3044 }
3045
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003046 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003047 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003048 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003049 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003050 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3051 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003052 }
3053 OS << " ]]\n";
3054 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003055 }
3056}
3057
Tobias Grosser75805372011-04-29 06:27:02 +00003058void Scop::printStatements(raw_ostream &OS) const {
3059 OS << "Statements {\n";
3060
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003061 for (const ScopStmt &Stmt : *this)
3062 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003063
3064 OS.indent(4) << "}\n";
3065}
3066
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003067void Scop::printArrayInfo(raw_ostream &OS) const {
3068 OS << "Arrays {\n";
3069
Tobias Grosserab671442015-05-23 05:58:27 +00003070 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003071 Array.second->print(OS);
3072
3073 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003074
3075 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3076
3077 for (auto &Array : arrays())
3078 Array.second->print(OS, /* SizeAsPwAff */ true);
3079
3080 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003081}
3082
Tobias Grosser75805372011-04-29 06:27:02 +00003083void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00003084 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
3085 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003086 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003087 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003088 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003089 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003090 const auto &MAs = std::get<1>(IAClass);
3091 if (MAs.empty()) {
3092 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003093 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003094 MAs.front()->print(OS);
3095 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003096 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003097 }
3098 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003099 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003100 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003101 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003102 printStatements(OS.indent(4));
3103}
3104
3105void Scop::dump() const { print(dbgs()); }
3106
Tobias Grosser9a38ab82011-11-08 15:41:03 +00003107isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00003108
Johannes Doerfertcef616f2015-09-15 22:49:04 +00003109__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
3110 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003111}
3112
Tobias Grosser808cd692015-07-14 09:33:13 +00003113__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003114 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003115
Tobias Grosser808cd692015-07-14 09:33:13 +00003116 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003117 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003118
3119 return Domain;
3120}
3121
Tobias Grossere5a35142015-11-12 14:07:09 +00003122__isl_give isl_union_map *
3123Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3124 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003125
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003126 for (ScopStmt &Stmt : *this) {
3127 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003128 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003129 continue;
3130
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003131 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003132 isl_map *AccessDomain = MA->getAccessRelation();
3133 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003134 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003135 }
3136 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003137 return isl_union_map_coalesce(Accesses);
3138}
3139
3140__isl_give isl_union_map *Scop::getMustWrites() {
3141 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003142}
3143
3144__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003145 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003146}
3147
Tobias Grosser37eb4222014-02-20 21:43:54 +00003148__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003149 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003150}
3151
3152__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003153 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003154}
3155
Tobias Grosser2ac23382015-11-12 14:07:13 +00003156__isl_give isl_union_map *Scop::getAccesses() {
3157 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3158}
3159
Tobias Grosser808cd692015-07-14 09:33:13 +00003160__isl_give isl_union_map *Scop::getSchedule() const {
3161 auto Tree = getScheduleTree();
3162 auto S = isl_schedule_get_map(Tree);
3163 isl_schedule_free(Tree);
3164 return S;
3165}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003166
Tobias Grosser808cd692015-07-14 09:33:13 +00003167__isl_give isl_schedule *Scop::getScheduleTree() const {
3168 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3169 getDomains());
3170}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003171
Tobias Grosser808cd692015-07-14 09:33:13 +00003172void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3173 auto *S = isl_schedule_from_domain(getDomains());
3174 S = isl_schedule_insert_partial_schedule(
3175 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3176 isl_schedule_free(Schedule);
3177 Schedule = S;
3178}
3179
3180void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3181 isl_schedule_free(Schedule);
3182 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003183}
3184
3185bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3186 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003187 for (ScopStmt &Stmt : *this) {
3188 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003189 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3190 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3191
3192 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3193 isl_union_set_free(StmtDomain);
3194 isl_union_set_free(NewStmtDomain);
3195 continue;
3196 }
3197
3198 Changed = true;
3199
3200 isl_union_set_free(StmtDomain);
3201 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3202
3203 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003204 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003205 isl_union_set_free(NewStmtDomain);
3206 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003207 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003208 }
3209 isl_union_set_free(Domain);
3210 return Changed;
3211}
3212
Tobias Grosser75805372011-04-29 06:27:02 +00003213ScalarEvolution *Scop::getSE() const { return SE; }
3214
Johannes Doerfertf5673802015-10-01 23:48:18 +00003215bool Scop::isIgnored(RegionNode *RN) {
3216 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser75805372011-04-29 06:27:02 +00003217
Johannes Doerfertf5673802015-10-01 23:48:18 +00003218 // Check if there are accesses contained.
3219 bool ContainsAccesses = false;
3220 if (!RN->isSubRegion())
3221 ContainsAccesses = getAccessFunctions(BB);
3222 else
3223 for (BasicBlock *RBB : RN->getNodeAs<Region>()->blocks())
3224 ContainsAccesses |= (getAccessFunctions(RBB) != nullptr);
3225 if (!ContainsAccesses)
3226 return true;
3227
3228 // Check for reachability via non-error blocks.
3229 if (!DomainMap.count(BB))
3230 return true;
3231
3232 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003233 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003234 return true;
3235
3236 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003237}
3238
Tobias Grosser808cd692015-07-14 09:33:13 +00003239struct MapToDimensionDataTy {
3240 int N;
3241 isl_union_pw_multi_aff *Res;
3242};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003243
Tobias Grosser808cd692015-07-14 09:33:13 +00003244// @brief Create a function that maps the elements of 'Set' to its N-th
3245// dimension.
3246//
3247// The result is added to 'User->Res'.
3248//
3249// @param Set The input set.
3250// @param N The dimension to map to.
3251//
3252// @returns Zero if no error occurred, non-zero otherwise.
3253static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3254 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3255 int Dim;
3256 isl_space *Space;
3257 isl_pw_multi_aff *PMA;
3258
3259 Dim = isl_set_dim(Set, isl_dim_set);
3260 Space = isl_set_get_space(Set);
3261 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3262 Dim - Data->N);
3263 if (Data->N > 1)
3264 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3265 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3266
3267 isl_set_free(Set);
3268
3269 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003270}
3271
Tobias Grosser808cd692015-07-14 09:33:13 +00003272// @brief Create a function that maps the elements of Domain to their Nth
3273// dimension.
3274//
3275// @param Domain The set of elements to map.
3276// @param N The dimension to map to.
3277static __isl_give isl_multi_union_pw_aff *
3278mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003279 if (N <= 0 || isl_union_set_is_empty(Domain)) {
3280 isl_union_set_free(Domain);
3281 return nullptr;
3282 }
3283
Tobias Grosser808cd692015-07-14 09:33:13 +00003284 struct MapToDimensionDataTy Data;
3285 isl_space *Space;
3286
3287 Space = isl_union_set_get_space(Domain);
3288 Data.N = N;
3289 Data.Res = isl_union_pw_multi_aff_empty(Space);
3290 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
3291 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
3292
3293 isl_union_set_free(Domain);
3294 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3295}
3296
Tobias Grosser316b5b22015-11-11 19:28:14 +00003297void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003298 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003299 Stmts.emplace_back(*this, *BB);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003300 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003301 StmtMap[BB] = Stmt;
3302 } else {
3303 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003304 Stmts.emplace_back(*this, *R);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003305 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003306 for (BasicBlock *BB : R->blocks())
3307 StmtMap[BB] = Stmt;
3308 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003309}
3310
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003311void Scop::buildSchedule(
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003312 Region *R,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003313 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00003314
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003315 if (SD.isNonAffineSubRegion(R, &getRegion())) {
Johannes Doerfertc6987c12015-09-26 13:41:43 +00003316 Loop *L = getLoopSurroundingRegion(*R, LI);
3317 auto &LSchedulePair = LoopSchedules[L];
Michael Krusecac948e2015-10-02 13:53:07 +00003318 ScopStmt *Stmt = getStmtForBasicBlock(R->getEntry());
Michael Kruseafe06702015-10-02 16:33:27 +00003319 isl_set *Domain = Stmt->getDomain();
Michael Krusecac948e2015-10-02 13:53:07 +00003320 auto *UDomain = isl_union_set_from_set(Domain);
3321 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003322 LSchedulePair.first = StmtSchedule;
3323 return;
3324 }
3325
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003326 ReversePostOrderTraversal<Region *> RTraversal(R);
3327 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00003328
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003329 if (RN->isSubRegion()) {
3330 Region *SubRegion = RN->getNodeAs<Region>();
3331 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003332 buildSchedule(SubRegion, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003333 continue;
3334 }
Tobias Grosser75805372011-04-29 06:27:02 +00003335 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003336
3337 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert30c22652015-10-18 21:17:11 +00003338 if (!getRegion().contains(L))
3339 L = getLoopSurroundingRegion(getRegion(), LI);
3340
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003341 int LD = getRelativeLoopDepth(L);
3342 auto &LSchedulePair = LoopSchedules[L];
3343 LSchedulePair.second += getNumBlocksInRegionNode(RN);
3344
Michael Krusecac948e2015-10-02 13:53:07 +00003345 BasicBlock *BB = getRegionNodeBasicBlock(RN);
3346 ScopStmt *Stmt = getStmtForBasicBlock(BB);
3347 if (Stmt) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003348 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3349 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
3350 LSchedulePair.first =
3351 combineInSequence(LSchedulePair.first, StmtSchedule);
3352 }
3353
3354 unsigned NumVisited = LSchedulePair.second;
3355 while (L && NumVisited == L->getNumBlocks()) {
3356 auto *LDomain = isl_schedule_get_domain(LSchedulePair.first);
3357 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
3358 LSchedulePair.first =
3359 isl_schedule_insert_partial_schedule(LSchedulePair.first, MUPA);
3360
3361 auto *PL = L->getParentLoop();
Johannes Doerfertdca28372015-11-03 00:28:07 +00003362
3363 // Either we have a proper loop and we also build a schedule for the
3364 // parent loop or we have a infinite loop that does not have a proper
3365 // parent loop. In the former case this conditional will be skipped, in
3366 // the latter case however we will break here as we do not build a domain
3367 // nor a schedule for a infinite loop.
3368 assert(LoopSchedules.count(PL) || LSchedulePair.first == nullptr);
3369 if (!LoopSchedules.count(PL))
3370 break;
3371
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003372 auto &PSchedulePair = LoopSchedules[PL];
3373 PSchedulePair.first =
3374 combineInSequence(PSchedulePair.first, LSchedulePair.first);
3375 PSchedulePair.second += NumVisited;
3376
3377 L = PL;
3378 NumVisited = PSchedulePair.second;
3379 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003380 }
Tobias Grosser75805372011-04-29 06:27:02 +00003381}
3382
Johannes Doerfert7c494212014-10-31 23:13:39 +00003383ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003384 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003385 if (StmtMapIt == StmtMap.end())
3386 return nullptr;
3387 return StmtMapIt->second;
3388}
3389
Johannes Doerfert96425c22015-08-30 21:13:53 +00003390int Scop::getRelativeLoopDepth(const Loop *L) const {
3391 Loop *OuterLoop =
3392 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3393 if (!OuterLoop)
3394 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003395 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3396}
3397
Michael Krused868b5d2015-09-10 15:25:24 +00003398void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003399 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003400
3401 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3402 // true, are not modeled as ordinary PHI nodes as they are not part of the
3403 // region. However, we model the operands in the predecessor blocks that are
3404 // part of the region as regular scalar accesses.
3405
3406 // If we can synthesize a PHI we can skip it, however only if it is in
3407 // the region. If it is not it can only be in the exit block of the region.
3408 // In this case we model the operands but not the PHI itself.
3409 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3410 return;
3411
3412 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3413 // detection. Hence, the PHI is a load of a new memory location in which the
3414 // incoming value was written at the end of the incoming basic block.
3415 bool OnlyNonAffineSubRegionOperands = true;
3416 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3417 Value *Op = PHI->getIncomingValue(u);
3418 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3419
3420 // Do not build scalar dependences inside a non-affine subregion.
3421 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3422 continue;
3423
3424 OnlyNonAffineSubRegionOperands = false;
3425
3426 if (!R.contains(OpBB))
3427 continue;
3428
3429 Instruction *OpI = dyn_cast<Instruction>(Op);
3430 if (OpI) {
3431 BasicBlock *OpIBB = OpI->getParent();
3432 // As we pretend there is a use (or more precise a write) of OpI in OpBB
3433 // we have to insert a scalar dependence from the definition of OpI to
3434 // OpBB if the definition is not in OpBB.
Michael Kruse668af712015-10-15 14:45:48 +00003435 if (scop->getStmtForBasicBlock(OpIBB) !=
3436 scop->getStmtForBasicBlock(OpBB)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003437 addScalarReadAccess(OpI, PHI, OpBB);
3438 addScalarWriteAccess(OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003439 }
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003440 } else if (ModelReadOnlyScalars && !isa<Constant>(Op)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003441 addScalarReadAccess(Op, PHI, OpBB);
Michael Kruse7bf39442015-09-10 12:46:52 +00003442 }
3443
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003444 addPHIWriteAccess(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003445 }
3446
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003447 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3448 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003449 }
3450}
3451
Michael Krused868b5d2015-09-10 15:25:24 +00003452bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
3453 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003454 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
3455 if (isIgnoredIntrinsic(Inst))
3456 return false;
3457
3458 bool AnyCrossStmtUse = false;
3459 BasicBlock *ParentBB = Inst->getParent();
3460
3461 for (User *U : Inst->users()) {
3462 Instruction *UI = dyn_cast<Instruction>(U);
3463
3464 // Ignore the strange user
3465 if (UI == 0)
3466 continue;
3467
3468 BasicBlock *UseParent = UI->getParent();
3469
Tobias Grosserbaffa092015-10-24 20:55:27 +00003470 // Ignore basic block local uses. A value that is defined in a scop, but
3471 // used in a PHI node in the same basic block does not count as basic block
3472 // local, as for such cases a control flow edge is passed between definition
3473 // and use.
3474 if (UseParent == ParentBB && !isa<PHINode>(UI))
Michael Kruse7bf39442015-09-10 12:46:52 +00003475 continue;
3476
Michael Krusef714d472015-11-05 13:18:43 +00003477 // Uses by PHI nodes in the entry node count as external uses in case the
3478 // use is through an incoming block that is itself not contained in the
3479 // region.
3480 if (R->getEntry() == UseParent) {
3481 if (auto *PHI = dyn_cast<PHINode>(UI)) {
3482 bool ExternalUse = false;
3483 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
3484 if (PHI->getIncomingValue(i) == Inst &&
3485 !R->contains(PHI->getIncomingBlock(i))) {
3486 ExternalUse = true;
3487 break;
3488 }
3489 }
3490
3491 if (ExternalUse) {
3492 AnyCrossStmtUse = true;
3493 continue;
3494 }
3495 }
3496 }
3497
Michael Kruse7bf39442015-09-10 12:46:52 +00003498 // Do not build scalar dependences inside a non-affine subregion.
3499 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
3500 continue;
3501
Michael Kruse01cb3792015-10-17 21:07:08 +00003502 // Check for PHI nodes in the region exit and skip them, if they will be
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003503 // modeled as PHI nodes.
Michael Kruse01cb3792015-10-17 21:07:08 +00003504 //
3505 // PHI nodes in the region exit that have more than two incoming edges need
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003506 // to be modeled as PHI-Nodes to correctly model the fact that depending on
3507 // the control flow a different value will be assigned to the PHI node. In
3508 // case this is the case, there is no need to create an additional normal
3509 // scalar dependence. Hence, bail out before we register an "out-of-region"
3510 // use for this definition.
Michael Kruse01cb3792015-10-17 21:07:08 +00003511 if (isa<PHINode>(UI) && UI->getParent() == R->getExit() &&
3512 !R->getExitingBlock())
3513 continue;
3514
Michael Kruse7bf39442015-09-10 12:46:52 +00003515 // Check whether or not the use is in the SCoP.
Tobias Grosserc73d8b02015-10-23 22:36:22 +00003516 if (!R->contains(UseParent)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003517 AnyCrossStmtUse = true;
3518 continue;
3519 }
3520
3521 // If the instruction can be synthesized and the user is in the region
3522 // we do not need to add scalar dependences.
3523 if (canSynthesizeInst)
3524 continue;
3525
3526 // No need to translate these scalar dependences into polyhedral form,
3527 // because synthesizable scalars can be generated by the code generator.
3528 if (canSynthesize(UI, LI, SE, R))
3529 continue;
3530
3531 // Skip PHI nodes in the region as they handle their operands on their own.
3532 if (isa<PHINode>(UI))
3533 continue;
3534
3535 // Now U is used in another statement.
3536 AnyCrossStmtUse = true;
3537
3538 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00003539 // Use the def instruction as base address of the MemoryAccess, so that it
3540 // will become the name of the scalar access in the polyhedral form.
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003541 addScalarReadAccess(Inst, UI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003542 }
3543
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003544 if (ModelReadOnlyScalars && !isa<PHINode>(Inst)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003545 for (Value *Op : Inst->operands()) {
3546 if (canSynthesize(Op, LI, SE, R))
3547 continue;
3548
3549 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
3550 if (R->contains(OpInst))
3551 continue;
3552
3553 if (isa<Constant>(Op))
3554 continue;
3555
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003556 addScalarReadAccess(Op, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003557 }
3558 }
3559
3560 return AnyCrossStmtUse;
3561}
3562
3563extern MapInsnToMemAcc InsnToMemAcc;
3564
Michael Krusee2bccbb2015-09-18 19:59:43 +00003565void ScopInfo::buildMemoryAccess(
3566 Instruction *Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003567 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3568 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003569 unsigned Size;
3570 Type *SizeType;
3571 Value *Val;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003572 enum MemoryAccess::AccessType Type;
Michael Kruse7bf39442015-09-10 12:46:52 +00003573
3574 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
3575 SizeType = Load->getType();
3576 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003577 Type = MemoryAccess::READ;
Michael Kruse7bf39442015-09-10 12:46:52 +00003578 Val = Load;
3579 } else {
3580 StoreInst *Store = cast<StoreInst>(Inst);
3581 SizeType = Store->getValueOperand()->getType();
3582 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003583 Type = MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003584 Val = Store->getValueOperand();
3585 }
3586
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003587 auto Address = getPointerOperand(*Inst);
3588
3589 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003590 const SCEVUnknown *BasePointer =
3591 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3592
3593 assert(BasePointer && "Could not find base pointer");
3594 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
3595
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003596 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3597 auto NewAddress = Address;
3598 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3599 auto Src = BitCast->getOperand(0);
3600 auto SrcTy = Src->getType();
3601 auto DstTy = BitCast->getType();
3602 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3603 NewAddress = Src;
3604 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003605
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003606 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3607 std::vector<const SCEV *> Subscripts;
3608 std::vector<int> Sizes;
3609 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3610 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003611
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003612 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003613
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003614 bool AllAffineSubcripts = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003615 for (auto Subscript : Subscripts) {
3616 InvariantLoadsSetTy AccessILS;
3617 AllAffineSubcripts =
3618 isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS);
3619
3620 for (LoadInst *LInst : AccessILS)
3621 if (!ScopRIL.count(LInst))
3622 AllAffineSubcripts = false;
3623
3624 if (!AllAffineSubcripts)
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003625 break;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003626 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003627
3628 if (AllAffineSubcripts && Sizes.size() > 0) {
3629 for (auto V : Sizes)
3630 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3631 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003632 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003633 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003634
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003635 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3636 Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00003637 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003638 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003639 }
3640 }
3641
Michael Kruse7bf39442015-09-10 12:46:52 +00003642 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003643 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003644 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3645 AccItr->second.DelinearizedSubscripts,
3646 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003647 return;
3648 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003649
3650 // Check if the access depends on a loop contained in a non-affine subregion.
3651 bool isVariantInNonAffineLoop = false;
3652 if (BoxedLoops) {
3653 SetVector<const Loop *> Loops;
3654 findLoops(AccessFunction, Loops);
3655 for (const Loop *L : Loops)
3656 if (BoxedLoops->count(L))
3657 isVariantInNonAffineLoop = true;
3658 }
3659
Johannes Doerfert09e36972015-10-07 20:17:36 +00003660 InvariantLoadsSetTy AccessILS;
3661 bool IsAffine =
3662 !isVariantInNonAffineLoop &&
3663 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3664
3665 for (LoadInst *LInst : AccessILS)
3666 if (!ScopRIL.count(LInst))
3667 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003668
Michael Krusecaac2b62015-09-26 15:51:44 +00003669 // FIXME: Size of the number of bytes of an array element, not the number of
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003670 // elements as probably intended here.
Tobias Grossera43b6e92015-09-27 17:54:50 +00003671 const SCEV *SizeSCEV =
3672 SE->getConstant(TD->getIntPtrType(Inst->getContext()), Size);
Michael Kruse7bf39442015-09-10 12:46:52 +00003673
Michael Krusee2bccbb2015-09-18 19:59:43 +00003674 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3675 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003676
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003677 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, IsAffine,
3678 ArrayRef<const SCEV *>(AccessFunction),
3679 ArrayRef<const SCEV *>(SizeSCEV), Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003680}
3681
Michael Krused868b5d2015-09-10 15:25:24 +00003682void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003683
3684 if (SD->isNonAffineSubRegion(&SR, &R)) {
3685 for (BasicBlock *BB : SR.blocks())
3686 buildAccessFunctions(R, *BB, &SR);
3687 return;
3688 }
3689
3690 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3691 if (I->isSubRegion())
3692 buildAccessFunctions(R, *I->getNodeAs<Region>());
3693 else
3694 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
3695}
3696
Michael Krusecac948e2015-10-02 13:53:07 +00003697void ScopInfo::buildStmts(Region &SR) {
3698 Region *R = getRegion();
3699
3700 if (SD->isNonAffineSubRegion(&SR, R)) {
3701 scop->addScopStmt(nullptr, &SR);
3702 return;
3703 }
3704
3705 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3706 if (I->isSubRegion())
3707 buildStmts(*I->getNodeAs<Region>());
3708 else
3709 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
3710}
3711
Michael Krused868b5d2015-09-10 15:25:24 +00003712void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
3713 Region *NonAffineSubRegion,
3714 bool IsExitBlock) {
Tobias Grosser910cf262015-11-11 20:15:49 +00003715 // We do not build access functions for error blocks, as they may contain
3716 // instructions we can not model.
3717 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3718 if (isErrorBlock(BB, R, *LI, DT) && !IsExitBlock)
3719 return;
3720
Michael Kruse7bf39442015-09-10 12:46:52 +00003721 Loop *L = LI->getLoopFor(&BB);
3722
3723 // The set of loops contained in non-affine subregions that are part of R.
3724 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3725
Johannes Doerfert09e36972015-10-07 20:17:36 +00003726 // The set of loads that are required to be invariant.
3727 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
3728
Michael Kruse7bf39442015-09-10 12:46:52 +00003729 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00003730 Instruction *Inst = &*I;
Michael Kruse7bf39442015-09-10 12:46:52 +00003731
3732 PHINode *PHI = dyn_cast<PHINode>(Inst);
3733 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003734 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003735
3736 // For the exit block we stop modeling after the last PHI node.
3737 if (!PHI && IsExitBlock)
3738 break;
3739
Johannes Doerfert09e36972015-10-07 20:17:36 +00003740 // TODO: At this point we only know that elements of ScopRIL have to be
3741 // invariant and will be hoisted for the SCoP to be processed. Though,
3742 // there might be other invariant accesses that will be hoisted and
3743 // that would allow to make a non-affine access affine.
Michael Kruse7bf39442015-09-10 12:46:52 +00003744 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
Johannes Doerfert09e36972015-10-07 20:17:36 +00003745 buildMemoryAccess(Inst, L, &R, BoxedLoops, ScopRIL);
Michael Kruse7bf39442015-09-10 12:46:52 +00003746
3747 if (isIgnoredIntrinsic(Inst))
3748 continue;
3749
Johannes Doerfert09e36972015-10-07 20:17:36 +00003750 // Do not build scalar dependences for required invariant loads as we will
3751 // hoist them later on anyway or drop the SCoP if we cannot.
3752 if (ScopRIL.count(dyn_cast<LoadInst>(Inst)))
3753 continue;
3754
Michael Kruse7bf39442015-09-10 12:46:52 +00003755 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00003756 if (!isa<StoreInst>(Inst))
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003757 addScalarWriteAccess(Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003758 }
3759 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003760}
Michael Kruse7bf39442015-09-10 12:46:52 +00003761
Michael Kruse2d0ece92015-09-24 11:41:21 +00003762void ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3763 MemoryAccess::AccessType Type,
3764 Value *BaseAddress, unsigned ElemBytes,
3765 bool Affine, Value *AccessValue,
3766 ArrayRef<const SCEV *> Subscripts,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003767 ArrayRef<const SCEV *> Sizes,
3768 MemoryAccess::AccessOrigin Origin) {
Michael Krusecac948e2015-10-02 13:53:07 +00003769 ScopStmt *Stmt = scop->getStmtForBasicBlock(BB);
3770
3771 // Do not create a memory access for anything not in the SCoP. It would be
3772 // ignored anyway.
3773 if (!Stmt)
3774 return;
3775
Michael Krusee2bccbb2015-09-18 19:59:43 +00003776 AccFuncSetType &AccList = AccFuncMap[BB];
Michael Krusee2bccbb2015-09-18 19:59:43 +00003777 Value *BaseAddr = BaseAddress;
3778 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3779
Michael Krusecac948e2015-10-02 13:53:07 +00003780 bool isApproximated =
3781 Stmt->isRegionStmt() && (Stmt->getRegion()->getEntry() != BB);
3782 if (isApproximated && Type == MemoryAccess::MUST_WRITE)
3783 Type = MemoryAccess::MAY_WRITE;
3784
Tobias Grosserf1bfd752015-11-05 20:15:37 +00003785 AccList.emplace_back(Stmt, Inst, Type, BaseAddress, ElemBytes, Affine,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003786 Subscripts, Sizes, AccessValue, Origin, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00003787 Stmt->addAccess(&AccList.back());
Michael Kruse7bf39442015-09-10 12:46:52 +00003788}
3789
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003790void ScopInfo::addExplicitAccess(
3791 Instruction *MemAccInst, MemoryAccess::AccessType Type, Value *BaseAddress,
3792 unsigned ElemBytes, bool IsAffine, ArrayRef<const SCEV *> Subscripts,
3793 ArrayRef<const SCEV *> Sizes, Value *AccessValue) {
3794 assert(isa<LoadInst>(MemAccInst) || isa<StoreInst>(MemAccInst));
3795 assert(isa<LoadInst>(MemAccInst) == (Type == MemoryAccess::READ));
3796 addMemoryAccess(MemAccInst->getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003797 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
3798 MemoryAccess::EXPLICIT);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003799}
3800void ScopInfo::addScalarWriteAccess(Instruction *Value) {
3801 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
3802 true, Value, ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003803 ArrayRef<const SCEV *>(), MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003804}
3805void ScopInfo::addScalarReadAccess(Value *Value, Instruction *User) {
3806 assert(!isa<PHINode>(User));
3807 addMemoryAccess(User->getParent(), User, MemoryAccess::READ, Value, 1, true,
3808 Value, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003809 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003810}
3811void ScopInfo::addScalarReadAccess(Value *Value, PHINode *User,
3812 BasicBlock *UserBB) {
3813 addMemoryAccess(UserBB, User, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003814 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3815 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003816}
3817void ScopInfo::addPHIWriteAccess(PHINode *PHI, BasicBlock *IncomingBlock,
3818 Value *IncomingValue, bool IsExitBlock) {
3819 addMemoryAccess(IncomingBlock, IncomingBlock->getTerminator(),
3820 MemoryAccess::MUST_WRITE, PHI, 1, true, IncomingValue,
3821 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003822 IsExitBlock ? MemoryAccess::SCALAR : MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003823}
3824void ScopInfo::addPHIReadAccess(PHINode *PHI) {
3825 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003826 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3827 MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003828}
3829
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003830void ScopInfo::buildScop(Region &R, DominatorTree &DT, AssumptionCache &AC) {
Michael Kruse9d080092015-09-11 21:41:48 +00003831 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003832 scop = new Scop(R, AccFuncMap, *SD, *SE, DT, *LI, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00003833
Michael Krusecac948e2015-10-02 13:53:07 +00003834 buildStmts(R);
Michael Kruse7bf39442015-09-10 12:46:52 +00003835 buildAccessFunctions(R, R);
3836
3837 // In case the region does not have an exiting block we will later (during
3838 // code generation) split the exit block. This will move potential PHI nodes
3839 // from the current exit block into the new region exiting block. Hence, PHI
3840 // nodes that are at this point not part of the region will be.
3841 // To handle these PHI nodes later we will now model their operands as scalar
3842 // accesses. Note that we do not model anything in the exit block if we have
3843 // an exiting block in the region, as there will not be any splitting later.
3844 if (!R.getExitingBlock())
3845 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
3846
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003847 scop->init(*AA, AC);
Michael Kruse7bf39442015-09-10 12:46:52 +00003848}
3849
Michael Krused868b5d2015-09-10 15:25:24 +00003850void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00003851 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00003852 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00003853 return;
3854 }
3855
Michael Kruse9d080092015-09-11 21:41:48 +00003856 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00003857}
3858
Michael Krused868b5d2015-09-10 15:25:24 +00003859void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00003860 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00003861 if (scop) {
3862 delete scop;
3863 scop = 0;
3864 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003865}
3866
3867//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00003868ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00003869 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00003870 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00003871}
3872
3873ScopInfo::~ScopInfo() {
3874 clear();
3875 isl_ctx_free(ctx);
3876}
3877
Tobias Grosser75805372011-04-29 06:27:02 +00003878void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00003879 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00003880 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00003881 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00003882 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
3883 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003884 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003885 AU.addRequired<AssumptionCacheTracker>();
Tobias Grosser75805372011-04-29 06:27:02 +00003886 AU.setPreservesAll();
3887}
3888
3889bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00003890 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00003891
Michael Krused868b5d2015-09-10 15:25:24 +00003892 if (!SD->isMaxRegionInScop(*R))
3893 return false;
3894
3895 Function *F = R->getEntry()->getParent();
3896 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3897 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3898 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3899 TD = &F->getParent()->getDataLayout();
3900 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003901 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krused868b5d2015-09-10 15:25:24 +00003902
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00003903 DebugLoc Beg, End;
3904 getDebugLocations(R, Beg, End);
3905 std::string Msg = "SCoP begins here.";
3906 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg);
3907
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003908 buildScop(*R, DT, AC);
Tobias Grosser75805372011-04-29 06:27:02 +00003909
Tobias Grosserd6a50b32015-05-30 06:26:21 +00003910 DEBUG(scop->print(dbgs()));
3911
Michael Kruseafe06702015-10-02 16:33:27 +00003912 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00003913 Msg = "SCoP ends here but was dismissed.";
Johannes Doerfert43788c52015-08-20 05:58:56 +00003914 delete scop;
3915 scop = nullptr;
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00003916 } else {
3917 Msg = "SCoP ends here.";
3918 ++ScopFound;
3919 if (scop->getMaxLoopDepth() > 0)
3920 ++RichScopFound;
Johannes Doerfert43788c52015-08-20 05:58:56 +00003921 }
3922
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00003923 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg);
3924
Tobias Grosser75805372011-04-29 06:27:02 +00003925 return false;
3926}
3927
3928char ScopInfo::ID = 0;
3929
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003930Pass *polly::createScopInfoPass() { return new ScopInfo(); }
3931
Tobias Grosser73600b82011-10-08 00:30:40 +00003932INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
3933 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003934 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003935INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003936INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00003937INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00003938INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00003939INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003940INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003941INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00003942INITIALIZE_PASS_END(ScopInfo, "polly-scops",
3943 "Polly - Create polyhedral description of Scops", false,
3944 false)