blob: 43e14bdc0b03bddfe45438da0b527d08c0dee76c [file] [log] [blame]
Johannes Doerfert58a7c752015-09-28 09:48:53 +00001//===--------- ScopInfo.cpp - Create Scops from LLVM IR ------------------===//
Tobias Grosser75805372011-04-29 06:27:02 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Create a polyhedral description for a static control flow region.
11//
12// The pass creates a polyhedral description of the Scops detected by the Scop
13// detection derived from their LLVM-IR code.
14//
Tobias Grossera5605d32014-10-29 19:58:28 +000015// This representation is shared among several tools in the polyhedral
Tobias Grosser75805372011-04-29 06:27:02 +000016// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
Tobias Grosser75805372011-04-29 06:27:02 +000020#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000021#include "polly/Options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000022#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000023#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000024#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000025#include "polly/Support/ScopHelper.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000026#include "llvm/ADT/MapVector.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000027#include "llvm/ADT/PostOrderIterator.h"
28#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000029#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000030#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000031#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000032#include "llvm/Analysis/AliasAnalysis.h"
Johannes Doerfert2af10e22015-11-12 03:25:01 +000033#include "llvm/Analysis/AssumptionCache.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000034#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000035#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000036#include "llvm/Analysis/RegionIterator.h"
37#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Johannes Doerfert48fe86f2015-11-12 02:32:32 +000038#include "llvm/IR/DiagnosticInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000039#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000040#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000041#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000042#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000043#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000044#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000045#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000046#include "isl/schedule.h"
47#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000048#include "isl/set.h"
49#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000050#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000051#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000052#include <sstream>
53#include <string>
54#include <vector>
55
56using namespace llvm;
57using namespace polly;
58
Chandler Carruth95fef942014-04-22 03:30:19 +000059#define DEBUG_TYPE "polly-scops"
60
Tobias Grosser74394f02013-01-14 22:40:23 +000061STATISTIC(ScopFound, "Number of valid Scops");
62STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000063
Michael Kruse7bf39442015-09-10 12:46:52 +000064static cl::opt<bool> ModelReadOnlyScalars(
65 "polly-analyze-read-only-scalars",
66 cl::desc("Model read-only scalar values in the scop description"),
67 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
68
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000069// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000070// operations can overflow easily. Additive reductions and bit operations
71// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000072static cl::opt<bool> DisableMultiplicativeReductions(
73 "polly-disable-multiplicative-reductions",
74 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
75 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000076
Johannes Doerfert9143d672014-09-27 11:02:39 +000077static cl::opt<unsigned> RunTimeChecksMaxParameters(
78 "polly-rtc-max-parameters",
79 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
80 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
81
Tobias Grosser71500722015-03-28 15:11:14 +000082static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
83 "polly-rtc-max-arrays-per-group",
84 cl::desc("The maximal number of arrays to compare in each alias group."),
85 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000086static cl::opt<std::string> UserContextStr(
87 "polly-context", cl::value_desc("isl parameter set"),
88 cl::desc("Provide additional constraints on the context parameters"),
89 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000090
Tobias Grosserd83b8a82015-08-20 19:08:11 +000091static cl::opt<bool> DetectReductions("polly-detect-reductions",
92 cl::desc("Detect and exploit reductions"),
93 cl::Hidden, cl::ZeroOrMore,
94 cl::init(true), cl::cat(PollyCategory));
95
Tobias Grosser20a4c0c2015-11-11 16:22:36 +000096static cl::opt<int> MaxDisjunctsAssumed(
97 "polly-max-disjuncts-assumed",
98 cl::desc("The maximal number of disjuncts we allow in the assumption "
99 "context (this bounds compile time)"),
100 cl::Hidden, cl::ZeroOrMore, cl::init(150), cl::cat(PollyCategory));
101
Michael Kruse7bf39442015-09-10 12:46:52 +0000102//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000103
Michael Kruse046dde42015-08-10 13:01:57 +0000104// Create a sequence of two schedules. Either argument may be null and is
105// interpreted as the empty schedule. Can also return null if both schedules are
106// empty.
107static __isl_give isl_schedule *
108combineInSequence(__isl_take isl_schedule *Prev,
109 __isl_take isl_schedule *Succ) {
110 if (!Prev)
111 return Succ;
112 if (!Succ)
113 return Prev;
114
115 return isl_schedule_sequence(Prev, Succ);
116}
117
Johannes Doerferte7044942015-02-24 11:58:30 +0000118static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
119 const ConstantRange &Range,
120 int dim,
121 enum isl_dim_type type) {
122 isl_val *V;
123 isl_ctx *ctx = isl_set_get_ctx(S);
124
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000125 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
126 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000127 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000128 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
129
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000130 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000131 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000132 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000133 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000134 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
135
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000136 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000137 return isl_set_union(SLB, SUB);
138 else
139 return isl_set_intersect(SLB, SUB);
140}
141
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000142static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
143 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
144 if (!BasePtrLI)
145 return nullptr;
146
147 if (!S->getRegion().contains(BasePtrLI))
148 return nullptr;
149
150 ScalarEvolution &SE = *S->getSE();
151
152 auto *OriginBaseSCEV =
153 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
154 if (!OriginBaseSCEV)
155 return nullptr;
156
157 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
158 if (!OriginBaseSCEVUnknown)
159 return nullptr;
160
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000161 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
162 ScopArrayInfo::KIND_ARRAY);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000163}
164
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000165ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000166 ArrayRef<const SCEV *> Sizes, enum ARRAYKIND Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000167 const DataLayout &DL, Scop *S)
168 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000169 std::string BasePtrName =
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000170 getIslCompatibleName("MemRef_", BasePtr, Kind == KIND_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000171 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000172
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000173 updateSizes(Sizes);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000174 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
175 if (BasePtrOriginSAI)
176 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000177}
178
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000179__isl_give isl_space *ScopArrayInfo::getSpace() const {
180 auto Space =
181 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
182 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
183 return Space;
184}
185
Tobias Grosser8286b832015-11-02 11:29:32 +0000186bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000187 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
188 int ExtraDimsNew = NewSizes.size() - SharedDims;
189 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Tobias Grosser8286b832015-11-02 11:29:32 +0000190 for (int i = 0; i < SharedDims; i++)
191 if (NewSizes[i + ExtraDimsNew] != DimensionSizes[i + ExtraDimsOld])
192 return false;
193
194 if (DimensionSizes.size() >= NewSizes.size())
195 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000196
197 DimensionSizes.clear();
198 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
199 NewSizes.end());
200 for (isl_pw_aff *Size : DimensionSizesPw)
201 isl_pw_aff_free(Size);
202 DimensionSizesPw.clear();
203 for (const SCEV *Expr : DimensionSizes) {
204 isl_pw_aff *Size = S.getPwAff(Expr);
205 DimensionSizesPw.push_back(Size);
206 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000207 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000208}
209
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000210ScopArrayInfo::~ScopArrayInfo() {
211 isl_id_free(Id);
212 for (isl_pw_aff *Size : DimensionSizesPw)
213 isl_pw_aff_free(Size);
214}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000215
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000216std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
217
218int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000219 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000220}
221
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000222isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
223
224void ScopArrayInfo::dump() const { print(errs()); }
225
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000226void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000227 OS.indent(8) << *getElementType() << " " << getName();
228 if (getNumberOfDimensions() > 0)
229 OS << "[*]";
Tobias Grosser26253842015-11-10 14:24:21 +0000230 for (unsigned u = 1; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000231 OS << "[";
232
Tobias Grosser26253842015-11-10 14:24:21 +0000233 if (SizeAsPwAff) {
234 auto Size = getDimensionSizePw(u);
235 OS << " " << Size << " ";
236 isl_pw_aff_free(Size);
237 } else {
238 OS << *getDimensionSize(u);
239 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000240
241 OS << "]";
242 }
243
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000244 OS << ";";
245
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000246 if (BasePtrOriginSAI)
247 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
248
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000249 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000250}
251
252const ScopArrayInfo *
253ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
254 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
255 assert(Id && "Output dimension didn't have an ID");
256 return getFromId(Id);
257}
258
259const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
260 void *User = isl_id_get_user(Id);
261 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
262 isl_id_free(Id);
263 return SAI;
264}
265
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000266void MemoryAccess::updateDimensionality() {
267 auto ArraySpace = getScopArrayInfo()->getSpace();
268 auto AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
269
270 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
271 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
272 auto DimsMissing = DimsArray - DimsAccess;
273
274 auto Map = isl_map_from_domain_and_range(isl_set_universe(AccessSpace),
275 isl_set_universe(ArraySpace));
276
277 for (unsigned i = 0; i < DimsMissing; i++)
278 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
279
280 for (unsigned i = DimsMissing; i < DimsArray; i++)
281 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
282
283 AccessRelation = isl_map_apply_range(AccessRelation, Map);
284}
285
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000286const std::string
287MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
288 switch (RT) {
289 case MemoryAccess::RT_NONE:
290 llvm_unreachable("Requested a reduction operator string for a memory "
291 "access which isn't a reduction");
292 case MemoryAccess::RT_ADD:
293 return "+";
294 case MemoryAccess::RT_MUL:
295 return "*";
296 case MemoryAccess::RT_BOR:
297 return "|";
298 case MemoryAccess::RT_BXOR:
299 return "^";
300 case MemoryAccess::RT_BAND:
301 return "&";
302 }
303 llvm_unreachable("Unknown reduction type");
304 return "";
305}
306
Johannes Doerfertf6183392014-07-01 20:52:51 +0000307/// @brief Return the reduction type for a given binary operator
308static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
309 const Instruction *Load) {
310 if (!BinOp)
311 return MemoryAccess::RT_NONE;
312 switch (BinOp->getOpcode()) {
313 case Instruction::FAdd:
314 if (!BinOp->hasUnsafeAlgebra())
315 return MemoryAccess::RT_NONE;
316 // Fall through
317 case Instruction::Add:
318 return MemoryAccess::RT_ADD;
319 case Instruction::Or:
320 return MemoryAccess::RT_BOR;
321 case Instruction::Xor:
322 return MemoryAccess::RT_BXOR;
323 case Instruction::And:
324 return MemoryAccess::RT_BAND;
325 case Instruction::FMul:
326 if (!BinOp->hasUnsafeAlgebra())
327 return MemoryAccess::RT_NONE;
328 // Fall through
329 case Instruction::Mul:
330 if (DisableMultiplicativeReductions)
331 return MemoryAccess::RT_NONE;
332 return MemoryAccess::RT_MUL;
333 default:
334 return MemoryAccess::RT_NONE;
335 }
336}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000337
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000338/// @brief Derive the individual index expressions from a GEP instruction
339///
340/// This function optimistically assumes the GEP references into a fixed size
341/// array. If this is actually true, this function returns a list of array
342/// subscript expressions as SCEV as well as a list of integers describing
343/// the size of the individual array dimensions. Both lists have either equal
344/// length of the size list is one element shorter in case there is no known
345/// size available for the outermost array dimension.
346///
347/// @param GEP The GetElementPtr instruction to analyze.
348///
349/// @return A tuple with the subscript expressions and the dimension sizes.
350static std::tuple<std::vector<const SCEV *>, std::vector<int>>
351getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
352 std::vector<const SCEV *> Subscripts;
353 std::vector<int> Sizes;
354
355 Type *Ty = GEP->getPointerOperandType();
356
357 bool DroppedFirstDim = false;
358
Michael Kruse26ed65e2015-09-24 17:32:49 +0000359 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000360
361 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
362
363 if (i == 1) {
364 if (auto PtrTy = dyn_cast<PointerType>(Ty)) {
365 Ty = PtrTy->getElementType();
366 } else if (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
367 Ty = ArrayTy->getElementType();
368 } else {
369 Subscripts.clear();
370 Sizes.clear();
371 break;
372 }
373 if (auto Const = dyn_cast<SCEVConstant>(Expr))
374 if (Const->getValue()->isZero()) {
375 DroppedFirstDim = true;
376 continue;
377 }
378 Subscripts.push_back(Expr);
379 continue;
380 }
381
382 auto ArrayTy = dyn_cast<ArrayType>(Ty);
383 if (!ArrayTy) {
384 Subscripts.clear();
385 Sizes.clear();
386 break;
387 }
388
389 Subscripts.push_back(Expr);
390 if (!(DroppedFirstDim && i == 2))
391 Sizes.push_back(ArrayTy->getNumElements());
392
393 Ty = ArrayTy->getElementType();
394 }
395
396 return std::make_tuple(Subscripts, Sizes);
397}
398
Tobias Grosser75805372011-04-29 06:27:02 +0000399MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000400 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000401 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000402 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000403}
404
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000405const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
406 isl_id *ArrayId = getArrayId();
407 void *User = isl_id_get_user(ArrayId);
408 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
409 isl_id_free(ArrayId);
410 return SAI;
411}
412
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000413__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000414 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
415}
416
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000417__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
418 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000419 isl_map *Schedule, *ScheduledAccRel;
420 isl_union_set *UDomain;
421
422 UDomain = isl_union_set_from_set(getStatement()->getDomain());
423 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
424 Schedule = isl_map_from_union_map(USchedule);
425 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
426 return isl_pw_multi_aff_from_map(ScheduledAccRel);
427}
428
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000429__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000430 return isl_map_copy(AccessRelation);
431}
432
Johannes Doerferta99130f2014-10-13 12:58:03 +0000433std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000434 return stringFromIslObj(AccessRelation);
435}
436
Johannes Doerferta99130f2014-10-13 12:58:03 +0000437__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000438 return isl_map_get_space(AccessRelation);
439}
440
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000441__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000442 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000443}
444
Tobias Grosser6f730082015-09-05 07:46:47 +0000445std::string MemoryAccess::getNewAccessRelationStr() const {
446 return stringFromIslObj(NewAccessRelation);
447}
448
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000449__isl_give isl_basic_map *
450MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000451 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000452 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000453
Tobias Grosser084d8f72012-05-29 09:29:44 +0000454 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000455 isl_basic_set_universe(Statement->getDomainSpace()),
456 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000457}
458
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000459// Formalize no out-of-bound access assumption
460//
461// When delinearizing array accesses we optimistically assume that the
462// delinearized accesses do not access out of bound locations (the subscript
463// expression of each array evaluates for each statement instance that is
464// executed to a value that is larger than zero and strictly smaller than the
465// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000466// dimension for which we do not need to assume any upper bound. At this point
467// we formalize this assumption to ensure that at code generation time the
468// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000469//
470// To find the set of constraints necessary to avoid out of bound accesses, we
471// first build the set of data locations that are not within array bounds. We
472// then apply the reverse access relation to obtain the set of iterations that
473// may contain invalid accesses and reduce this set of iterations to the ones
474// that are actually executed by intersecting them with the domain of the
475// statement. If we now project out all loop dimensions, we obtain a set of
476// parameters that may cause statement instances to be executed that may
477// possibly yield out of bound memory accesses. The complement of these
478// constraints is the set of constraints that needs to be assumed to ensure such
479// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000480void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000481 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000482 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Michael Krusee2bccbb2015-09-18 19:59:43 +0000483 for (int i = 1, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000484 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
485 isl_pw_aff *Var =
486 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
487 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
488
489 isl_set *DimOutside;
490
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000491 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Michael Krusee2bccbb2015-09-18 19:59:43 +0000492 isl_pw_aff *SizeE = Statement->getPwAff(Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000493
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000494 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
495 Statement->getNumIterators());
496 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
497 isl_space_dim(Space, isl_dim_set));
498 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
499 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000500
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000501 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000502
503 Outside = isl_set_union(Outside, DimOutside);
504 }
505
506 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
507 Outside = isl_set_intersect(Outside, Statement->getDomain());
508 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000509
510 // Remove divs to avoid the construction of overly complicated assumptions.
511 // Doing so increases the set of parameter combinations that are assumed to
512 // not appear. This is always save, but may make the resulting run-time check
513 // bail out more often than strictly necessary.
514 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000515 Outside = isl_set_complement(Outside);
Johannes Doerfertd84493e2015-11-12 02:33:38 +0000516 Statement->getParent()->addAssumption(INBOUNDS, Outside,
517 getAccessInstruction()->getDebugLoc());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000518 isl_space_free(Space);
519}
520
Johannes Doerferte7044942015-02-24 11:58:30 +0000521void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
522 ScalarEvolution *SE = Statement->getParent()->getSE();
523
524 Value *Ptr = getPointerOperand(*getAccessInstruction());
525 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
526 return;
527
528 auto *PtrSCEV = SE->getSCEV(Ptr);
529 if (isa<SCEVCouldNotCompute>(PtrSCEV))
530 return;
531
532 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
533 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
534 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
535
536 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
537 if (Range.isFullSet())
538 return;
539
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000540 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000541 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000542 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
543 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
544
545 auto Min = LB.sdiv(APInt(BW, ElementSize));
546 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000547
548 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
549 AccessRange =
550 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
551 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
552}
553
Michael Krusee2bccbb2015-09-18 19:59:43 +0000554__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000555 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000556 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000557
558 for (int i = Size - 2; i >= 0; --i) {
559 isl_space *Space;
560 isl_map *MapOne, *MapTwo;
Michael Krusee2bccbb2015-09-18 19:59:43 +0000561 isl_pw_aff *DimSize = Statement->getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000562
563 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
564 isl_pw_aff_free(DimSize);
565 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
566
567 Space = isl_map_get_space(AccessRelation);
568 Space = isl_space_map_from_set(isl_space_range(Space));
569 Space = isl_space_align_params(Space, SpaceSize);
570
571 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
572 isl_id_free(ParamId);
573
574 MapOne = isl_map_universe(isl_space_copy(Space));
575 for (int j = 0; j < Size; ++j)
576 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
577 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
578
579 MapTwo = isl_map_universe(isl_space_copy(Space));
580 for (int j = 0; j < Size; ++j)
581 if (j < i || j > i + 1)
582 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
583
584 isl_local_space *LS = isl_local_space_from_space(Space);
585 isl_constraint *C;
586 C = isl_equality_alloc(isl_local_space_copy(LS));
587 C = isl_constraint_set_constant_si(C, -1);
588 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
589 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
590 MapTwo = isl_map_add_constraint(MapTwo, C);
591 C = isl_equality_alloc(LS);
592 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
593 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
594 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
595 MapTwo = isl_map_add_constraint(MapTwo, C);
596 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
597
598 MapOne = isl_map_union(MapOne, MapTwo);
599 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
600 }
601 return AccessRelation;
602}
603
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) {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00002866 auto &DL = getRegion().getEntry()->getModule()->getDataLayout();
2867 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, Kind,
2868 DL, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002869 } else {
Tobias Grosser8286b832015-11-02 11:29:32 +00002870 // In case of mismatching array sizes, we bail out by setting the run-time
2871 // context to false.
2872 if (!SAI->updateSizes(Sizes))
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002873 addAssumption(DELINEARIZATION, isl_set_empty(getParamSpace()),
2874 DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002875 }
Tobias Grosserab671442015-05-23 05:58:27 +00002876 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002877}
2878
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002879const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
2880 ScopArrayInfo::ARRAYKIND Kind) {
2881 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002882 assert(SAI && "No ScopArrayInfo available for this base pointer");
2883 return SAI;
2884}
2885
Tobias Grosser74394f02013-01-14 22:40:23 +00002886std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002887std::string Scop::getAssumedContextStr() const {
2888 return stringFromIslObj(AssumedContext);
2889}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002890std::string Scop::getBoundaryContextStr() const {
2891 return stringFromIslObj(BoundaryContext);
2892}
Tobias Grosser75805372011-04-29 06:27:02 +00002893
2894std::string Scop::getNameStr() const {
2895 std::string ExitName, EntryName;
2896 raw_string_ostream ExitStr(ExitName);
2897 raw_string_ostream EntryStr(EntryName);
2898
Tobias Grosserf240b482014-01-09 10:42:15 +00002899 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002900 EntryStr.str();
2901
2902 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00002903 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002904 ExitStr.str();
2905 } else
2906 ExitName = "FunctionExit";
2907
2908 return EntryName + "---" + ExitName;
2909}
2910
Tobias Grosser74394f02013-01-14 22:40:23 +00002911__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00002912__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002913 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00002914}
2915
Tobias Grossere86109f2013-10-29 21:05:49 +00002916__isl_give isl_set *Scop::getAssumedContext() const {
2917 return isl_set_copy(AssumedContext);
2918}
2919
Johannes Doerfert43788c52015-08-20 05:58:56 +00002920__isl_give isl_set *Scop::getRuntimeCheckContext() const {
2921 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002922 RuntimeCheckContext =
2923 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
2924 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002925 return RuntimeCheckContext;
2926}
2927
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002928bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002929 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002930 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002931 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
2932 isl_set_free(RuntimeCheckContext);
2933 return IsFeasible;
2934}
2935
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002936static std::string toString(AssumptionKind Kind) {
2937 switch (Kind) {
2938 case ALIASING:
2939 return "No-aliasing";
2940 case INBOUNDS:
2941 return "Inbounds";
2942 case WRAPPING:
2943 return "No-overflows";
2944 case ERRORBLOCK:
2945 return "No-error";
2946 case INFINITELOOP:
2947 return "Finite loop";
2948 case INVARIANTLOAD:
2949 return "Invariant load";
2950 case DELINEARIZATION:
2951 return "Delinearization";
2952 }
2953 llvm_unreachable("Unknown AssumptionKind!");
2954}
2955
2956void Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
2957 DebugLoc Loc) {
2958 if (isl_set_is_subset(Context, Set))
2959 return;
2960
2961 if (isl_set_is_subset(AssumedContext, Set))
2962 return;
2963
2964 auto &F = *getRegion().getEntry()->getParent();
2965 std::string Msg = toString(Kind) + " assumption:\t" + stringFromIslObj(Set);
2966 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
2967}
2968
2969void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
2970 DebugLoc Loc) {
2971 trackAssumption(Kind, Set, Loc);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002972 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00002973
Johannes Doerfert9d7899e2015-11-11 20:01:31 +00002974 int NSets = isl_set_n_basic_set(AssumedContext);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00002975 if (NSets >= MaxDisjunctsAssumed) {
2976 isl_space *Space = isl_set_get_space(AssumedContext);
2977 isl_set_free(AssumedContext);
Tobias Grossere19fca42015-11-11 20:21:39 +00002978 AssumedContext = isl_set_empty(Space);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00002979 }
2980
Tobias Grosser7b50bee2014-11-25 10:51:12 +00002981 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002982}
2983
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002984__isl_give isl_set *Scop::getBoundaryContext() const {
2985 return isl_set_copy(BoundaryContext);
2986}
2987
Tobias Grosser75805372011-04-29 06:27:02 +00002988void Scop::printContext(raw_ostream &OS) const {
2989 OS << "Context:\n";
2990
2991 if (!Context) {
2992 OS.indent(4) << "n/a\n\n";
2993 return;
2994 }
2995
2996 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00002997
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002998 OS.indent(4) << "Assumed Context:\n";
2999 if (!AssumedContext) {
3000 OS.indent(4) << "n/a\n\n";
3001 return;
3002 }
3003
3004 OS.indent(4) << getAssumedContextStr() << "\n";
3005
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003006 OS.indent(4) << "Boundary Context:\n";
3007 if (!BoundaryContext) {
3008 OS.indent(4) << "n/a\n\n";
3009 return;
3010 }
3011
3012 OS.indent(4) << getBoundaryContextStr() << "\n";
3013
Tobias Grosser083d3d32014-06-28 08:59:45 +00003014 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00003015 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00003016 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
3017 }
Tobias Grosser75805372011-04-29 06:27:02 +00003018}
3019
Johannes Doerfertb164c792014-09-18 11:17:17 +00003020void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003021 int noOfGroups = 0;
3022 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003023 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003024 noOfGroups += 1;
3025 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003026 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003027 }
3028
Tobias Grosserbb853c22015-07-25 12:31:03 +00003029 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003030 if (MinMaxAliasGroups.empty()) {
3031 OS.indent(8) << "n/a\n";
3032 return;
3033 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003034
Tobias Grosserbb853c22015-07-25 12:31:03 +00003035 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003036
3037 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003038 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003039 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003040 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003041 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3042 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003043 }
3044 OS << " ]]\n";
3045 }
3046
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003047 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003048 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003049 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003050 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003051 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3052 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003053 }
3054 OS << " ]]\n";
3055 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003056 }
3057}
3058
Tobias Grosser75805372011-04-29 06:27:02 +00003059void Scop::printStatements(raw_ostream &OS) const {
3060 OS << "Statements {\n";
3061
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003062 for (const ScopStmt &Stmt : *this)
3063 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003064
3065 OS.indent(4) << "}\n";
3066}
3067
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003068void Scop::printArrayInfo(raw_ostream &OS) const {
3069 OS << "Arrays {\n";
3070
Tobias Grosserab671442015-05-23 05:58:27 +00003071 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003072 Array.second->print(OS);
3073
3074 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003075
3076 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3077
3078 for (auto &Array : arrays())
3079 Array.second->print(OS, /* SizeAsPwAff */ true);
3080
3081 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003082}
3083
Tobias Grosser75805372011-04-29 06:27:02 +00003084void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00003085 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
3086 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003087 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003088 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003089 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003090 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003091 const auto &MAs = std::get<1>(IAClass);
3092 if (MAs.empty()) {
3093 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003094 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003095 MAs.front()->print(OS);
3096 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003097 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003098 }
3099 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003100 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003101 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003102 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003103 printStatements(OS.indent(4));
3104}
3105
3106void Scop::dump() const { print(dbgs()); }
3107
Tobias Grosser9a38ab82011-11-08 15:41:03 +00003108isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00003109
Johannes Doerfertcef616f2015-09-15 22:49:04 +00003110__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
3111 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003112}
3113
Tobias Grosser808cd692015-07-14 09:33:13 +00003114__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003115 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003116
Tobias Grosser808cd692015-07-14 09:33:13 +00003117 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003118 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003119
3120 return Domain;
3121}
3122
Tobias Grossere5a35142015-11-12 14:07:09 +00003123__isl_give isl_union_map *
3124Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3125 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003126
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003127 for (ScopStmt &Stmt : *this) {
3128 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003129 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003130 continue;
3131
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003132 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003133 isl_map *AccessDomain = MA->getAccessRelation();
3134 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003135 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003136 }
3137 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003138 return isl_union_map_coalesce(Accesses);
3139}
3140
3141__isl_give isl_union_map *Scop::getMustWrites() {
3142 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003143}
3144
3145__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003146 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003147}
3148
Tobias Grosser37eb4222014-02-20 21:43:54 +00003149__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003150 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003151}
3152
3153__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003154 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003155}
3156
Tobias Grosser2ac23382015-11-12 14:07:13 +00003157__isl_give isl_union_map *Scop::getAccesses() {
3158 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3159}
3160
Tobias Grosser808cd692015-07-14 09:33:13 +00003161__isl_give isl_union_map *Scop::getSchedule() const {
3162 auto Tree = getScheduleTree();
3163 auto S = isl_schedule_get_map(Tree);
3164 isl_schedule_free(Tree);
3165 return S;
3166}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003167
Tobias Grosser808cd692015-07-14 09:33:13 +00003168__isl_give isl_schedule *Scop::getScheduleTree() const {
3169 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3170 getDomains());
3171}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003172
Tobias Grosser808cd692015-07-14 09:33:13 +00003173void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3174 auto *S = isl_schedule_from_domain(getDomains());
3175 S = isl_schedule_insert_partial_schedule(
3176 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3177 isl_schedule_free(Schedule);
3178 Schedule = S;
3179}
3180
3181void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3182 isl_schedule_free(Schedule);
3183 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003184}
3185
3186bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3187 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003188 for (ScopStmt &Stmt : *this) {
3189 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003190 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3191 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3192
3193 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3194 isl_union_set_free(StmtDomain);
3195 isl_union_set_free(NewStmtDomain);
3196 continue;
3197 }
3198
3199 Changed = true;
3200
3201 isl_union_set_free(StmtDomain);
3202 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3203
3204 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003205 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003206 isl_union_set_free(NewStmtDomain);
3207 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003208 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003209 }
3210 isl_union_set_free(Domain);
3211 return Changed;
3212}
3213
Tobias Grosser75805372011-04-29 06:27:02 +00003214ScalarEvolution *Scop::getSE() const { return SE; }
3215
Johannes Doerfertf5673802015-10-01 23:48:18 +00003216bool Scop::isIgnored(RegionNode *RN) {
3217 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser75805372011-04-29 06:27:02 +00003218
Johannes Doerfertf5673802015-10-01 23:48:18 +00003219 // Check if there are accesses contained.
3220 bool ContainsAccesses = false;
3221 if (!RN->isSubRegion())
3222 ContainsAccesses = getAccessFunctions(BB);
3223 else
3224 for (BasicBlock *RBB : RN->getNodeAs<Region>()->blocks())
3225 ContainsAccesses |= (getAccessFunctions(RBB) != nullptr);
3226 if (!ContainsAccesses)
3227 return true;
3228
3229 // Check for reachability via non-error blocks.
3230 if (!DomainMap.count(BB))
3231 return true;
3232
3233 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003234 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003235 return true;
3236
3237 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003238}
3239
Tobias Grosser808cd692015-07-14 09:33:13 +00003240struct MapToDimensionDataTy {
3241 int N;
3242 isl_union_pw_multi_aff *Res;
3243};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003244
Tobias Grosser808cd692015-07-14 09:33:13 +00003245// @brief Create a function that maps the elements of 'Set' to its N-th
3246// dimension.
3247//
3248// The result is added to 'User->Res'.
3249//
3250// @param Set The input set.
3251// @param N The dimension to map to.
3252//
3253// @returns Zero if no error occurred, non-zero otherwise.
3254static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3255 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3256 int Dim;
3257 isl_space *Space;
3258 isl_pw_multi_aff *PMA;
3259
3260 Dim = isl_set_dim(Set, isl_dim_set);
3261 Space = isl_set_get_space(Set);
3262 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3263 Dim - Data->N);
3264 if (Data->N > 1)
3265 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3266 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3267
3268 isl_set_free(Set);
3269
3270 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003271}
3272
Tobias Grosser808cd692015-07-14 09:33:13 +00003273// @brief Create a function that maps the elements of Domain to their Nth
3274// dimension.
3275//
3276// @param Domain The set of elements to map.
3277// @param N The dimension to map to.
3278static __isl_give isl_multi_union_pw_aff *
3279mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003280 if (N <= 0 || isl_union_set_is_empty(Domain)) {
3281 isl_union_set_free(Domain);
3282 return nullptr;
3283 }
3284
Tobias Grosser808cd692015-07-14 09:33:13 +00003285 struct MapToDimensionDataTy Data;
3286 isl_space *Space;
3287
3288 Space = isl_union_set_get_space(Domain);
3289 Data.N = N;
3290 Data.Res = isl_union_pw_multi_aff_empty(Space);
3291 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
3292 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
3293
3294 isl_union_set_free(Domain);
3295 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3296}
3297
Tobias Grosser316b5b22015-11-11 19:28:14 +00003298void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003299 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003300 Stmts.emplace_back(*this, *BB);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003301 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003302 StmtMap[BB] = Stmt;
3303 } else {
3304 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003305 Stmts.emplace_back(*this, *R);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003306 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003307 for (BasicBlock *BB : R->blocks())
3308 StmtMap[BB] = Stmt;
3309 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003310}
3311
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003312void Scop::buildSchedule(
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003313 Region *R,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003314 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00003315
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003316 if (SD.isNonAffineSubRegion(R, &getRegion())) {
Johannes Doerfertc6987c12015-09-26 13:41:43 +00003317 Loop *L = getLoopSurroundingRegion(*R, LI);
3318 auto &LSchedulePair = LoopSchedules[L];
Michael Krusecac948e2015-10-02 13:53:07 +00003319 ScopStmt *Stmt = getStmtForBasicBlock(R->getEntry());
Michael Kruseafe06702015-10-02 16:33:27 +00003320 isl_set *Domain = Stmt->getDomain();
Michael Krusecac948e2015-10-02 13:53:07 +00003321 auto *UDomain = isl_union_set_from_set(Domain);
3322 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003323 LSchedulePair.first = StmtSchedule;
3324 return;
3325 }
3326
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003327 ReversePostOrderTraversal<Region *> RTraversal(R);
3328 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00003329
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003330 if (RN->isSubRegion()) {
3331 Region *SubRegion = RN->getNodeAs<Region>();
3332 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003333 buildSchedule(SubRegion, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003334 continue;
3335 }
Tobias Grosser75805372011-04-29 06:27:02 +00003336 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003337
3338 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert30c22652015-10-18 21:17:11 +00003339 if (!getRegion().contains(L))
3340 L = getLoopSurroundingRegion(getRegion(), LI);
3341
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003342 int LD = getRelativeLoopDepth(L);
3343 auto &LSchedulePair = LoopSchedules[L];
3344 LSchedulePair.second += getNumBlocksInRegionNode(RN);
3345
Michael Krusecac948e2015-10-02 13:53:07 +00003346 BasicBlock *BB = getRegionNodeBasicBlock(RN);
3347 ScopStmt *Stmt = getStmtForBasicBlock(BB);
3348 if (Stmt) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003349 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3350 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
3351 LSchedulePair.first =
3352 combineInSequence(LSchedulePair.first, StmtSchedule);
3353 }
3354
3355 unsigned NumVisited = LSchedulePair.second;
3356 while (L && NumVisited == L->getNumBlocks()) {
3357 auto *LDomain = isl_schedule_get_domain(LSchedulePair.first);
3358 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
3359 LSchedulePair.first =
3360 isl_schedule_insert_partial_schedule(LSchedulePair.first, MUPA);
3361
3362 auto *PL = L->getParentLoop();
Johannes Doerfertdca28372015-11-03 00:28:07 +00003363
3364 // Either we have a proper loop and we also build a schedule for the
3365 // parent loop or we have a infinite loop that does not have a proper
3366 // parent loop. In the former case this conditional will be skipped, in
3367 // the latter case however we will break here as we do not build a domain
3368 // nor a schedule for a infinite loop.
3369 assert(LoopSchedules.count(PL) || LSchedulePair.first == nullptr);
3370 if (!LoopSchedules.count(PL))
3371 break;
3372
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003373 auto &PSchedulePair = LoopSchedules[PL];
3374 PSchedulePair.first =
3375 combineInSequence(PSchedulePair.first, LSchedulePair.first);
3376 PSchedulePair.second += NumVisited;
3377
3378 L = PL;
3379 NumVisited = PSchedulePair.second;
3380 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003381 }
Tobias Grosser75805372011-04-29 06:27:02 +00003382}
3383
Johannes Doerfert7c494212014-10-31 23:13:39 +00003384ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003385 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003386 if (StmtMapIt == StmtMap.end())
3387 return nullptr;
3388 return StmtMapIt->second;
3389}
3390
Johannes Doerfert96425c22015-08-30 21:13:53 +00003391int Scop::getRelativeLoopDepth(const Loop *L) const {
3392 Loop *OuterLoop =
3393 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3394 if (!OuterLoop)
3395 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003396 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3397}
3398
Michael Krused868b5d2015-09-10 15:25:24 +00003399void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003400 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003401
3402 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3403 // true, are not modeled as ordinary PHI nodes as they are not part of the
3404 // region. However, we model the operands in the predecessor blocks that are
3405 // part of the region as regular scalar accesses.
3406
3407 // If we can synthesize a PHI we can skip it, however only if it is in
3408 // the region. If it is not it can only be in the exit block of the region.
3409 // In this case we model the operands but not the PHI itself.
3410 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3411 return;
3412
3413 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3414 // detection. Hence, the PHI is a load of a new memory location in which the
3415 // incoming value was written at the end of the incoming basic block.
3416 bool OnlyNonAffineSubRegionOperands = true;
3417 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3418 Value *Op = PHI->getIncomingValue(u);
3419 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3420
3421 // Do not build scalar dependences inside a non-affine subregion.
3422 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3423 continue;
3424
3425 OnlyNonAffineSubRegionOperands = false;
3426
3427 if (!R.contains(OpBB))
3428 continue;
3429
3430 Instruction *OpI = dyn_cast<Instruction>(Op);
3431 if (OpI) {
3432 BasicBlock *OpIBB = OpI->getParent();
3433 // As we pretend there is a use (or more precise a write) of OpI in OpBB
3434 // we have to insert a scalar dependence from the definition of OpI to
3435 // OpBB if the definition is not in OpBB.
Michael Kruse668af712015-10-15 14:45:48 +00003436 if (scop->getStmtForBasicBlock(OpIBB) !=
3437 scop->getStmtForBasicBlock(OpBB)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003438 addScalarReadAccess(OpI, PHI, OpBB);
3439 addScalarWriteAccess(OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003440 }
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003441 } else if (ModelReadOnlyScalars && !isa<Constant>(Op)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003442 addScalarReadAccess(Op, PHI, OpBB);
Michael Kruse7bf39442015-09-10 12:46:52 +00003443 }
3444
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003445 addPHIWriteAccess(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003446 }
3447
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003448 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3449 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003450 }
3451}
3452
Michael Krused868b5d2015-09-10 15:25:24 +00003453bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
3454 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003455 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
3456 if (isIgnoredIntrinsic(Inst))
3457 return false;
3458
3459 bool AnyCrossStmtUse = false;
3460 BasicBlock *ParentBB = Inst->getParent();
3461
3462 for (User *U : Inst->users()) {
3463 Instruction *UI = dyn_cast<Instruction>(U);
3464
3465 // Ignore the strange user
3466 if (UI == 0)
3467 continue;
3468
3469 BasicBlock *UseParent = UI->getParent();
3470
Tobias Grosserbaffa092015-10-24 20:55:27 +00003471 // Ignore basic block local uses. A value that is defined in a scop, but
3472 // used in a PHI node in the same basic block does not count as basic block
3473 // local, as for such cases a control flow edge is passed between definition
3474 // and use.
3475 if (UseParent == ParentBB && !isa<PHINode>(UI))
Michael Kruse7bf39442015-09-10 12:46:52 +00003476 continue;
3477
Michael Krusef714d472015-11-05 13:18:43 +00003478 // Uses by PHI nodes in the entry node count as external uses in case the
3479 // use is through an incoming block that is itself not contained in the
3480 // region.
3481 if (R->getEntry() == UseParent) {
3482 if (auto *PHI = dyn_cast<PHINode>(UI)) {
3483 bool ExternalUse = false;
3484 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
3485 if (PHI->getIncomingValue(i) == Inst &&
3486 !R->contains(PHI->getIncomingBlock(i))) {
3487 ExternalUse = true;
3488 break;
3489 }
3490 }
3491
3492 if (ExternalUse) {
3493 AnyCrossStmtUse = true;
3494 continue;
3495 }
3496 }
3497 }
3498
Michael Kruse7bf39442015-09-10 12:46:52 +00003499 // Do not build scalar dependences inside a non-affine subregion.
3500 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
3501 continue;
3502
Michael Kruse01cb3792015-10-17 21:07:08 +00003503 // Check for PHI nodes in the region exit and skip them, if they will be
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003504 // modeled as PHI nodes.
Michael Kruse01cb3792015-10-17 21:07:08 +00003505 //
3506 // PHI nodes in the region exit that have more than two incoming edges need
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003507 // to be modeled as PHI-Nodes to correctly model the fact that depending on
3508 // the control flow a different value will be assigned to the PHI node. In
3509 // case this is the case, there is no need to create an additional normal
3510 // scalar dependence. Hence, bail out before we register an "out-of-region"
3511 // use for this definition.
Michael Kruse01cb3792015-10-17 21:07:08 +00003512 if (isa<PHINode>(UI) && UI->getParent() == R->getExit() &&
3513 !R->getExitingBlock())
3514 continue;
3515
Michael Kruse7bf39442015-09-10 12:46:52 +00003516 // Check whether or not the use is in the SCoP.
Tobias Grosserc73d8b02015-10-23 22:36:22 +00003517 if (!R->contains(UseParent)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003518 AnyCrossStmtUse = true;
3519 continue;
3520 }
3521
3522 // If the instruction can be synthesized and the user is in the region
3523 // we do not need to add scalar dependences.
3524 if (canSynthesizeInst)
3525 continue;
3526
3527 // No need to translate these scalar dependences into polyhedral form,
3528 // because synthesizable scalars can be generated by the code generator.
3529 if (canSynthesize(UI, LI, SE, R))
3530 continue;
3531
3532 // Skip PHI nodes in the region as they handle their operands on their own.
3533 if (isa<PHINode>(UI))
3534 continue;
3535
3536 // Now U is used in another statement.
3537 AnyCrossStmtUse = true;
3538
3539 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00003540 // Use the def instruction as base address of the MemoryAccess, so that it
3541 // will become the name of the scalar access in the polyhedral form.
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003542 addScalarReadAccess(Inst, UI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003543 }
3544
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003545 if (ModelReadOnlyScalars && !isa<PHINode>(Inst)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003546 for (Value *Op : Inst->operands()) {
3547 if (canSynthesize(Op, LI, SE, R))
3548 continue;
3549
3550 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
3551 if (R->contains(OpInst))
3552 continue;
3553
3554 if (isa<Constant>(Op))
3555 continue;
3556
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003557 addScalarReadAccess(Op, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003558 }
3559 }
3560
3561 return AnyCrossStmtUse;
3562}
3563
3564extern MapInsnToMemAcc InsnToMemAcc;
3565
Michael Krusee2bccbb2015-09-18 19:59:43 +00003566void ScopInfo::buildMemoryAccess(
3567 Instruction *Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003568 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3569 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003570 unsigned Size;
3571 Type *SizeType;
3572 Value *Val;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003573 enum MemoryAccess::AccessType Type;
Michael Kruse7bf39442015-09-10 12:46:52 +00003574
3575 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
3576 SizeType = Load->getType();
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003577 Size = TD->getTypeAllocSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003578 Type = MemoryAccess::READ;
Michael Kruse7bf39442015-09-10 12:46:52 +00003579 Val = Load;
3580 } else {
3581 StoreInst *Store = cast<StoreInst>(Inst);
3582 SizeType = Store->getValueOperand()->getType();
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003583 Size = TD->getTypeAllocSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003584 Type = MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003585 Val = Store->getValueOperand();
3586 }
3587
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003588 auto Address = getPointerOperand(*Inst);
3589
3590 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003591 const SCEVUnknown *BasePointer =
3592 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3593
3594 assert(BasePointer && "Could not find base pointer");
3595 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
3596
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003597 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3598 auto NewAddress = Address;
3599 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3600 auto Src = BitCast->getOperand(0);
3601 auto SrcTy = Src->getType();
3602 auto DstTy = BitCast->getType();
3603 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3604 NewAddress = Src;
3605 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003606
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003607 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3608 std::vector<const SCEV *> Subscripts;
3609 std::vector<int> Sizes;
3610 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3611 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003612
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003613 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003614
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003615 bool AllAffineSubcripts = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003616 for (auto Subscript : Subscripts) {
3617 InvariantLoadsSetTy AccessILS;
3618 AllAffineSubcripts =
3619 isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS);
3620
3621 for (LoadInst *LInst : AccessILS)
3622 if (!ScopRIL.count(LInst))
3623 AllAffineSubcripts = false;
3624
3625 if (!AllAffineSubcripts)
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003626 break;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003627 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003628
3629 if (AllAffineSubcripts && Sizes.size() > 0) {
3630 for (auto V : Sizes)
3631 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3632 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003633 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003634 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003635
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003636 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3637 Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00003638 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003639 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003640 }
3641 }
3642
Michael Kruse7bf39442015-09-10 12:46:52 +00003643 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003644 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003645 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3646 AccItr->second.DelinearizedSubscripts,
3647 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003648 return;
3649 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003650
3651 // Check if the access depends on a loop contained in a non-affine subregion.
3652 bool isVariantInNonAffineLoop = false;
3653 if (BoxedLoops) {
3654 SetVector<const Loop *> Loops;
3655 findLoops(AccessFunction, Loops);
3656 for (const Loop *L : Loops)
3657 if (BoxedLoops->count(L))
3658 isVariantInNonAffineLoop = true;
3659 }
3660
Johannes Doerfert09e36972015-10-07 20:17:36 +00003661 InvariantLoadsSetTy AccessILS;
3662 bool IsAffine =
3663 !isVariantInNonAffineLoop &&
3664 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3665
3666 for (LoadInst *LInst : AccessILS)
3667 if (!ScopRIL.count(LInst))
3668 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003669
Michael Krusecaac2b62015-09-26 15:51:44 +00003670 // FIXME: Size of the number of bytes of an array element, not the number of
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003671 // elements as probably intended here.
Tobias Grossera43b6e92015-09-27 17:54:50 +00003672 const SCEV *SizeSCEV =
3673 SE->getConstant(TD->getIntPtrType(Inst->getContext()), Size);
Michael Kruse7bf39442015-09-10 12:46:52 +00003674
Michael Krusee2bccbb2015-09-18 19:59:43 +00003675 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3676 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003677
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003678 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, IsAffine,
3679 ArrayRef<const SCEV *>(AccessFunction),
3680 ArrayRef<const SCEV *>(SizeSCEV), Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003681}
3682
Michael Krused868b5d2015-09-10 15:25:24 +00003683void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003684
3685 if (SD->isNonAffineSubRegion(&SR, &R)) {
3686 for (BasicBlock *BB : SR.blocks())
3687 buildAccessFunctions(R, *BB, &SR);
3688 return;
3689 }
3690
3691 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3692 if (I->isSubRegion())
3693 buildAccessFunctions(R, *I->getNodeAs<Region>());
3694 else
3695 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
3696}
3697
Michael Krusecac948e2015-10-02 13:53:07 +00003698void ScopInfo::buildStmts(Region &SR) {
3699 Region *R = getRegion();
3700
3701 if (SD->isNonAffineSubRegion(&SR, R)) {
3702 scop->addScopStmt(nullptr, &SR);
3703 return;
3704 }
3705
3706 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3707 if (I->isSubRegion())
3708 buildStmts(*I->getNodeAs<Region>());
3709 else
3710 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
3711}
3712
Michael Krused868b5d2015-09-10 15:25:24 +00003713void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
3714 Region *NonAffineSubRegion,
3715 bool IsExitBlock) {
Tobias Grosser910cf262015-11-11 20:15:49 +00003716 // We do not build access functions for error blocks, as they may contain
3717 // instructions we can not model.
3718 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3719 if (isErrorBlock(BB, R, *LI, DT) && !IsExitBlock)
3720 return;
3721
Michael Kruse7bf39442015-09-10 12:46:52 +00003722 Loop *L = LI->getLoopFor(&BB);
3723
3724 // The set of loops contained in non-affine subregions that are part of R.
3725 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3726
Johannes Doerfert09e36972015-10-07 20:17:36 +00003727 // The set of loads that are required to be invariant.
3728 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
3729
Michael Kruse7bf39442015-09-10 12:46:52 +00003730 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00003731 Instruction *Inst = &*I;
Michael Kruse7bf39442015-09-10 12:46:52 +00003732
3733 PHINode *PHI = dyn_cast<PHINode>(Inst);
3734 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003735 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003736
3737 // For the exit block we stop modeling after the last PHI node.
3738 if (!PHI && IsExitBlock)
3739 break;
3740
Johannes Doerfert09e36972015-10-07 20:17:36 +00003741 // TODO: At this point we only know that elements of ScopRIL have to be
3742 // invariant and will be hoisted for the SCoP to be processed. Though,
3743 // there might be other invariant accesses that will be hoisted and
3744 // that would allow to make a non-affine access affine.
Michael Kruse7bf39442015-09-10 12:46:52 +00003745 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
Johannes Doerfert09e36972015-10-07 20:17:36 +00003746 buildMemoryAccess(Inst, L, &R, BoxedLoops, ScopRIL);
Michael Kruse7bf39442015-09-10 12:46:52 +00003747
3748 if (isIgnoredIntrinsic(Inst))
3749 continue;
3750
Johannes Doerfert09e36972015-10-07 20:17:36 +00003751 // Do not build scalar dependences for required invariant loads as we will
3752 // hoist them later on anyway or drop the SCoP if we cannot.
3753 if (ScopRIL.count(dyn_cast<LoadInst>(Inst)))
3754 continue;
3755
Michael Kruse7bf39442015-09-10 12:46:52 +00003756 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00003757 if (!isa<StoreInst>(Inst))
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003758 addScalarWriteAccess(Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003759 }
3760 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003761}
Michael Kruse7bf39442015-09-10 12:46:52 +00003762
Michael Kruse2d0ece92015-09-24 11:41:21 +00003763void ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3764 MemoryAccess::AccessType Type,
3765 Value *BaseAddress, unsigned ElemBytes,
3766 bool Affine, Value *AccessValue,
3767 ArrayRef<const SCEV *> Subscripts,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003768 ArrayRef<const SCEV *> Sizes,
3769 MemoryAccess::AccessOrigin Origin) {
Michael Krusecac948e2015-10-02 13:53:07 +00003770 ScopStmt *Stmt = scop->getStmtForBasicBlock(BB);
3771
3772 // Do not create a memory access for anything not in the SCoP. It would be
3773 // ignored anyway.
3774 if (!Stmt)
3775 return;
3776
Michael Krusee2bccbb2015-09-18 19:59:43 +00003777 AccFuncSetType &AccList = AccFuncMap[BB];
Michael Krusee2bccbb2015-09-18 19:59:43 +00003778 Value *BaseAddr = BaseAddress;
3779 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3780
Michael Krusecac948e2015-10-02 13:53:07 +00003781 bool isApproximated =
3782 Stmt->isRegionStmt() && (Stmt->getRegion()->getEntry() != BB);
3783 if (isApproximated && Type == MemoryAccess::MUST_WRITE)
3784 Type = MemoryAccess::MAY_WRITE;
3785
Tobias Grosserf1bfd752015-11-05 20:15:37 +00003786 AccList.emplace_back(Stmt, Inst, Type, BaseAddress, ElemBytes, Affine,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003787 Subscripts, Sizes, AccessValue, Origin, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00003788 Stmt->addAccess(&AccList.back());
Michael Kruse7bf39442015-09-10 12:46:52 +00003789}
3790
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003791void ScopInfo::addExplicitAccess(
3792 Instruction *MemAccInst, MemoryAccess::AccessType Type, Value *BaseAddress,
3793 unsigned ElemBytes, bool IsAffine, ArrayRef<const SCEV *> Subscripts,
3794 ArrayRef<const SCEV *> Sizes, Value *AccessValue) {
3795 assert(isa<LoadInst>(MemAccInst) || isa<StoreInst>(MemAccInst));
3796 assert(isa<LoadInst>(MemAccInst) == (Type == MemoryAccess::READ));
3797 addMemoryAccess(MemAccInst->getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003798 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
3799 MemoryAccess::EXPLICIT);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003800}
3801void ScopInfo::addScalarWriteAccess(Instruction *Value) {
3802 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
3803 true, Value, ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003804 ArrayRef<const SCEV *>(), MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003805}
3806void ScopInfo::addScalarReadAccess(Value *Value, Instruction *User) {
3807 assert(!isa<PHINode>(User));
3808 addMemoryAccess(User->getParent(), User, MemoryAccess::READ, Value, 1, true,
3809 Value, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003810 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003811}
3812void ScopInfo::addScalarReadAccess(Value *Value, PHINode *User,
3813 BasicBlock *UserBB) {
3814 addMemoryAccess(UserBB, User, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003815 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3816 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003817}
3818void ScopInfo::addPHIWriteAccess(PHINode *PHI, BasicBlock *IncomingBlock,
3819 Value *IncomingValue, bool IsExitBlock) {
3820 addMemoryAccess(IncomingBlock, IncomingBlock->getTerminator(),
3821 MemoryAccess::MUST_WRITE, PHI, 1, true, IncomingValue,
3822 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003823 IsExitBlock ? MemoryAccess::SCALAR : MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003824}
3825void ScopInfo::addPHIReadAccess(PHINode *PHI) {
3826 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003827 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3828 MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003829}
3830
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003831void ScopInfo::buildScop(Region &R, DominatorTree &DT, AssumptionCache &AC) {
Michael Kruse9d080092015-09-11 21:41:48 +00003832 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003833 scop = new Scop(R, AccFuncMap, *SD, *SE, DT, *LI, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00003834
Michael Krusecac948e2015-10-02 13:53:07 +00003835 buildStmts(R);
Michael Kruse7bf39442015-09-10 12:46:52 +00003836 buildAccessFunctions(R, R);
3837
3838 // In case the region does not have an exiting block we will later (during
3839 // code generation) split the exit block. This will move potential PHI nodes
3840 // from the current exit block into the new region exiting block. Hence, PHI
3841 // nodes that are at this point not part of the region will be.
3842 // To handle these PHI nodes later we will now model their operands as scalar
3843 // accesses. Note that we do not model anything in the exit block if we have
3844 // an exiting block in the region, as there will not be any splitting later.
3845 if (!R.getExitingBlock())
3846 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
3847
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003848 scop->init(*AA, AC);
Michael Kruse7bf39442015-09-10 12:46:52 +00003849}
3850
Michael Krused868b5d2015-09-10 15:25:24 +00003851void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00003852 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00003853 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00003854 return;
3855 }
3856
Michael Kruse9d080092015-09-11 21:41:48 +00003857 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00003858}
3859
Michael Krused868b5d2015-09-10 15:25:24 +00003860void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00003861 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00003862 if (scop) {
3863 delete scop;
3864 scop = 0;
3865 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003866}
3867
3868//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00003869ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00003870 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00003871 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00003872}
3873
3874ScopInfo::~ScopInfo() {
3875 clear();
3876 isl_ctx_free(ctx);
3877}
3878
Tobias Grosser75805372011-04-29 06:27:02 +00003879void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00003880 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00003881 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00003882 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00003883 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
3884 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003885 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003886 AU.addRequired<AssumptionCacheTracker>();
Tobias Grosser75805372011-04-29 06:27:02 +00003887 AU.setPreservesAll();
3888}
3889
3890bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00003891 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00003892
Michael Krused868b5d2015-09-10 15:25:24 +00003893 if (!SD->isMaxRegionInScop(*R))
3894 return false;
3895
3896 Function *F = R->getEntry()->getParent();
3897 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3898 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3899 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3900 TD = &F->getParent()->getDataLayout();
3901 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003902 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krused868b5d2015-09-10 15:25:24 +00003903
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00003904 DebugLoc Beg, End;
3905 getDebugLocations(R, Beg, End);
3906 std::string Msg = "SCoP begins here.";
3907 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg);
3908
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003909 buildScop(*R, DT, AC);
Tobias Grosser75805372011-04-29 06:27:02 +00003910
Tobias Grosserd6a50b32015-05-30 06:26:21 +00003911 DEBUG(scop->print(dbgs()));
3912
Michael Kruseafe06702015-10-02 16:33:27 +00003913 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00003914 Msg = "SCoP ends here but was dismissed.";
Johannes Doerfert43788c52015-08-20 05:58:56 +00003915 delete scop;
3916 scop = nullptr;
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00003917 } else {
3918 Msg = "SCoP ends here.";
3919 ++ScopFound;
3920 if (scop->getMaxLoopDepth() > 0)
3921 ++RichScopFound;
Johannes Doerfert43788c52015-08-20 05:58:56 +00003922 }
3923
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00003924 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg);
3925
Tobias Grosser75805372011-04-29 06:27:02 +00003926 return false;
3927}
3928
3929char ScopInfo::ID = 0;
3930
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003931Pass *polly::createScopInfoPass() { return new ScopInfo(); }
3932
Tobias Grosser73600b82011-10-08 00:30:40 +00003933INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
3934 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003935 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003936INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003937INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00003938INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00003939INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00003940INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003941INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003942INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00003943INITIALIZE_PASS_END(ScopInfo, "polly-scops",
3944 "Polly - Create polyhedral description of Scops", false,
3945 false)