blob: b1fa5804d7427c117080c4c185a336866a9e87dd [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===--------- ScopInfo.cpp - Create Scops from LLVM IR ------------------===//
2//
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"
Michael Kruse7bf39442015-09-10 12:46:52 +000026#include "polly/CodeGen/BlockGenerators.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000027#include "llvm/ADT/MapVector.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000028#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000029#include "llvm/ADT/Statistic.h"
Johannes Doerfertecff11d2015-05-22 23:43:58 +000030#include "llvm/ADT/STLExtras.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000031#include "llvm/ADT/StringExtras.h"
Johannes Doerfert96425c22015-08-30 21:13:53 +000032#include "llvm/ADT/PostOrderIterator.h"
Johannes Doerfertb68cffb2015-09-10 15:27:46 +000033#include "llvm/Analysis/LoopIterator.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000034#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000035#include "llvm/Analysis/LoopInfo.h"
Tobias Grosser83628182013-05-07 08:11:54 +000036#include "llvm/Analysis/RegionIterator.h"
37#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser75805372011-04-29 06:27:02 +000038#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000039#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000040#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000041#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000042#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000043#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000044#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000045#include "isl/schedule.h"
46#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000047#include "isl/set.h"
48#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000049#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000050#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000051#include <sstream>
52#include <string>
53#include <vector>
54
55using namespace llvm;
56using namespace polly;
57
Chandler Carruth95fef942014-04-22 03:30:19 +000058#define DEBUG_TYPE "polly-scops"
59
Tobias Grosser74394f02013-01-14 22:40:23 +000060STATISTIC(ScopFound, "Number of valid Scops");
61STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000062
Michael Kruse7bf39442015-09-10 12:46:52 +000063static cl::opt<bool> ModelReadOnlyScalars(
64 "polly-analyze-read-only-scalars",
65 cl::desc("Model read-only scalar values in the scop description"),
66 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
67
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000068// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000069// operations can overflow easily. Additive reductions and bit operations
70// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000071static cl::opt<bool> DisableMultiplicativeReductions(
72 "polly-disable-multiplicative-reductions",
73 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
74 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000075
Johannes Doerfert9143d672014-09-27 11:02:39 +000076static cl::opt<unsigned> RunTimeChecksMaxParameters(
77 "polly-rtc-max-parameters",
78 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
79 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
80
Tobias Grosser71500722015-03-28 15:11:14 +000081static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
82 "polly-rtc-max-arrays-per-group",
83 cl::desc("The maximal number of arrays to compare in each alias group."),
84 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000085static cl::opt<std::string> UserContextStr(
86 "polly-context", cl::value_desc("isl parameter set"),
87 cl::desc("Provide additional constraints on the context parameters"),
88 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000089
Tobias Grosserd83b8a82015-08-20 19:08:11 +000090static cl::opt<bool> DetectReductions("polly-detect-reductions",
91 cl::desc("Detect and exploit reductions"),
92 cl::Hidden, cl::ZeroOrMore,
93 cl::init(true), cl::cat(PollyCategory));
94
Michael Kruse7bf39442015-09-10 12:46:52 +000095//===----------------------------------------------------------------------===//
96/// Helper Classes
97
98void Comparison::print(raw_ostream &OS) const {
99 // Not yet implemented.
100}
101
Michael Kruse046dde42015-08-10 13:01:57 +0000102// Create a sequence of two schedules. Either argument may be null and is
103// interpreted as the empty schedule. Can also return null if both schedules are
104// empty.
105static __isl_give isl_schedule *
106combineInSequence(__isl_take isl_schedule *Prev,
107 __isl_take isl_schedule *Succ) {
108 if (!Prev)
109 return Succ;
110 if (!Succ)
111 return Prev;
112
113 return isl_schedule_sequence(Prev, Succ);
114}
115
Johannes Doerferte7044942015-02-24 11:58:30 +0000116static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
117 const ConstantRange &Range,
118 int dim,
119 enum isl_dim_type type) {
120 isl_val *V;
121 isl_ctx *ctx = isl_set_get_ctx(S);
122
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000123 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
124 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000125 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000126 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
127
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000128 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000129 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000130 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000131 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000132 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
133
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000134 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000135 return isl_set_union(SLB, SUB);
136 else
137 return isl_set_intersect(SLB, SUB);
138}
139
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000140static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
141 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
142 if (!BasePtrLI)
143 return nullptr;
144
145 if (!S->getRegion().contains(BasePtrLI))
146 return nullptr;
147
148 ScalarEvolution &SE = *S->getSE();
149
150 auto *OriginBaseSCEV =
151 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
152 if (!OriginBaseSCEV)
153 return nullptr;
154
155 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
156 if (!OriginBaseSCEVUnknown)
157 return nullptr;
158
159 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue());
160}
161
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000162ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Michael Kruse28468772015-09-14 15:45:33 +0000163 ArrayRef<const SCEV *> DimensionSizes, bool IsPHI,
164 Scop *S)
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000165 : BasePtr(BasePtr), ElementType(ElementType),
Michael Kruse28468772015-09-14 15:45:33 +0000166 DimensionSizes(DimensionSizes.begin(), DimensionSizes.end()),
167 IsPHI(IsPHI) {
Tobias Grosser92245222015-07-28 14:53:44 +0000168 std::string BasePtrName =
169 getIslCompatibleName("MemRef_", BasePtr, IsPHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000170 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000171 for (const SCEV *Expr : DimensionSizes) {
172 isl_pw_aff *Size = S->getPwAff(Expr);
173 DimensionSizesPw.push_back(Size);
174 }
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000175
176 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
177 if (BasePtrOriginSAI)
178 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000179}
180
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000181ScopArrayInfo::~ScopArrayInfo() {
182 isl_id_free(Id);
183 for (isl_pw_aff *Size : DimensionSizesPw)
184 isl_pw_aff_free(Size);
185}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000186
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000187std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
188
189int ScopArrayInfo::getElemSizeInBytes() const {
190 return ElementType->getPrimitiveSizeInBits() / 8;
191}
192
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000193isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
194
195void ScopArrayInfo::dump() const { print(errs()); }
196
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000197void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000198 OS.indent(8) << *getElementType() << " " << getName() << "[*]";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000199 for (unsigned u = 0; u < getNumberOfDimensions(); u++) {
200 OS << "[";
201
202 if (SizeAsPwAff)
203 OS << " " << DimensionSizesPw[u] << " ";
204 else
205 OS << *DimensionSizes[u];
206
207 OS << "]";
208 }
209
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000210 if (BasePtrOriginSAI)
211 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
212
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000213 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000214}
215
216const ScopArrayInfo *
217ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
218 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
219 assert(Id && "Output dimension didn't have an ID");
220 return getFromId(Id);
221}
222
223const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
224 void *User = isl_id_get_user(Id);
225 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
226 isl_id_free(Id);
227 return SAI;
228}
229
Michael Kruse7bf39442015-09-10 12:46:52 +0000230void IRAccess::print(raw_ostream &OS) const {
231 if (isRead())
232 OS << "Read ";
233 else {
234 if (isMayWrite())
235 OS << "May";
236 OS << "Write ";
237 }
238 OS << BaseAddress->getName() << '[' << *Offset << "]\n";
239}
240
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000241const std::string
242MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
243 switch (RT) {
244 case MemoryAccess::RT_NONE:
245 llvm_unreachable("Requested a reduction operator string for a memory "
246 "access which isn't a reduction");
247 case MemoryAccess::RT_ADD:
248 return "+";
249 case MemoryAccess::RT_MUL:
250 return "*";
251 case MemoryAccess::RT_BOR:
252 return "|";
253 case MemoryAccess::RT_BXOR:
254 return "^";
255 case MemoryAccess::RT_BAND:
256 return "&";
257 }
258 llvm_unreachable("Unknown reduction type");
259 return "";
260}
261
Johannes Doerfertf6183392014-07-01 20:52:51 +0000262/// @brief Return the reduction type for a given binary operator
263static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
264 const Instruction *Load) {
265 if (!BinOp)
266 return MemoryAccess::RT_NONE;
267 switch (BinOp->getOpcode()) {
268 case Instruction::FAdd:
269 if (!BinOp->hasUnsafeAlgebra())
270 return MemoryAccess::RT_NONE;
271 // Fall through
272 case Instruction::Add:
273 return MemoryAccess::RT_ADD;
274 case Instruction::Or:
275 return MemoryAccess::RT_BOR;
276 case Instruction::Xor:
277 return MemoryAccess::RT_BXOR;
278 case Instruction::And:
279 return MemoryAccess::RT_BAND;
280 case Instruction::FMul:
281 if (!BinOp->hasUnsafeAlgebra())
282 return MemoryAccess::RT_NONE;
283 // Fall through
284 case Instruction::Mul:
285 if (DisableMultiplicativeReductions)
286 return MemoryAccess::RT_NONE;
287 return MemoryAccess::RT_MUL;
288 default:
289 return MemoryAccess::RT_NONE;
290 }
291}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000292
Tobias Grosser75805372011-04-29 06:27:02 +0000293//===----------------------------------------------------------------------===//
294
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000295/// @brief Derive the individual index expressions from a GEP instruction
296///
297/// This function optimistically assumes the GEP references into a fixed size
298/// array. If this is actually true, this function returns a list of array
299/// subscript expressions as SCEV as well as a list of integers describing
300/// the size of the individual array dimensions. Both lists have either equal
301/// length of the size list is one element shorter in case there is no known
302/// size available for the outermost array dimension.
303///
304/// @param GEP The GetElementPtr instruction to analyze.
305///
306/// @return A tuple with the subscript expressions and the dimension sizes.
307static std::tuple<std::vector<const SCEV *>, std::vector<int>>
308getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
309 std::vector<const SCEV *> Subscripts;
310 std::vector<int> Sizes;
311
312 Type *Ty = GEP->getPointerOperandType();
313
314 bool DroppedFirstDim = false;
315
316 for (long i = 1; i < GEP->getNumOperands(); i++) {
317
318 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
319
320 if (i == 1) {
321 if (auto PtrTy = dyn_cast<PointerType>(Ty)) {
322 Ty = PtrTy->getElementType();
323 } else if (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
324 Ty = ArrayTy->getElementType();
325 } else {
326 Subscripts.clear();
327 Sizes.clear();
328 break;
329 }
330 if (auto Const = dyn_cast<SCEVConstant>(Expr))
331 if (Const->getValue()->isZero()) {
332 DroppedFirstDim = true;
333 continue;
334 }
335 Subscripts.push_back(Expr);
336 continue;
337 }
338
339 auto ArrayTy = dyn_cast<ArrayType>(Ty);
340 if (!ArrayTy) {
341 Subscripts.clear();
342 Sizes.clear();
343 break;
344 }
345
346 Subscripts.push_back(Expr);
347 if (!(DroppedFirstDim && i == 2))
348 Sizes.push_back(ArrayTy->getNumElements());
349
350 Ty = ArrayTy->getElementType();
351 }
352
353 return std::make_tuple(Subscripts, Sizes);
354}
355
Tobias Grosser75805372011-04-29 06:27:02 +0000356MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000357 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000358 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000359 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000360}
361
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000362static MemoryAccess::AccessType getMemoryAccessType(const IRAccess &Access) {
363 switch (Access.getType()) {
364 case IRAccess::READ:
365 return MemoryAccess::READ;
366 case IRAccess::MUST_WRITE:
367 return MemoryAccess::MUST_WRITE;
368 case IRAccess::MAY_WRITE:
369 return MemoryAccess::MAY_WRITE;
370 }
371 llvm_unreachable("Unknown IRAccess type!");
372}
373
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000374const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
375 isl_id *ArrayId = getArrayId();
376 void *User = isl_id_get_user(ArrayId);
377 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
378 isl_id_free(ArrayId);
379 return SAI;
380}
381
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000382__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000383 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
384}
385
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000386__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
387 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000388 isl_map *Schedule, *ScheduledAccRel;
389 isl_union_set *UDomain;
390
391 UDomain = isl_union_set_from_set(getStatement()->getDomain());
392 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
393 Schedule = isl_map_from_union_map(USchedule);
394 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
395 return isl_pw_multi_aff_from_map(ScheduledAccRel);
396}
397
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000398__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000399 return isl_map_copy(AccessRelation);
400}
401
Johannes Doerferta99130f2014-10-13 12:58:03 +0000402std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000403 return stringFromIslObj(AccessRelation);
404}
405
Johannes Doerferta99130f2014-10-13 12:58:03 +0000406__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000407 return isl_map_get_space(AccessRelation);
408}
409
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000410__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000411 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000412}
413
Tobias Grosser6f730082015-09-05 07:46:47 +0000414std::string MemoryAccess::getNewAccessRelationStr() const {
415 return stringFromIslObj(NewAccessRelation);
416}
417
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000418__isl_give isl_basic_map *
419MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000420 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000421 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000422
Tobias Grosser084d8f72012-05-29 09:29:44 +0000423 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000424 isl_basic_set_universe(Statement->getDomainSpace()),
425 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000426}
427
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000428// Formalize no out-of-bound access assumption
429//
430// When delinearizing array accesses we optimistically assume that the
431// delinearized accesses do not access out of bound locations (the subscript
432// expression of each array evaluates for each statement instance that is
433// executed to a value that is larger than zero and strictly smaller than the
434// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000435// dimension for which we do not need to assume any upper bound. At this point
436// we formalize this assumption to ensure that at code generation time the
437// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000438//
439// To find the set of constraints necessary to avoid out of bound accesses, we
440// first build the set of data locations that are not within array bounds. We
441// then apply the reverse access relation to obtain the set of iterations that
442// may contain invalid accesses and reduce this set of iterations to the ones
443// that are actually executed by intersecting them with the domain of the
444// statement. If we now project out all loop dimensions, we obtain a set of
445// parameters that may cause statement instances to be executed that may
446// possibly yield out of bound memory accesses. The complement of these
447// constraints is the set of constraints that needs to be assumed to ensure such
448// statement instances are never executed.
449void MemoryAccess::assumeNoOutOfBound(const IRAccess &Access) {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000450 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000451 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000452 for (int i = 1, Size = Access.Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000453 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
454 isl_pw_aff *Var =
455 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
456 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
457
458 isl_set *DimOutside;
459
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000460 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfert574182d2015-08-12 10:19:50 +0000461 isl_pw_aff *SizeE = Statement->getPwAff(Access.Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000462
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000463 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
464 Statement->getNumIterators());
465 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
466 isl_space_dim(Space, isl_dim_set));
467 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
468 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000469
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000470 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000471
472 Outside = isl_set_union(Outside, DimOutside);
473 }
474
475 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
476 Outside = isl_set_intersect(Outside, Statement->getDomain());
477 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000478
479 // Remove divs to avoid the construction of overly complicated assumptions.
480 // Doing so increases the set of parameter combinations that are assumed to
481 // not appear. This is always save, but may make the resulting run-time check
482 // bail out more often than strictly necessary.
483 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000484 Outside = isl_set_complement(Outside);
485 Statement->getParent()->addAssumption(Outside);
486 isl_space_free(Space);
487}
488
Johannes Doerferte7044942015-02-24 11:58:30 +0000489void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
490 ScalarEvolution *SE = Statement->getParent()->getSE();
491
492 Value *Ptr = getPointerOperand(*getAccessInstruction());
493 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
494 return;
495
496 auto *PtrSCEV = SE->getSCEV(Ptr);
497 if (isa<SCEVCouldNotCompute>(PtrSCEV))
498 return;
499
500 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
501 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
502 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
503
504 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
505 if (Range.isFullSet())
506 return;
507
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000508 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000509 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000510 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
511 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
512
513 auto Min = LB.sdiv(APInt(BW, ElementSize));
514 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000515
516 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
517 AccessRange =
518 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
519 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
520}
521
Tobias Grosser619190d2015-03-30 17:22:28 +0000522__isl_give isl_map *MemoryAccess::foldAccess(const IRAccess &Access,
523 __isl_take isl_map *AccessRelation,
524 ScopStmt *Statement) {
525 int Size = Access.Subscripts.size();
526
527 for (int i = Size - 2; i >= 0; --i) {
528 isl_space *Space;
529 isl_map *MapOne, *MapTwo;
Johannes Doerfert574182d2015-08-12 10:19:50 +0000530 isl_pw_aff *DimSize = Statement->getPwAff(Access.Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000531
532 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
533 isl_pw_aff_free(DimSize);
534 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
535
536 Space = isl_map_get_space(AccessRelation);
537 Space = isl_space_map_from_set(isl_space_range(Space));
538 Space = isl_space_align_params(Space, SpaceSize);
539
540 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
541 isl_id_free(ParamId);
542
543 MapOne = isl_map_universe(isl_space_copy(Space));
544 for (int j = 0; j < Size; ++j)
545 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
546 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
547
548 MapTwo = isl_map_universe(isl_space_copy(Space));
549 for (int j = 0; j < Size; ++j)
550 if (j < i || j > i + 1)
551 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
552
553 isl_local_space *LS = isl_local_space_from_space(Space);
554 isl_constraint *C;
555 C = isl_equality_alloc(isl_local_space_copy(LS));
556 C = isl_constraint_set_constant_si(C, -1);
557 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
558 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
559 MapTwo = isl_map_add_constraint(MapTwo, C);
560 C = isl_equality_alloc(LS);
561 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
562 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
563 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
564 MapTwo = isl_map_add_constraint(MapTwo, C);
565 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
566
567 MapOne = isl_map_union(MapOne, MapTwo);
568 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
569 }
570 return AccessRelation;
571}
572
Johannes Doerfert13c8cf22014-08-10 08:09:38 +0000573MemoryAccess::MemoryAccess(const IRAccess &Access, Instruction *AccInst,
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000574 ScopStmt *Statement, const ScopArrayInfo *SAI,
575 int Identifier)
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000576 : AccType(getMemoryAccessType(Access)), Statement(Statement),
577 AccessInstruction(AccInst), AccessValue(Access.getAccessValue()),
Tobias Grosser166c4222015-09-05 07:46:40 +0000578 NewAccessRelation(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +0000579
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000580 isl_ctx *Ctx = Statement->getIslCtx();
Tobias Grosser9759f852011-11-10 12:44:55 +0000581 BaseAddr = Access.getBase();
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000582 BaseName = getIslCompatibleName("MemRef_", getBaseAddr(), "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000583
584 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000585
Tobias Grosserac3a95f2015-08-03 17:53:21 +0000586 auto IdName = "__polly_array_ref_" + std::to_string(Identifier);
Tobias Grossere29d31c2015-05-15 12:24:09 +0000587 Id = isl_id_alloc(Ctx, IdName.c_str(), nullptr);
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000588
Tobias Grossera1879642011-12-20 10:43:14 +0000589 if (!Access.isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000590 // We overapproximate non-affine accesses with a possible access to the
591 // whole array. For read accesses it does not make a difference, if an
592 // access must or may happen. However, for write accesses it is important to
593 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000594 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000595 AccessRelation =
596 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000597
598 computeBoundsOnAccessRelation(Access.getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000599 return;
600 }
601
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000602 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000603 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000604
Tobias Grosser79baa212014-04-10 08:38:02 +0000605 for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000606 isl_pw_aff *Affine = Statement->getPwAff(Access.Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000607
Sebastian Pop422e33f2014-06-03 18:16:31 +0000608 if (Size == 1) {
609 // For the non delinearized arrays, divide the access function of the last
610 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000611 //
612 // A stride one array access in C expressed as A[i] is expressed in
613 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
614 // two subsequent values of 'i' index two values that are stored next to
615 // each other in memory. By this division we make this characteristic
616 // obvious again.
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000617 isl_val *v = isl_val_int_from_si(Ctx, Access.getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000618 Affine = isl_pw_aff_scale_down_val(Affine, v);
619 }
620
621 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
622
Tobias Grosser79baa212014-04-10 08:38:02 +0000623 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000624 }
625
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000626 if (Access.Sizes.size() > 1 && !isa<SCEVConstant>(Access.Sizes[0]))
627 AccessRelation = foldAccess(Access, AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000628
Tobias Grosser79baa212014-04-10 08:38:02 +0000629 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000630 AccessRelation = isl_map_set_tuple_id(
631 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000632 AccessRelation =
633 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
634
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000635 assumeNoOutOfBound(Access);
Tobias Grosseraa660a92015-03-30 00:07:50 +0000636 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000637 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000638}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000639
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000640void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000641 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000642 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000643}
644
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000645const std::string MemoryAccess::getReductionOperatorStr() const {
646 return MemoryAccess::getReductionOperatorStr(getReductionType());
647}
648
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000649__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
650
Johannes Doerfertf6183392014-07-01 20:52:51 +0000651raw_ostream &polly::operator<<(raw_ostream &OS,
652 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000653 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000654 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000655 else
656 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000657 return OS;
658}
659
Tobias Grosser75805372011-04-29 06:27:02 +0000660void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000661 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000662 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000663 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000664 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000665 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000666 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000667 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000668 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000669 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000670 break;
671 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000672 OS << "[Reduction Type: " << getReductionType() << "] ";
673 OS << "[Scalar: " << isScalar() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000674 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000675 if (hasNewAccessRelation())
676 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000677}
678
Tobias Grosser74394f02013-01-14 22:40:23 +0000679void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000680
681// Create a map in the size of the provided set domain, that maps from the
682// one element of the provided set domain to another element of the provided
683// set domain.
684// The mapping is limited to all points that are equal in all but the last
685// dimension and for which the last dimension of the input is strict smaller
686// than the last dimension of the output.
687//
688// getEqualAndLarger(set[i0, i1, ..., iX]):
689//
690// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
691// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
692//
Tobias Grosserf5338802011-10-06 00:03:35 +0000693static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000694 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000695 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000696 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000697
698 // Set all but the last dimension to be equal for the input and output
699 //
700 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
701 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000702 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000703 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000704
705 // Set the last dimension of the input to be strict smaller than the
706 // last dimension of the output.
707 //
708 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000709 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
710 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000711 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000712}
713
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000714__isl_give isl_set *
715MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000716 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000717 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000718 isl_space *Space = isl_space_range(isl_map_get_space(S));
719 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000720
Sebastian Popa00a0292012-12-18 07:46:06 +0000721 S = isl_map_reverse(S);
722 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000723
Sebastian Popa00a0292012-12-18 07:46:06 +0000724 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
725 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
726 NextScatt = isl_map_apply_domain(NextScatt, S);
727 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000728
Sebastian Popa00a0292012-12-18 07:46:06 +0000729 isl_set *Deltas = isl_map_deltas(NextScatt);
730 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000731}
732
Sebastian Popa00a0292012-12-18 07:46:06 +0000733bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000734 int StrideWidth) const {
735 isl_set *Stride, *StrideX;
736 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000737
Sebastian Popa00a0292012-12-18 07:46:06 +0000738 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000739 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000740 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
741 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
742 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
743 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000744 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000745
Tobias Grosser28dd4862012-01-24 16:42:16 +0000746 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000747 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000748
Tobias Grosser28dd4862012-01-24 16:42:16 +0000749 return IsStrideX;
750}
751
Sebastian Popa00a0292012-12-18 07:46:06 +0000752bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
753 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000754}
755
Tobias Grosser79baa212014-04-10 08:38:02 +0000756bool MemoryAccess::isScalar() const {
757 return isl_map_n_out(AccessRelation) == 0;
758}
759
Sebastian Popa00a0292012-12-18 07:46:06 +0000760bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
761 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000762}
763
Tobias Grosser166c4222015-09-05 07:46:40 +0000764void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
765 isl_map_free(NewAccessRelation);
766 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000767}
Tobias Grosser75805372011-04-29 06:27:02 +0000768
769//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000770
Tobias Grosser808cd692015-07-14 09:33:13 +0000771isl_map *ScopStmt::getSchedule() const {
772 isl_set *Domain = getDomain();
773 if (isl_set_is_empty(Domain)) {
774 isl_set_free(Domain);
775 return isl_map_from_aff(
776 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
777 }
778 auto *Schedule = getParent()->getSchedule();
779 Schedule = isl_union_map_intersect_domain(
780 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
781 if (isl_union_map_is_empty(Schedule)) {
782 isl_set_free(Domain);
783 isl_union_map_free(Schedule);
784 return isl_map_from_aff(
785 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
786 }
787 auto *M = isl_map_from_union_map(Schedule);
788 M = isl_map_coalesce(M);
789 M = isl_map_gist_domain(M, Domain);
790 M = isl_map_coalesce(M);
791 return M;
792}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000793
Johannes Doerfert574182d2015-08-12 10:19:50 +0000794__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000795 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
796 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000797}
798
Tobias Grosser37eb4222014-02-20 21:43:54 +0000799void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
800 assert(isl_set_is_subset(NewDomain, Domain) &&
801 "New domain is not a subset of old domain!");
802 isl_set_free(Domain);
803 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000804}
805
Michael Kruse9d080092015-09-11 21:41:48 +0000806void ScopStmt::buildAccesses(BasicBlock *Block, bool isApproximated) {
807 AccFuncSetType *AFS = Parent.getAccessFunctions(Block);
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000808 if (!AFS)
809 return;
810
811 for (auto &AccessPair : *AFS) {
812 IRAccess &Access = AccessPair.first;
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000813 Instruction *AccessInst = AccessPair.second;
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000814 Type *ElementType = Access.getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000815
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000816 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Tobias Grosser92245222015-07-28 14:53:44 +0000817 Access.getBase(), ElementType, Access.Sizes, Access.isPHI());
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000818
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000819 if (isApproximated && Access.isWrite())
820 Access.setMayWrite();
821
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000822 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
823 if (!MAL)
824 MAL = new MemoryAccessList();
825 MAL->emplace_front(Access, AccessInst, this, SAI, MemAccs.size());
826 MemAccs.push_back(&MAL->front());
Tobias Grosser75805372011-04-29 06:27:02 +0000827 }
828}
829
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000830void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000831 for (MemoryAccess *MA : *this)
832 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000833
834 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000835}
836
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000837/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
838static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
839 void *User) {
840 isl_set **BoundedParts = static_cast<isl_set **>(User);
841 if (isl_basic_set_is_bounded(BSet))
842 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
843 else
844 isl_basic_set_free(BSet);
845 return isl_stat_ok;
846}
847
848/// @brief Return the bounded parts of @p S.
849static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
850 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
851 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
852 isl_set_free(S);
853 return BoundedParts;
854}
855
856/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
857///
858/// @returns A separation of @p S into first an unbounded then a bounded subset,
859/// both with regards to the dimension @p Dim.
860static std::pair<__isl_give isl_set *, __isl_give isl_set *>
861partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
862
863 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertca1e38f2015-09-14 11:12:52 +0000864 S = isl_set_lower_bound_si(S, isl_dim_set, u, u == Dim ? -1 : 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000865
866 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertca1e38f2015-09-14 11:12:52 +0000867 isl_set *OnlyDimS = S;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000868
869 // Remove dimensions that are greater than Dim as they are not interesting.
870 assert(NumDimsS >= Dim + 1);
871 OnlyDimS =
872 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
873
874 // Create artificial parametric upper bounds for dimensions smaller than Dim
875 // as we are not interested in them.
876 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
877 for (unsigned u = 0; u < Dim; u++) {
878 isl_constraint *C = isl_inequality_alloc(
879 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
880 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
881 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
882 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
883 }
884
885 // Collect all bounded parts of OnlyDimS.
886 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
887
888 // Create the dimensions greater than Dim again.
889 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
890 NumDimsS - Dim - 1);
891
892 // Remove the artificial upper bound parameters again.
893 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
894
Johannes Doerfertca1e38f2015-09-14 11:12:52 +0000895 isl_set *UnboundedParts = isl_set_complement(isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000896 return std::make_pair(UnboundedParts, BoundedParts);
897}
898
Johannes Doerfert96425c22015-08-30 21:13:53 +0000899static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
900 isl_pw_aff *L, isl_pw_aff *R) {
901 switch (Pred) {
902 case ICmpInst::ICMP_EQ:
903 return isl_pw_aff_eq_set(L, R);
904 case ICmpInst::ICMP_NE:
905 return isl_pw_aff_ne_set(L, R);
906 case ICmpInst::ICMP_SLT:
907 return isl_pw_aff_lt_set(L, R);
908 case ICmpInst::ICMP_SLE:
909 return isl_pw_aff_le_set(L, R);
910 case ICmpInst::ICMP_SGT:
911 return isl_pw_aff_gt_set(L, R);
912 case ICmpInst::ICMP_SGE:
913 return isl_pw_aff_ge_set(L, R);
914 case ICmpInst::ICMP_ULT:
915 return isl_pw_aff_lt_set(L, R);
916 case ICmpInst::ICMP_UGT:
917 return isl_pw_aff_gt_set(L, R);
918 case ICmpInst::ICMP_ULE:
919 return isl_pw_aff_le_set(L, R);
920 case ICmpInst::ICMP_UGE:
921 return isl_pw_aff_ge_set(L, R);
922 default:
923 llvm_unreachable("Non integer predicate not supported");
924 }
925}
926
927/// @brief Build the conditions sets for the branch @p BI in the @p Domain.
928///
929/// This will fill @p ConditionSets with the conditions under which control
930/// will be moved from @p BI to its successors. Hence, @p ConditionSets will
931/// have as many elements as @p BI has successors.
932static void
933buildConditionSets(Scop &S, BranchInst *BI, Loop *L, __isl_keep isl_set *Domain,
934 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
935
936 if (BI->isUnconditional()) {
937 ConditionSets.push_back(isl_set_copy(Domain));
938 return;
939 }
940
941 Value *Condition = BI->getCondition();
942
943 isl_set *ConsequenceCondSet = nullptr;
944 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
945 if (CCond->isZero())
946 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
947 else
948 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
949 } else {
950 auto *ICond = dyn_cast<ICmpInst>(Condition);
951 assert(ICond &&
952 "Condition of exiting branch was neither constant nor ICmp!");
953
954 ScalarEvolution &SE = *S.getSE();
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000955 BasicBlock *BB = BI->getParent();
Johannes Doerfert96425c22015-08-30 21:13:53 +0000956 isl_pw_aff *LHS, *RHS;
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000957 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
958 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
Johannes Doerfert96425c22015-08-30 21:13:53 +0000959 ConsequenceCondSet = buildConditionSet(ICond->getPredicate(), LHS, RHS);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000960
961 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
962 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
963 ConsequenceCondSet =
964 isl_set_set_dim_id(ConsequenceCondSet, isl_dim_set, u, DimId);
965 }
Johannes Doerfert96425c22015-08-30 21:13:53 +0000966 }
967
968 assert(ConsequenceCondSet);
969 isl_set *AlternativeCondSet =
970 isl_set_complement(isl_set_copy(ConsequenceCondSet));
971
972 ConditionSets.push_back(isl_set_coalesce(
973 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
974 ConditionSets.push_back(isl_set_coalesce(
975 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
976}
977
Johannes Doerfert32ae76e2015-09-10 13:12:02 +0000978void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000979 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000980
Tobias Grosser084d8f72012-05-29 09:29:44 +0000981 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
982
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000983 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +0000984 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +0000985}
986
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000987void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
988 int Dimension = 0;
989 isl_ctx *Ctx = Parent.getIslCtx();
990 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
991 Type *Ty = GEP->getPointerOperandType();
992 ScalarEvolution &SE = *Parent.getSE();
993
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000994 std::vector<const SCEV *> Subscripts;
995 std::vector<int> Sizes;
996
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000997 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000998
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000999 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
1000 Dimension = 1;
1001 Ty = PtrTy->getElementType();
1002 }
1003
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001004 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001005
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001006 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001007
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001008 for (size_t i = 0; i < Sizes.size(); i++) {
1009 auto Expr = Subscripts[i + IndexOffset];
1010 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001011
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001012 if (!isAffineExpr(&Parent.getRegion(), Expr, SE))
1013 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001014
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001015 isl_pw_aff *AccessOffset = getPwAff(Expr);
1016 AccessOffset =
1017 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001018
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001019 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1020 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001021
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001022 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1023 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1024 OutOfBound = isl_set_params(OutOfBound);
1025 isl_set *InBound = isl_set_complement(OutOfBound);
1026 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001027
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001028 // A => B == !A or B
1029 isl_set *InBoundIfExecuted =
1030 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001031
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001032 Parent.addAssumption(InBoundIfExecuted);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001033 }
1034
1035 isl_local_space_free(LSpace);
1036}
1037
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001038void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1039 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001040 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1041 deriveAssumptionsFromGEP(GEP);
1042}
1043
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001044void ScopStmt::collectSurroundingLoops() {
1045 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1046 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1047 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1048 isl_id_free(DimId);
1049 }
1050}
1051
Michael Kruse9d080092015-09-11 21:41:48 +00001052ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001053 : Parent(parent), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001054
Tobias Grosser16c44032015-07-09 07:31:45 +00001055 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001056
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001057 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001058 collectSurroundingLoops();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001059
1060 BasicBlock *EntryBB = R.getEntry();
1061 for (BasicBlock *Block : R.blocks()) {
Michael Kruse9d080092015-09-11 21:41:48 +00001062 buildAccesses(Block, Block != EntryBB);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001063 deriveAssumptions(Block);
1064 }
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001065 if (DetectReductions)
1066 checkForReductions();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001067}
1068
Michael Kruse9d080092015-09-11 21:41:48 +00001069ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001070 : Parent(parent), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001071
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001072 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +00001073
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001074 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001075 collectSurroundingLoops();
Michael Kruse9d080092015-09-11 21:41:48 +00001076 buildAccesses(BB);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001077 deriveAssumptions(BB);
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001078 if (DetectReductions)
1079 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001080}
1081
Johannes Doerferte58a0122014-06-27 20:31:28 +00001082/// @brief Collect loads which might form a reduction chain with @p StoreMA
1083///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001084/// Check if the stored value for @p StoreMA is a binary operator with one or
1085/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001086/// used only once (by @p StoreMA) and its load operands are also used only
1087/// once, we have found a possible reduction chain. It starts at an operand
1088/// load and includes the binary operator and @p StoreMA.
1089///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001090/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001091/// escape this block or into any other store except @p StoreMA.
1092void ScopStmt::collectCandiateReductionLoads(
1093 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1094 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1095 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001096 return;
1097
1098 // Skip if there is not one binary operator between the load and the store
1099 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001100 if (!BinOp)
1101 return;
1102
1103 // Skip if the binary operators has multiple uses
1104 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001105 return;
1106
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001107 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001108 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1109 return;
1110
Johannes Doerfert9890a052014-07-01 00:32:29 +00001111 // Skip if the binary operator is outside the current SCoP
1112 if (BinOp->getParent() != Store->getParent())
1113 return;
1114
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001115 // Skip if it is a multiplicative reduction and we disabled them
1116 if (DisableMultiplicativeReductions &&
1117 (BinOp->getOpcode() == Instruction::Mul ||
1118 BinOp->getOpcode() == Instruction::FMul))
1119 return;
1120
Johannes Doerferte58a0122014-06-27 20:31:28 +00001121 // Check the binary operator operands for a candidate load
1122 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1123 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1124 if (!PossibleLoad0 && !PossibleLoad1)
1125 return;
1126
1127 // A load is only a candidate if it cannot escape (thus has only this use)
1128 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001129 if (PossibleLoad0->getParent() == Store->getParent())
1130 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001131 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001132 if (PossibleLoad1->getParent() == Store->getParent())
1133 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001134}
1135
1136/// @brief Check for reductions in this ScopStmt
1137///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001138/// Iterate over all store memory accesses and check for valid binary reduction
1139/// like chains. For all candidates we check if they have the same base address
1140/// and there are no other accesses which overlap with them. The base address
1141/// check rules out impossible reductions candidates early. The overlap check,
1142/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001143/// guarantees that none of the intermediate results will escape during
1144/// execution of the loop nest. We basically check here that no other memory
1145/// access can access the same memory as the potential reduction.
1146void ScopStmt::checkForReductions() {
1147 SmallVector<MemoryAccess *, 2> Loads;
1148 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1149
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001150 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001151 // stores and collecting possible reduction loads.
1152 for (MemoryAccess *StoreMA : MemAccs) {
1153 if (StoreMA->isRead())
1154 continue;
1155
1156 Loads.clear();
1157 collectCandiateReductionLoads(StoreMA, Loads);
1158 for (MemoryAccess *LoadMA : Loads)
1159 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1160 }
1161
1162 // Then check each possible candidate pair.
1163 for (const auto &CandidatePair : Candidates) {
1164 bool Valid = true;
1165 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1166 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1167
1168 // Skip those with obviously unequal base addresses.
1169 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1170 isl_map_free(LoadAccs);
1171 isl_map_free(StoreAccs);
1172 continue;
1173 }
1174
1175 // And check if the remaining for overlap with other memory accesses.
1176 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1177 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1178 isl_set *AllAccs = isl_map_range(AllAccsRel);
1179
1180 for (MemoryAccess *MA : MemAccs) {
1181 if (MA == CandidatePair.first || MA == CandidatePair.second)
1182 continue;
1183
1184 isl_map *AccRel =
1185 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1186 isl_set *Accs = isl_map_range(AccRel);
1187
1188 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1189 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1190 Valid = Valid && isl_set_is_empty(OverlapAccs);
1191 isl_set_free(OverlapAccs);
1192 }
1193 }
1194
1195 isl_set_free(AllAccs);
1196 if (!Valid)
1197 continue;
1198
Johannes Doerfertf6183392014-07-01 20:52:51 +00001199 const LoadInst *Load =
1200 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1201 MemoryAccess::ReductionType RT =
1202 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1203
Johannes Doerferte58a0122014-06-27 20:31:28 +00001204 // If no overlapping access was found we mark the load and store as
1205 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001206 CandidatePair.first->markAsReductionLike(RT);
1207 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001208 }
Tobias Grosser75805372011-04-29 06:27:02 +00001209}
1210
Tobias Grosser74394f02013-01-14 22:40:23 +00001211std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001212
Tobias Grosser54839312015-04-21 11:37:25 +00001213std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001214 auto *S = getSchedule();
1215 auto Str = stringFromIslObj(S);
1216 isl_map_free(S);
1217 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001218}
1219
Tobias Grosser74394f02013-01-14 22:40:23 +00001220unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001221
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001222unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001223
Tobias Grosser75805372011-04-29 06:27:02 +00001224const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1225
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001226const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001227 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001228}
1229
Tobias Grosser74394f02013-01-14 22:40:23 +00001230isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001231
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001232__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001233
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001234__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001235 return isl_set_get_space(Domain);
1236}
1237
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001238__isl_give isl_id *ScopStmt::getDomainId() const {
1239 return isl_set_get_tuple_id(Domain);
1240}
Tobias Grossercd95b772012-08-30 11:49:38 +00001241
Tobias Grosser75805372011-04-29 06:27:02 +00001242ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001243 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001244 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001245}
1246
1247void ScopStmt::print(raw_ostream &OS) const {
1248 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001249 OS.indent(12) << "Domain :=\n";
1250
1251 if (Domain) {
1252 OS.indent(16) << getDomainStr() << ";\n";
1253 } else
1254 OS.indent(16) << "n/a\n";
1255
Tobias Grosser54839312015-04-21 11:37:25 +00001256 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001257
1258 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001259 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001260 } else
1261 OS.indent(16) << "n/a\n";
1262
Tobias Grosser083d3d32014-06-28 08:59:45 +00001263 for (MemoryAccess *Access : MemAccs)
1264 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001265}
1266
1267void ScopStmt::dump() const { print(dbgs()); }
1268
1269//===----------------------------------------------------------------------===//
1270/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001271
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001272void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001273 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1274 isl_set_free(Context);
1275 Context = NewContext;
1276}
1277
Tobias Grosserabfbe632013-02-05 12:09:06 +00001278void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001279 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001280 Parameter = extractConstantFactor(Parameter, *SE).second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001281 if (ParameterIds.find(Parameter) != ParameterIds.end())
1282 continue;
1283
1284 int dimension = Parameters.size();
1285
1286 Parameters.push_back(Parameter);
1287 ParameterIds[Parameter] = dimension;
1288 }
1289}
1290
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001291__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1292 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001293
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001294 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001295 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001296
Tobias Grosser8f99c162011-11-15 11:38:55 +00001297 std::string ParameterName;
1298
1299 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1300 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001301 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001302 }
1303
1304 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001305 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001306
Tobias Grosser20532b82014-04-11 17:56:49 +00001307 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1308 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001309}
Tobias Grosser75805372011-04-29 06:27:02 +00001310
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001311isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1312 isl_set *DomainContext = isl_union_set_params(getDomains());
1313 return isl_set_intersect_params(C, DomainContext);
1314}
1315
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001316void Scop::buildBoundaryContext() {
1317 BoundaryContext = Affinator.getWrappingContext();
1318 BoundaryContext = isl_set_complement(BoundaryContext);
1319 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
1320}
1321
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001322void Scop::addUserContext() {
1323 if (UserContextStr.empty())
1324 return;
1325
1326 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1327 isl_space *Space = getParamSpace();
1328 if (isl_space_dim(Space, isl_dim_param) !=
1329 isl_set_dim(UserContext, isl_dim_param)) {
1330 auto SpaceStr = isl_space_to_str(Space);
1331 errs() << "Error: the context provided in -polly-context has not the same "
1332 << "number of dimensions than the computed context. Due to this "
1333 << "mismatch, the -polly-context option is ignored. Please provide "
1334 << "the context in the parameter space: " << SpaceStr << ".\n";
1335 free(SpaceStr);
1336 isl_set_free(UserContext);
1337 isl_space_free(Space);
1338 return;
1339 }
1340
1341 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1342 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1343 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1344
1345 if (strcmp(NameContext, NameUserContext) != 0) {
1346 auto SpaceStr = isl_space_to_str(Space);
1347 errs() << "Error: the name of dimension " << i
1348 << " provided in -polly-context "
1349 << "is '" << NameUserContext << "', but the name in the computed "
1350 << "context is '" << NameContext
1351 << "'. Due to this name mismatch, "
1352 << "the -polly-context option is ignored. Please provide "
1353 << "the context in the parameter space: " << SpaceStr << ".\n";
1354 free(SpaceStr);
1355 isl_set_free(UserContext);
1356 isl_space_free(Space);
1357 return;
1358 }
1359
1360 UserContext =
1361 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1362 isl_space_get_dim_id(Space, isl_dim_param, i));
1363 }
1364
1365 Context = isl_set_intersect(Context, UserContext);
1366 isl_space_free(Space);
1367}
1368
Tobias Grosser6be480c2011-11-08 15:41:13 +00001369void Scop::buildContext() {
1370 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001371 Context = isl_set_universe(isl_space_copy(Space));
1372 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001373}
1374
Tobias Grosser18daaca2012-05-22 10:47:27 +00001375void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001376 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001377 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001378
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001379 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001380
Johannes Doerferte7044942015-02-24 11:58:30 +00001381 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001382 }
1383}
1384
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001385void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001386 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001387 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001388
Tobias Grosser083d3d32014-06-28 08:59:45 +00001389 for (const auto &ParamID : ParameterIds) {
1390 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001391 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001392 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001393 }
1394
1395 // Align the parameters of all data structures to the model.
1396 Context = isl_set_align_params(Context, Space);
1397
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001398 for (ScopStmt &Stmt : *this)
1399 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001400}
1401
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001402static __isl_give isl_set *
1403simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1404 const Scop &S) {
1405 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1406 AssumptionContext = isl_set_gist_params(AssumptionContext, DomainParameters);
1407 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1408 return AssumptionContext;
1409}
1410
1411void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001412 // The parameter constraints of the iteration domains give us a set of
1413 // constraints that need to hold for all cases where at least a single
1414 // statement iteration is executed in the whole scop. We now simplify the
1415 // assumed context under the assumption that such constraints hold and at
1416 // least a single statement iteration is executed. For cases where no
1417 // statement instances are executed, the assumptions we have taken about
1418 // the executed code do not matter and can be changed.
1419 //
1420 // WARNING: This only holds if the assumptions we have taken do not reduce
1421 // the set of statement instances that are executed. Otherwise we
1422 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001423 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001424 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001425 // performed. In such a case, modifying the run-time conditions and
1426 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001427 // to not be executed.
1428 //
1429 // Example:
1430 //
1431 // When delinearizing the following code:
1432 //
1433 // for (long i = 0; i < 100; i++)
1434 // for (long j = 0; j < m; j++)
1435 // A[i+p][j] = 1.0;
1436 //
1437 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001438 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001439 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001440 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1441 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001442}
1443
Johannes Doerfertb164c792014-09-18 11:17:17 +00001444/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001445static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001446 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1447 isl_pw_multi_aff *MinPMA, *MaxPMA;
1448 isl_pw_aff *LastDimAff;
1449 isl_aff *OneAff;
1450 unsigned Pos;
1451
Johannes Doerfert9143d672014-09-27 11:02:39 +00001452 // Restrict the number of parameters involved in the access as the lexmin/
1453 // lexmax computation will take too long if this number is high.
1454 //
1455 // Experiments with a simple test case using an i7 4800MQ:
1456 //
1457 // #Parameters involved | Time (in sec)
1458 // 6 | 0.01
1459 // 7 | 0.04
1460 // 8 | 0.12
1461 // 9 | 0.40
1462 // 10 | 1.54
1463 // 11 | 6.78
1464 // 12 | 30.38
1465 //
1466 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1467 unsigned InvolvedParams = 0;
1468 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1469 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1470 InvolvedParams++;
1471
1472 if (InvolvedParams > RunTimeChecksMaxParameters) {
1473 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001474 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001475 }
1476 }
1477
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001478 Set = isl_set_remove_divs(Set);
1479
Johannes Doerfertb164c792014-09-18 11:17:17 +00001480 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1481 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1482
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001483 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1484 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1485
Johannes Doerfertb164c792014-09-18 11:17:17 +00001486 // Adjust the last dimension of the maximal access by one as we want to
1487 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1488 // we test during code generation might now point after the end of the
1489 // allocated array but we will never dereference it anyway.
1490 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1491 "Assumed at least one output dimension");
1492 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1493 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1494 OneAff = isl_aff_zero_on_domain(
1495 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1496 OneAff = isl_aff_add_constant_si(OneAff, 1);
1497 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1498 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1499
1500 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1501
1502 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001503 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001504}
1505
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001506static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1507 isl_set *Domain = MA->getStatement()->getDomain();
1508 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1509 return isl_set_reset_tuple_id(Domain);
1510}
1511
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001512/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1513static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001514 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001515 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001516
1517 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1518 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001519 Locations = isl_union_set_coalesce(Locations);
1520 Locations = isl_union_set_detect_equalities(Locations);
1521 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001522 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001523 isl_union_set_free(Locations);
1524 return Valid;
1525}
1526
Johannes Doerfert96425c22015-08-30 21:13:53 +00001527/// @brief Helper to treat non-affine regions and basic blocks the same.
1528///
1529///{
1530
1531/// @brief Return the block that is the representing block for @p RN.
1532static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1533 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1534 : RN->getNodeAs<BasicBlock>();
1535}
1536
1537/// @brief Return the @p idx'th block that is executed after @p RN.
1538static inline BasicBlock *getRegionNodeSuccessor(RegionNode *RN, BranchInst *BI,
1539 unsigned idx) {
1540 if (RN->isSubRegion()) {
1541 assert(idx == 0);
1542 return RN->getNodeAs<Region>()->getExit();
1543 }
1544 return BI->getSuccessor(idx);
1545}
1546
1547/// @brief Return the smallest loop surrounding @p RN.
1548static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1549 if (!RN->isSubRegion())
1550 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1551
1552 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1553 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1554 while (L && NonAffineSubRegion->contains(L))
1555 L = L->getParentLoop();
1556 return L;
1557}
1558
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001559static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1560 if (!RN->isSubRegion())
1561 return 1;
1562
1563 unsigned NumBlocks = 0;
1564 Region *R = RN->getNodeAs<Region>();
1565 for (auto BB : R->blocks()) {
1566 (void)BB;
1567 NumBlocks++;
1568 }
1569 return NumBlocks;
1570}
1571
Johannes Doerfert96425c22015-08-30 21:13:53 +00001572///}
1573
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001574static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1575 unsigned Dim, Loop *L) {
1576 isl_id *DimId =
1577 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
1578 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
1579}
1580
Johannes Doerfert96425c22015-08-30 21:13:53 +00001581isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1582 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1583 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00001584 return getDomainConditions(BB);
1585}
1586
1587isl_set *Scop::getDomainConditions(BasicBlock *BB) {
1588 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001589 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001590}
1591
1592void Scop::buildDomains(Region *R, LoopInfo &LI, ScopDetection &SD,
1593 DominatorTree &DT) {
1594
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001595 auto *EntryBB = R->getEntry();
1596 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
1597 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001598
1599 Loop *L = LI.getLoopFor(EntryBB);
1600 while (LD-- >= 0) {
1601 S = addDomainDimId(S, LD + 1, L);
1602 L = L->getParentLoop();
1603 }
1604
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001605 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001606
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00001607 if (SD.isNonAffineSubRegion(R, R))
1608 return;
1609
Johannes Doerfert96425c22015-08-30 21:13:53 +00001610 buildDomainsWithBranchConstraints(R, LI, SD, DT);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001611 addLoopBoundsToHeaderDomains(LI, SD, DT);
1612 propagateDomainConstraints(R, LI, SD, DT);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001613}
1614
1615void Scop::buildDomainsWithBranchConstraints(Region *R, LoopInfo &LI,
1616 ScopDetection &SD,
1617 DominatorTree &DT) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001618 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00001619
1620 // To create the domain for each block in R we iterate over all blocks and
1621 // subregions in R and propagate the conditions under which the current region
1622 // element is executed. To this end we iterate in reverse post order over R as
1623 // it ensures that we first visit all predecessors of a region node (either a
1624 // basic block or a subregion) before we visit the region node itself.
1625 // Initially, only the domain for the SCoP region entry block is set and from
1626 // there we propagate the current domain to all successors, however we add the
1627 // condition that the successor is actually executed next.
1628 // As we are only interested in non-loop carried constraints here we can
1629 // simply skip loop back edges.
1630
1631 ReversePostOrderTraversal<Region *> RTraversal(R);
1632 for (auto *RN : RTraversal) {
1633
1634 // Recurse for affine subregions but go on for basic blocks and non-affine
1635 // subregions.
1636 if (RN->isSubRegion()) {
1637 Region *SubRegion = RN->getNodeAs<Region>();
1638 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
1639 buildDomainsWithBranchConstraints(SubRegion, LI, SD, DT);
1640 continue;
1641 }
1642 }
1643
1644 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001645 TerminatorInst *TI = BB->getTerminator();
1646
1647 // Unreachable instructions do not have successors so we can skip them.
1648 if (isa<UnreachableInst>(TI)) {
1649 // Assume unreachables only in error blocks.
1650 assert(isErrorBlock(*BB));
1651 continue;
1652 }
1653
Johannes Doerfert96425c22015-08-30 21:13:53 +00001654 isl_set *Domain = DomainMap[BB];
1655 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
1656 assert(Domain && "Due to reverse post order traversal of the region all "
1657 "predecessor of the current region node should have been "
1658 "visited and a domain for this region node should have "
1659 "been set.");
1660
1661 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1662 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1663
1664 // Build the condition sets for the successor nodes of the current region
1665 // node. If it is a non-affine subregion we will always execute the single
1666 // exit node, hence the single entry node domain is the condition set. For
1667 // basic blocks we use the helper function buildConditionSets.
1668 SmallVector<isl_set *, 2> ConditionSets;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001669 BranchInst *BI = cast<BranchInst>(TI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001670 if (RN->isSubRegion())
1671 ConditionSets.push_back(isl_set_copy(Domain));
1672 else
1673 buildConditionSets(*this, BI, BBLoop, Domain, ConditionSets);
1674
1675 // Now iterate over the successors and set their initial domain based on
1676 // their condition set. We skip back edges here and have to be careful when
1677 // we leave a loop not to keep constraints over a dimension that doesn't
1678 // exist anymore.
1679 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
1680 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, BI, u);
1681 isl_set *CondSet = ConditionSets[u];
1682
1683 // Skip back edges.
1684 if (DT.dominates(SuccBB, BB)) {
1685 isl_set_free(CondSet);
1686 continue;
1687 }
1688
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001689 // Do not adjust the number of dimensions if we enter a boxed loop or are
1690 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001691 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001692 Region *SuccRegion = RI.getRegionFor(SuccBB);
1693 if (BBLoop != SuccBBLoop && !RN->isSubRegion() &&
1694 !(SD.isNonAffineSubRegion(SuccRegion, &getRegion()) &&
1695 SuccRegion->contains(SuccBBLoop))) {
1696
1697 // Check if the edge to SuccBB is a loop entry or exit edge. If so
1698 // adjust the dimensionality accordingly. Lastly, if we leave a loop
1699 // and enter a new one we need to drop the old constraints.
1700 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001701 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001702 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001703 CondSet = isl_set_project_out(CondSet, isl_dim_set,
1704 isl_set_n_dim(CondSet) - LoopDepthDiff,
1705 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001706 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001707 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001708 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001709 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001710 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001711 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001712 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
1713 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001714 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001715 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00001716 }
1717
1718 // Set the domain for the successor or merge it with an existing domain in
1719 // case there are multiple paths (without loop back edges) to the
1720 // successor block.
1721 isl_set *&SuccDomain = DomainMap[SuccBB];
1722 if (!SuccDomain)
1723 SuccDomain = CondSet;
1724 else
1725 SuccDomain = isl_set_union(SuccDomain, CondSet);
1726
1727 SuccDomain = isl_set_coalesce(SuccDomain);
1728 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : " << Domain
1729 << "\n");
1730 }
1731 }
1732}
1733
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001734/// @brief Return the domain for @p BB wrt @p DomainMap.
1735///
1736/// This helper function will lookup @p BB in @p DomainMap but also handle the
1737/// case where @p BB is contained in a non-affine subregion using the region
1738/// tree obtained by @p RI.
1739static __isl_give isl_set *
1740getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
1741 RegionInfo &RI) {
1742 auto DIt = DomainMap.find(BB);
1743 if (DIt != DomainMap.end())
1744 return isl_set_copy(DIt->getSecond());
1745
1746 Region *R = RI.getRegionFor(BB);
1747 while (R->getEntry() == BB)
1748 R = R->getParent();
1749 return getDomainForBlock(R->getEntry(), DomainMap, RI);
1750}
1751
Johannes Doerferte114dc02015-09-14 11:15:58 +00001752static bool containsErrorBlock(RegionNode *RN) {
1753 if (!RN->isSubRegion())
1754 return isErrorBlock(*RN->getNodeAs<BasicBlock>());
1755 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
1756 if (isErrorBlock(*BB))
1757 return true;
1758 return false;
1759}
1760
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001761void Scop::propagateDomainConstraints(Region *R, LoopInfo &LI,
1762 ScopDetection &SD, DominatorTree &DT) {
1763 // Iterate over the region R and propagate the domain constrains from the
1764 // predecessors to the current node. In contrast to the
1765 // buildDomainsWithBranchConstraints function, this one will pull the domain
1766 // information from the predecessors instead of pushing it to the successors.
1767 // Additionally, we assume the domains to be already present in the domain
1768 // map here. However, we iterate again in reverse post order so we know all
1769 // predecessors have been visited before a block or non-affine subregion is
1770 // visited.
1771
1772 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
1773 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
1774
1775 ReversePostOrderTraversal<Region *> RTraversal(R);
1776 for (auto *RN : RTraversal) {
1777
1778 // Recurse for affine subregions but go on for basic blocks and non-affine
1779 // subregions.
1780 if (RN->isSubRegion()) {
1781 Region *SubRegion = RN->getNodeAs<Region>();
1782 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
1783 propagateDomainConstraints(SubRegion, LI, SD, DT);
1784 continue;
1785 }
1786 }
1787
1788 BasicBlock *BB = getRegionNodeBasicBlock(RN);
1789 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1790 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1791
1792 isl_set *&Domain = DomainMap[BB];
1793 assert(Domain && "Due to reverse post order traversal of the region all "
1794 "predecessor of the current region node should have been "
1795 "visited and a domain for this region node should have "
1796 "been set.");
1797
1798 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
1799 for (auto *PredBB : predecessors(BB)) {
1800
1801 // Skip backedges
1802 if (DT.dominates(BB, PredBB))
1803 continue;
1804
1805 isl_set *PredBBDom = nullptr;
1806
1807 // Handle the SCoP entry block with its outside predecessors.
1808 if (!getRegion().contains(PredBB))
1809 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
1810
1811 if (!PredBBDom) {
1812 // Determine the loop depth of the predecessor and adjust its domain to
1813 // the domain of the current block. This can mean we have to:
1814 // o) Drop a dimension if this block is the exit of a loop, not the
1815 // header of a new loop and the predecessor was part of the loop.
1816 // o) Add an unconstrainted new dimension if this block is the header
1817 // of a loop and the predecessor is not part of it.
1818 // o) Drop the information about the innermost loop dimension when the
1819 // predecessor and the current block are surrounded by different
1820 // loops in the same depth.
1821 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
1822 Loop *PredBBLoop = LI.getLoopFor(PredBB);
1823 while (BoxedLoops.count(PredBBLoop))
1824 PredBBLoop = PredBBLoop->getParentLoop();
1825
1826 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001827 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001828 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001829 PredBBDom = isl_set_project_out(
1830 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
1831 LoopDepthDiff);
1832 else if (PredBBLoopDepth < BBLoopDepth) {
1833 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001834 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001835 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
1836 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001837 PredBBDom = isl_set_drop_constraints_involving_dims(
1838 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001839 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001840 }
1841
1842 PredDom = isl_set_union(PredDom, PredBBDom);
1843 }
1844
1845 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00001846 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001847
1848 // Add assumptions for error blocks.
Johannes Doerferte114dc02015-09-14 11:15:58 +00001849 if (containsErrorBlock(RN)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001850 IsOptimized = true;
1851 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
1852 addAssumption(isl_set_complement(DomPar));
1853 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001854 }
1855}
1856
1857/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
1858/// is incremented by one and all other dimensions are equal, e.g.,
1859/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
1860/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
1861static __isl_give isl_map *
1862createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
1863 auto *MapSpace = isl_space_map_from_set(SetSpace);
1864 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
1865 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
1866 if (u != Dim)
1867 NextIterationMap =
1868 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
1869 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
1870 C = isl_constraint_set_constant_si(C, 1);
1871 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
1872 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
1873 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
1874 return NextIterationMap;
1875}
1876
1877/// @brief Add @p L & all children to @p Loops if they are not in @p BoxedLoops.
1878static inline void
1879addLoopAndSubloops(Loop *L, SmallVectorImpl<Loop *> &Loops,
1880 const ScopDetection::BoxedLoopsSetTy &BoxedLoops) {
1881 if (BoxedLoops.count(L))
1882 return;
1883
1884 Loops.push_back(L);
1885 for (Loop *Subloop : *L)
1886 addLoopAndSubloops(Subloop, Loops, BoxedLoops);
1887}
1888
1889/// @brief Add loops in @p R to @p RegionLoops if they are not in @p BoxedLoops.
1890static inline void
1891collectLoopsInRegion(Region &R, LoopInfo &LI,
1892 SmallVector<Loop *, 8> &RegionLoops,
1893 const ScopDetection::BoxedLoopsSetTy &BoxedLoops) {
1894
1895 SmallVector<Loop *, 8> Loops(LI.begin(), LI.end());
1896 while (!Loops.empty()) {
1897 Loop *L = Loops.pop_back_val();
1898
1899 if (R.contains(L))
1900 addLoopAndSubloops(L, RegionLoops, BoxedLoops);
1901 else if (L->contains(R.getEntry()))
1902 Loops.append(L->begin(), L->end());
1903 }
1904}
1905
1906/// @brief Create a set from @p Space with @p Dim fixed to 0.
1907static __isl_give isl_set *
1908createFirstIterationDomain(__isl_take isl_space *Space, unsigned Dim) {
1909 auto *Domain = isl_set_universe(Space);
1910 Domain = isl_set_fix_si(Domain, isl_dim_set, Dim, 0);
1911 return Domain;
1912}
1913
1914void Scop::addLoopBoundsToHeaderDomains(LoopInfo &LI, ScopDetection &SD,
1915 DominatorTree &DT) {
1916 // We iterate over all loops in the SCoP, create the condition set under which
1917 // we will take the back edge, and then apply these restrictions to the
1918 // header.
1919
1920 Region &R = getRegion();
1921 SmallVector<Loop *, 8> RegionLoops;
1922 collectLoopsInRegion(R, LI, RegionLoops, *SD.getBoxedLoops(&R));
1923
1924 while (!RegionLoops.empty()) {
1925 Loop *L = RegionLoops.pop_back_val();
1926 int LoopDepth = getRelativeLoopDepth(L);
1927 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
1928
1929 BasicBlock *LatchBB = L->getLoopLatch();
1930 assert(LatchBB && "TODO implement multiple exit loop handling");
1931
1932 isl_set *LatchBBDom = DomainMap[LatchBB];
1933 isl_set *BackedgeCondition = nullptr;
1934
1935 BasicBlock *HeaderBB = L->getHeader();
1936
1937 BranchInst *BI = cast<BranchInst>(LatchBB->getTerminator());
1938 if (BI->isUnconditional())
1939 BackedgeCondition = isl_set_copy(LatchBBDom);
1940 else {
1941 SmallVector<isl_set *, 2> ConditionSets;
1942 int idx = BI->getSuccessor(0) != HeaderBB;
1943 buildConditionSets(*this, BI, L, LatchBBDom, ConditionSets);
1944
1945 // Free the non back edge condition set as we do not need it.
1946 isl_set_free(ConditionSets[1 - idx]);
1947
1948 BackedgeCondition = ConditionSets[idx];
1949 }
1950
1951 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
1952 isl_set *FirstIteration =
1953 createFirstIterationDomain(isl_set_get_space(HeaderBBDom), LoopDepth);
1954
1955 isl_map *NextIterationMap =
1956 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
1957
1958 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
1959 assert(LatchLoopDepth >= LoopDepth);
1960 BackedgeCondition =
1961 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
1962 LatchLoopDepth - LoopDepth);
1963
Johannes Doerfertca1e38f2015-09-14 11:12:52 +00001964 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
1965 for (int i = 0; i < LoopDepth; i++)
1966 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
1967
1968 isl_set *BackedgeConditionComplement =
1969 isl_set_complement(BackedgeCondition);
1970 BackedgeConditionComplement = isl_set_lower_bound_si(
1971 BackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
1972 BackedgeConditionComplement =
1973 isl_set_apply(BackedgeConditionComplement, ForwardMap);
1974 HeaderBBDom = isl_set_subtract(HeaderBBDom, BackedgeConditionComplement);
1975
1976 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001977
1978 // If a loop has an unbounded back edge condition part (here Parts.first)
1979 // we do not want to assume the header will even be executed for the first
1980 // iteration of an execution that will lead to an infinite loop. While it
1981 // would not be wrong to do so, it does not seem helpful.
Johannes Doerfertca1e38f2015-09-14 11:12:52 +00001982 // TODO: Use the unbounded part to build runtime assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001983 FirstIteration = isl_set_subtract(FirstIteration, Parts.first);
1984
Johannes Doerfertca1e38f2015-09-14 11:12:52 +00001985 HeaderBBDom = isl_set_apply(Parts.second, NextIterationMap);
1986 HeaderBBDom = isl_set_coalesce(isl_set_union(HeaderBBDom, FirstIteration));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001987 }
1988}
1989
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001990void Scop::buildAliasChecks(AliasAnalysis &AA) {
1991 if (!PollyUseRuntimeAliasChecks)
1992 return;
1993
1994 if (buildAliasGroups(AA))
1995 return;
1996
1997 // If a problem occurs while building the alias groups we need to delete
1998 // this SCoP and pretend it wasn't valid in the first place. To this end
1999 // we make the assumed context infeasible.
2000 addAssumption(isl_set_empty(getParamSpace()));
2001
2002 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2003 << " could not be created as the number of parameters involved "
2004 "is too high. The SCoP will be "
2005 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2006 "the maximal number of parameters but be advised that the "
2007 "compile time might increase exponentially.\n\n");
2008}
2009
Johannes Doerfert9143d672014-09-27 11:02:39 +00002010bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002011 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002012 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002013 // for all memory accesses inside the SCoP.
2014 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002015 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002016 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002017 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002018 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002019 // if their access domains intersect, otherwise they are in different
2020 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002021 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002022 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002023 // and maximal accesses to each array of a group in read only and non
2024 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002025 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2026
2027 AliasSetTracker AST(AA);
2028
2029 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002030 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002031 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002032
2033 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002034 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002035 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2036 isl_set_free(StmtDomain);
2037 if (StmtDomainEmpty)
2038 continue;
2039
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002040 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002041 if (MA->isScalar())
2042 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002043 if (!MA->isRead())
2044 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002045 Instruction *Acc = MA->getAccessInstruction();
2046 PtrToAcc[getPointerOperand(*Acc)] = MA;
2047 AST.add(Acc);
2048 }
2049 }
2050
2051 SmallVector<AliasGroupTy, 4> AliasGroups;
2052 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002053 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002054 continue;
2055 AliasGroupTy AG;
2056 for (auto PR : AS)
2057 AG.push_back(PtrToAcc[PR.getValue()]);
2058 assert(AG.size() > 1 &&
2059 "Alias groups should contain at least two accesses");
2060 AliasGroups.push_back(std::move(AG));
2061 }
2062
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002063 // Split the alias groups based on their domain.
2064 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2065 AliasGroupTy NewAG;
2066 AliasGroupTy &AG = AliasGroups[u];
2067 AliasGroupTy::iterator AGI = AG.begin();
2068 isl_set *AGDomain = getAccessDomain(*AGI);
2069 while (AGI != AG.end()) {
2070 MemoryAccess *MA = *AGI;
2071 isl_set *MADomain = getAccessDomain(MA);
2072 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2073 NewAG.push_back(MA);
2074 AGI = AG.erase(AGI);
2075 isl_set_free(MADomain);
2076 } else {
2077 AGDomain = isl_set_union(AGDomain, MADomain);
2078 AGI++;
2079 }
2080 }
2081 if (NewAG.size() > 1)
2082 AliasGroups.push_back(std::move(NewAG));
2083 isl_set_free(AGDomain);
2084 }
2085
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002086 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002087 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2088 for (AliasGroupTy &AG : AliasGroups) {
2089 NonReadOnlyBaseValues.clear();
2090 ReadOnlyPairs.clear();
2091
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002092 if (AG.size() < 2) {
2093 AG.clear();
2094 continue;
2095 }
2096
Johannes Doerfert13771732014-10-01 12:40:46 +00002097 for (auto II = AG.begin(); II != AG.end();) {
2098 Value *BaseAddr = (*II)->getBaseAddr();
2099 if (HasWriteAccess.count(BaseAddr)) {
2100 NonReadOnlyBaseValues.insert(BaseAddr);
2101 II++;
2102 } else {
2103 ReadOnlyPairs[BaseAddr].insert(*II);
2104 II = AG.erase(II);
2105 }
2106 }
2107
2108 // If we don't have read only pointers check if there are at least two
2109 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002110 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002111 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002112 continue;
2113 }
2114
2115 // If we don't have non read only pointers clear the alias group.
2116 if (NonReadOnlyBaseValues.empty()) {
2117 AG.clear();
2118 continue;
2119 }
2120
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002121 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002122 MinMaxAliasGroups.emplace_back();
2123 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2124 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2125 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2126 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002127
2128 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002129
2130 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002131 for (MemoryAccess *MA : AG)
2132 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002133
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002134 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2135 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002136
2137 // Bail out if the number of values we need to compare is too large.
2138 // This is important as the number of comparisions grows quadratically with
2139 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002140 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2141 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002142 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002143
2144 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002145 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002146 Accesses = isl_union_map_empty(getParamSpace());
2147
2148 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2149 for (MemoryAccess *MA : ReadOnlyPair.second)
2150 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2151
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002152 Valid =
2153 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002154
2155 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002156 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002157 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002158
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002159 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002160}
2161
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002162static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
2163 Loop *L = LI.getLoopFor(R.getEntry());
2164 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2165}
2166
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002167static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2168 ScopDetection &SD) {
2169
2170 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2171
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002172 unsigned MinLD = INT_MAX, MaxLD = 0;
2173 for (BasicBlock *BB : R.blocks()) {
2174 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002175 if (!R.contains(L))
2176 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002177 if (BoxedLoops && BoxedLoops->count(L))
2178 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002179 unsigned LD = L->getLoopDepth();
2180 MinLD = std::min(MinLD, LD);
2181 MaxLD = std::max(MaxLD, LD);
2182 }
2183 }
2184
2185 // Handle the case that there is no loop in the SCoP first.
2186 if (MaxLD == 0)
2187 return 1;
2188
2189 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2190 assert(MaxLD >= MinLD &&
2191 "Maximal loop depth was smaller than mininaml loop depth?");
2192 return MaxLD - MinLD + 1;
2193}
2194
Michael Kruse9d080092015-09-11 21:41:48 +00002195Scop::Scop(Region &R, AccFuncMapType &AccFuncMap,
2196 ScalarEvolution &ScalarEvolution, DominatorTree &DT,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002197 isl_ctx *Context, unsigned MaxLoopDepth)
Michael Kruse9d080092015-09-11 21:41:48 +00002198 : DT(DT), SE(&ScalarEvolution), R(R), AccFuncMap(AccFuncMap),
2199 IsOptimized(false), HasSingleExitEdge(R.getExitingBlock()),
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002200 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Affinator(this),
2201 BoundaryContext(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002202
Michael Kruse9d080092015-09-11 21:41:48 +00002203void Scop::init(LoopInfo &LI, ScopDetection &SD, AliasAnalysis &AA) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002204 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00002205
Johannes Doerfert96425c22015-08-30 21:13:53 +00002206 buildDomains(&R, LI, SD, DT);
2207
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002208 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
Tobias Grosser75805372011-04-29 06:27:02 +00002209
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002210 Loop *L = getLoopSurroundingRegion(R, LI);
2211 LoopSchedules[L];
Michael Kruse9d080092015-09-11 21:41:48 +00002212 buildSchedule(&R, LI, SD, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002213 Schedule = LoopSchedules[L].first;
Tobias Grosser75805372011-04-29 06:27:02 +00002214
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002215 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002216 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002217 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002218 buildBoundaryContext();
2219 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002220 buildAliasChecks(AA);
Tobias Grosser75805372011-04-29 06:27:02 +00002221}
2222
2223Scop::~Scop() {
2224 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002225 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002226 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002227 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002228
Johannes Doerfert96425c22015-08-30 21:13:53 +00002229 for (auto It : DomainMap)
2230 isl_set_free(It.second);
2231
Johannes Doerfertb164c792014-09-18 11:17:17 +00002232 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002233 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002234 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002235 isl_pw_multi_aff_free(MMA.first);
2236 isl_pw_multi_aff_free(MMA.second);
2237 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002238 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002239 isl_pw_multi_aff_free(MMA.first);
2240 isl_pw_multi_aff_free(MMA.second);
2241 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002242 }
Tobias Grosser75805372011-04-29 06:27:02 +00002243}
2244
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002245const ScopArrayInfo *
2246Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Michael Kruse28468772015-09-14 15:45:33 +00002247 ArrayRef<const SCEV *> Sizes, bool IsPHI) {
Tobias Grosser92245222015-07-28 14:53:44 +00002248 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)];
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002249 if (!SAI)
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002250 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, IsPHI,
2251 this));
Tobias Grosserab671442015-05-23 05:58:27 +00002252 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002253}
2254
Tobias Grosser92245222015-07-28 14:53:44 +00002255const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, bool IsPHI) {
2256 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002257 assert(SAI && "No ScopArrayInfo available for this base pointer");
2258 return SAI;
2259}
2260
Tobias Grosser74394f02013-01-14 22:40:23 +00002261std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002262std::string Scop::getAssumedContextStr() const {
2263 return stringFromIslObj(AssumedContext);
2264}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002265std::string Scop::getBoundaryContextStr() const {
2266 return stringFromIslObj(BoundaryContext);
2267}
Tobias Grosser75805372011-04-29 06:27:02 +00002268
2269std::string Scop::getNameStr() const {
2270 std::string ExitName, EntryName;
2271 raw_string_ostream ExitStr(ExitName);
2272 raw_string_ostream EntryStr(EntryName);
2273
Tobias Grosserf240b482014-01-09 10:42:15 +00002274 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002275 EntryStr.str();
2276
2277 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00002278 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002279 ExitStr.str();
2280 } else
2281 ExitName = "FunctionExit";
2282
2283 return EntryName + "---" + ExitName;
2284}
2285
Tobias Grosser74394f02013-01-14 22:40:23 +00002286__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00002287__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002288 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00002289}
2290
Tobias Grossere86109f2013-10-29 21:05:49 +00002291__isl_give isl_set *Scop::getAssumedContext() const {
2292 return isl_set_copy(AssumedContext);
2293}
2294
Johannes Doerfert43788c52015-08-20 05:58:56 +00002295__isl_give isl_set *Scop::getRuntimeCheckContext() const {
2296 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002297 RuntimeCheckContext =
2298 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
2299 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002300 return RuntimeCheckContext;
2301}
2302
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002303bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002304 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002305 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002306 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
2307 isl_set_free(RuntimeCheckContext);
2308 return IsFeasible;
2309}
2310
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002311void Scop::addAssumption(__isl_take isl_set *Set) {
2312 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00002313 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002314}
2315
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002316__isl_give isl_set *Scop::getBoundaryContext() const {
2317 return isl_set_copy(BoundaryContext);
2318}
2319
Tobias Grosser75805372011-04-29 06:27:02 +00002320void Scop::printContext(raw_ostream &OS) const {
2321 OS << "Context:\n";
2322
2323 if (!Context) {
2324 OS.indent(4) << "n/a\n\n";
2325 return;
2326 }
2327
2328 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00002329
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002330 OS.indent(4) << "Assumed Context:\n";
2331 if (!AssumedContext) {
2332 OS.indent(4) << "n/a\n\n";
2333 return;
2334 }
2335
2336 OS.indent(4) << getAssumedContextStr() << "\n";
2337
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002338 OS.indent(4) << "Boundary Context:\n";
2339 if (!BoundaryContext) {
2340 OS.indent(4) << "n/a\n\n";
2341 return;
2342 }
2343
2344 OS.indent(4) << getBoundaryContextStr() << "\n";
2345
Tobias Grosser083d3d32014-06-28 08:59:45 +00002346 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00002347 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00002348 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
2349 }
Tobias Grosser75805372011-04-29 06:27:02 +00002350}
2351
Johannes Doerfertb164c792014-09-18 11:17:17 +00002352void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002353 int noOfGroups = 0;
2354 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002355 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002356 noOfGroups += 1;
2357 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002358 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002359 }
2360
Tobias Grosserbb853c22015-07-25 12:31:03 +00002361 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00002362 if (MinMaxAliasGroups.empty()) {
2363 OS.indent(8) << "n/a\n";
2364 return;
2365 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002366
Tobias Grosserbb853c22015-07-25 12:31:03 +00002367 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002368
2369 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002370 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002371 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002372 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002373 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2374 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002375 }
2376 OS << " ]]\n";
2377 }
2378
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002379 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002380 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00002381 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002382 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002383 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2384 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002385 }
2386 OS << " ]]\n";
2387 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002388 }
2389}
2390
Tobias Grosser75805372011-04-29 06:27:02 +00002391void Scop::printStatements(raw_ostream &OS) const {
2392 OS << "Statements {\n";
2393
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002394 for (const ScopStmt &Stmt : *this)
2395 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00002396
2397 OS.indent(4) << "}\n";
2398}
2399
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002400void Scop::printArrayInfo(raw_ostream &OS) const {
2401 OS << "Arrays {\n";
2402
Tobias Grosserab671442015-05-23 05:58:27 +00002403 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002404 Array.second->print(OS);
2405
2406 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002407
2408 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
2409
2410 for (auto &Array : arrays())
2411 Array.second->print(OS, /* SizeAsPwAff */ true);
2412
2413 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002414}
2415
Tobias Grosser75805372011-04-29 06:27:02 +00002416void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00002417 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
2418 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00002419 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00002420 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00002421 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002422 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002423 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00002424 printStatements(OS.indent(4));
2425}
2426
2427void Scop::dump() const { print(dbgs()); }
2428
Tobias Grosser9a38ab82011-11-08 15:41:03 +00002429isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00002430
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002431__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
2432 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00002433}
2434
Tobias Grosser808cd692015-07-14 09:33:13 +00002435__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002436 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002437
Tobias Grosser808cd692015-07-14 09:33:13 +00002438 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002439 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002440
2441 return Domain;
2442}
2443
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002444__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002445 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002446
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002447 for (ScopStmt &Stmt : *this) {
2448 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002449 if (!MA->isMustWrite())
2450 continue;
2451
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002452 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002453 isl_map *AccessDomain = MA->getAccessRelation();
2454 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2455 Write = isl_union_map_add_map(Write, AccessDomain);
2456 }
2457 }
2458 return isl_union_map_coalesce(Write);
2459}
2460
2461__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002462 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002463
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002464 for (ScopStmt &Stmt : *this) {
2465 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002466 if (!MA->isMayWrite())
2467 continue;
2468
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002469 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002470 isl_map *AccessDomain = MA->getAccessRelation();
2471 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2472 Write = isl_union_map_add_map(Write, AccessDomain);
2473 }
2474 }
2475 return isl_union_map_coalesce(Write);
2476}
2477
Tobias Grosser37eb4222014-02-20 21:43:54 +00002478__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002479 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002480
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002481 for (ScopStmt &Stmt : *this) {
2482 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002483 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002484 continue;
2485
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002486 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002487 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002488 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2489 Write = isl_union_map_add_map(Write, AccessDomain);
2490 }
2491 }
2492 return isl_union_map_coalesce(Write);
2493}
2494
2495__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002496 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002497
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002498 for (ScopStmt &Stmt : *this) {
2499 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002500 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002501 continue;
2502
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002503 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002504 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002505
2506 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2507 Read = isl_union_map_add_map(Read, AccessDomain);
2508 }
2509 }
2510 return isl_union_map_coalesce(Read);
2511}
2512
Tobias Grosser808cd692015-07-14 09:33:13 +00002513__isl_give isl_union_map *Scop::getSchedule() const {
2514 auto Tree = getScheduleTree();
2515 auto S = isl_schedule_get_map(Tree);
2516 isl_schedule_free(Tree);
2517 return S;
2518}
Tobias Grosser37eb4222014-02-20 21:43:54 +00002519
Tobias Grosser808cd692015-07-14 09:33:13 +00002520__isl_give isl_schedule *Scop::getScheduleTree() const {
2521 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
2522 getDomains());
2523}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002524
Tobias Grosser808cd692015-07-14 09:33:13 +00002525void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
2526 auto *S = isl_schedule_from_domain(getDomains());
2527 S = isl_schedule_insert_partial_schedule(
2528 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
2529 isl_schedule_free(Schedule);
2530 Schedule = S;
2531}
2532
2533void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
2534 isl_schedule_free(Schedule);
2535 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00002536}
2537
2538bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
2539 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002540 for (ScopStmt &Stmt : *this) {
2541 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002542 isl_union_set *NewStmtDomain = isl_union_set_intersect(
2543 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
2544
2545 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
2546 isl_union_set_free(StmtDomain);
2547 isl_union_set_free(NewStmtDomain);
2548 continue;
2549 }
2550
2551 Changed = true;
2552
2553 isl_union_set_free(StmtDomain);
2554 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
2555
2556 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002557 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002558 isl_union_set_free(NewStmtDomain);
2559 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002560 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002561 }
2562 isl_union_set_free(Domain);
2563 return Changed;
2564}
2565
Tobias Grosser75805372011-04-29 06:27:02 +00002566ScalarEvolution *Scop::getSE() const { return SE; }
2567
Michael Kruse9d080092015-09-11 21:41:48 +00002568bool Scop::isTrivialBB(BasicBlock *BB) {
2569 if (getAccessFunctions(BB) && !isErrorBlock(*BB))
Tobias Grosser75805372011-04-29 06:27:02 +00002570 return false;
2571
2572 return true;
2573}
2574
Tobias Grosser808cd692015-07-14 09:33:13 +00002575struct MapToDimensionDataTy {
2576 int N;
2577 isl_union_pw_multi_aff *Res;
2578};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002579
Tobias Grosser808cd692015-07-14 09:33:13 +00002580// @brief Create a function that maps the elements of 'Set' to its N-th
2581// dimension.
2582//
2583// The result is added to 'User->Res'.
2584//
2585// @param Set The input set.
2586// @param N The dimension to map to.
2587//
2588// @returns Zero if no error occurred, non-zero otherwise.
2589static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
2590 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
2591 int Dim;
2592 isl_space *Space;
2593 isl_pw_multi_aff *PMA;
2594
2595 Dim = isl_set_dim(Set, isl_dim_set);
2596 Space = isl_set_get_space(Set);
2597 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
2598 Dim - Data->N);
2599 if (Data->N > 1)
2600 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
2601 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
2602
2603 isl_set_free(Set);
2604
2605 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002606}
2607
Tobias Grosser808cd692015-07-14 09:33:13 +00002608// @brief Create a function that maps the elements of Domain to their Nth
2609// dimension.
2610//
2611// @param Domain The set of elements to map.
2612// @param N The dimension to map to.
2613static __isl_give isl_multi_union_pw_aff *
2614mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002615 if (N <= 0 || isl_union_set_is_empty(Domain)) {
2616 isl_union_set_free(Domain);
2617 return nullptr;
2618 }
2619
Tobias Grosser808cd692015-07-14 09:33:13 +00002620 struct MapToDimensionDataTy Data;
2621 isl_space *Space;
2622
2623 Space = isl_union_set_get_space(Domain);
2624 Data.N = N;
2625 Data.Res = isl_union_pw_multi_aff_empty(Space);
2626 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
2627 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
2628
2629 isl_union_set_free(Domain);
2630 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
2631}
2632
Michael Kruse9d080092015-09-11 21:41:48 +00002633ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00002634 ScopStmt *Stmt;
2635 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00002636 Stmts.emplace_back(*this, *BB);
Tobias Grosser808cd692015-07-14 09:33:13 +00002637 Stmt = &Stmts.back();
2638 StmtMap[BB] = Stmt;
2639 } else {
2640 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00002641 Stmts.emplace_back(*this, *R);
Tobias Grosser808cd692015-07-14 09:33:13 +00002642 Stmt = &Stmts.back();
2643 for (BasicBlock *BB : R->blocks())
2644 StmtMap[BB] = Stmt;
2645 }
2646 return Stmt;
2647}
2648
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002649void Scop::buildSchedule(
Michael Kruse9d080092015-09-11 21:41:48 +00002650 Region *R, LoopInfo &LI, ScopDetection &SD,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002651 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00002652
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002653 if (SD.isNonAffineSubRegion(R, &getRegion())) {
2654 auto *Stmt = addScopStmt(nullptr, R);
2655 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
2656 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
2657 auto &LSchedulePair = LoopSchedules[nullptr];
2658 LSchedulePair.first = StmtSchedule;
2659 return;
2660 }
2661
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002662 ReversePostOrderTraversal<Region *> RTraversal(R);
2663 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00002664
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002665 if (RN->isSubRegion()) {
2666 Region *SubRegion = RN->getNodeAs<Region>();
2667 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Michael Kruse9d080092015-09-11 21:41:48 +00002668 buildSchedule(SubRegion, LI, SD, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002669 continue;
2670 }
Tobias Grosser75805372011-04-29 06:27:02 +00002671 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002672
2673 Loop *L = getRegionNodeLoop(RN, LI);
2674 int LD = getRelativeLoopDepth(L);
2675 auto &LSchedulePair = LoopSchedules[L];
2676 LSchedulePair.second += getNumBlocksInRegionNode(RN);
2677
2678 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Michael Kruse9d080092015-09-11 21:41:48 +00002679 if (RN->isSubRegion() || !isTrivialBB(BB)) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002680
2681 ScopStmt *Stmt;
2682 if (RN->isSubRegion())
Michael Kruse9d080092015-09-11 21:41:48 +00002683 Stmt = addScopStmt(nullptr, RN->getNodeAs<Region>());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002684 else
Michael Kruse9d080092015-09-11 21:41:48 +00002685 Stmt = addScopStmt(BB, nullptr);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002686
2687 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
2688 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
2689 LSchedulePair.first =
2690 combineInSequence(LSchedulePair.first, StmtSchedule);
2691 }
2692
2693 unsigned NumVisited = LSchedulePair.second;
2694 while (L && NumVisited == L->getNumBlocks()) {
2695 auto *LDomain = isl_schedule_get_domain(LSchedulePair.first);
2696 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
2697 LSchedulePair.first =
2698 isl_schedule_insert_partial_schedule(LSchedulePair.first, MUPA);
2699
2700 auto *PL = L->getParentLoop();
2701 assert(LoopSchedules.count(PL));
2702 auto &PSchedulePair = LoopSchedules[PL];
2703 PSchedulePair.first =
2704 combineInSequence(PSchedulePair.first, LSchedulePair.first);
2705 PSchedulePair.second += NumVisited;
2706
2707 L = PL;
2708 NumVisited = PSchedulePair.second;
2709 }
Tobias Grosser808cd692015-07-14 09:33:13 +00002710 }
Tobias Grosser75805372011-04-29 06:27:02 +00002711}
2712
Johannes Doerfert7c494212014-10-31 23:13:39 +00002713ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00002714 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00002715 if (StmtMapIt == StmtMap.end())
2716 return nullptr;
2717 return StmtMapIt->second;
2718}
2719
Michael Kruse9d080092015-09-11 21:41:48 +00002720void Scop::printIRAccesses(raw_ostream &OS, ScalarEvolution *SE,
2721 LoopInfo *LI) const {
Michael Kruse7bf39442015-09-10 12:46:52 +00002722 OS << "Scop: " << R.getNameStr() << "\n";
2723
Michael Kruse9d080092015-09-11 21:41:48 +00002724 printIRAccessesDetail(OS, SE, LI, &R, 0);
Michael Kruse7bf39442015-09-10 12:46:52 +00002725}
2726
Michael Kruse9d080092015-09-11 21:41:48 +00002727void Scop::printIRAccessesDetail(raw_ostream &OS, ScalarEvolution *SE,
2728 LoopInfo *LI, const Region *CurR,
2729 unsigned ind) const {
Michael Kruse7bf39442015-09-10 12:46:52 +00002730 // FIXME: Print other details rather than memory accesses.
2731 for (const auto &CurBlock : CurR->blocks()) {
2732 AccFuncMapType::const_iterator AccSetIt = AccFuncMap.find(CurBlock);
2733
2734 // Ignore trivial blocks that do not contain any memory access.
2735 if (AccSetIt == AccFuncMap.end())
2736 continue;
2737
2738 OS.indent(ind) << "BB: " << CurBlock->getName() << '\n';
2739 typedef AccFuncSetType::const_iterator access_iterator;
2740 const AccFuncSetType &AccFuncs = AccSetIt->second;
2741
2742 for (access_iterator AI = AccFuncs.begin(), AE = AccFuncs.end(); AI != AE;
2743 ++AI)
2744 AI->first.print(OS.indent(ind + 2));
2745 }
2746}
2747
Johannes Doerfert96425c22015-08-30 21:13:53 +00002748int Scop::getRelativeLoopDepth(const Loop *L) const {
2749 Loop *OuterLoop =
2750 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
2751 if (!OuterLoop)
2752 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00002753 return L->getLoopDepth() - OuterLoop->getLoopDepth();
2754}
2755
Michael Krused868b5d2015-09-10 15:25:24 +00002756void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
2757 AccFuncSetType &Functions,
2758 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002759
2760 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
2761 // true, are not modeled as ordinary PHI nodes as they are not part of the
2762 // region. However, we model the operands in the predecessor blocks that are
2763 // part of the region as regular scalar accesses.
2764
2765 // If we can synthesize a PHI we can skip it, however only if it is in
2766 // the region. If it is not it can only be in the exit block of the region.
2767 // In this case we model the operands but not the PHI itself.
2768 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
2769 return;
2770
2771 // PHI nodes are modeled as if they had been demoted prior to the SCoP
2772 // detection. Hence, the PHI is a load of a new memory location in which the
2773 // incoming value was written at the end of the incoming basic block.
2774 bool OnlyNonAffineSubRegionOperands = true;
2775 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
2776 Value *Op = PHI->getIncomingValue(u);
2777 BasicBlock *OpBB = PHI->getIncomingBlock(u);
2778
2779 // Do not build scalar dependences inside a non-affine subregion.
2780 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
2781 continue;
2782
2783 OnlyNonAffineSubRegionOperands = false;
2784
2785 if (!R.contains(OpBB))
2786 continue;
2787
2788 Instruction *OpI = dyn_cast<Instruction>(Op);
2789 if (OpI) {
2790 BasicBlock *OpIBB = OpI->getParent();
2791 // As we pretend there is a use (or more precise a write) of OpI in OpBB
2792 // we have to insert a scalar dependence from the definition of OpI to
2793 // OpBB if the definition is not in OpBB.
2794 if (OpIBB != OpBB) {
2795 IRAccess ScalarRead(IRAccess::READ, OpI, ZeroOffset, 1, true, OpI);
2796 AccFuncMap[OpBB].push_back(std::make_pair(ScalarRead, PHI));
2797 IRAccess ScalarWrite(IRAccess::MUST_WRITE, OpI, ZeroOffset, 1, true,
2798 OpI);
2799 AccFuncMap[OpIBB].push_back(std::make_pair(ScalarWrite, OpI));
2800 }
2801 }
2802
2803 // Always use the terminator of the incoming basic block as the access
2804 // instruction.
2805 OpI = OpBB->getTerminator();
2806
2807 IRAccess ScalarAccess(IRAccess::MUST_WRITE, PHI, ZeroOffset, 1, true, Op,
2808 /* IsPHI */ !IsExitBlock);
2809 AccFuncMap[OpBB].push_back(std::make_pair(ScalarAccess, OpI));
2810 }
2811
2812 if (!OnlyNonAffineSubRegionOperands) {
2813 IRAccess ScalarAccess(IRAccess::READ, PHI, ZeroOffset, 1, true, PHI,
2814 /* IsPHI */ !IsExitBlock);
2815 Functions.push_back(std::make_pair(ScalarAccess, PHI));
2816 }
2817}
2818
Michael Krused868b5d2015-09-10 15:25:24 +00002819bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
2820 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002821 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
2822 if (isIgnoredIntrinsic(Inst))
2823 return false;
2824
2825 bool AnyCrossStmtUse = false;
2826 BasicBlock *ParentBB = Inst->getParent();
2827
2828 for (User *U : Inst->users()) {
2829 Instruction *UI = dyn_cast<Instruction>(U);
2830
2831 // Ignore the strange user
2832 if (UI == 0)
2833 continue;
2834
2835 BasicBlock *UseParent = UI->getParent();
2836
2837 // Ignore the users in the same BB (statement)
2838 if (UseParent == ParentBB)
2839 continue;
2840
2841 // Do not build scalar dependences inside a non-affine subregion.
2842 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
2843 continue;
2844
2845 // Check whether or not the use is in the SCoP.
2846 if (!R->contains(UseParent)) {
2847 AnyCrossStmtUse = true;
2848 continue;
2849 }
2850
2851 // If the instruction can be synthesized and the user is in the region
2852 // we do not need to add scalar dependences.
2853 if (canSynthesizeInst)
2854 continue;
2855
2856 // No need to translate these scalar dependences into polyhedral form,
2857 // because synthesizable scalars can be generated by the code generator.
2858 if (canSynthesize(UI, LI, SE, R))
2859 continue;
2860
2861 // Skip PHI nodes in the region as they handle their operands on their own.
2862 if (isa<PHINode>(UI))
2863 continue;
2864
2865 // Now U is used in another statement.
2866 AnyCrossStmtUse = true;
2867
2868 // Do not build a read access that is not in the current SCoP
2869 // Use the def instruction as base address of the IRAccess, so that it will
2870 // become the name of the scalar access in the polyhedral form.
2871 IRAccess ScalarAccess(IRAccess::READ, Inst, ZeroOffset, 1, true, Inst);
2872 AccFuncMap[UseParent].push_back(std::make_pair(ScalarAccess, UI));
2873 }
2874
2875 if (ModelReadOnlyScalars) {
2876 for (Value *Op : Inst->operands()) {
2877 if (canSynthesize(Op, LI, SE, R))
2878 continue;
2879
2880 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
2881 if (R->contains(OpInst))
2882 continue;
2883
2884 if (isa<Constant>(Op))
2885 continue;
2886
2887 IRAccess ScalarAccess(IRAccess::READ, Op, ZeroOffset, 1, true, Op);
2888 AccFuncMap[Inst->getParent()].push_back(
2889 std::make_pair(ScalarAccess, Inst));
2890 }
2891 }
2892
2893 return AnyCrossStmtUse;
2894}
2895
2896extern MapInsnToMemAcc InsnToMemAcc;
2897
2898IRAccess
Michael Krused868b5d2015-09-10 15:25:24 +00002899ScopInfo::buildIRAccess(Instruction *Inst, Loop *L, Region *R,
2900 const ScopDetection::BoxedLoopsSetTy *BoxedLoops) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002901 unsigned Size;
2902 Type *SizeType;
2903 Value *Val;
2904 enum IRAccess::TypeKind Type;
2905
2906 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
2907 SizeType = Load->getType();
2908 Size = TD->getTypeStoreSize(SizeType);
2909 Type = IRAccess::READ;
2910 Val = Load;
2911 } else {
2912 StoreInst *Store = cast<StoreInst>(Inst);
2913 SizeType = Store->getValueOperand()->getType();
2914 Size = TD->getTypeStoreSize(SizeType);
2915 Type = IRAccess::MUST_WRITE;
2916 Val = Store->getValueOperand();
2917 }
2918
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002919 auto Address = getPointerOperand(*Inst);
2920
2921 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00002922 const SCEVUnknown *BasePointer =
2923 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
2924
2925 assert(BasePointer && "Could not find base pointer");
2926 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
2927
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002928 if (auto *GEP = dyn_cast<GetElementPtrInst>(Address)) {
2929 std::vector<const SCEV *> Subscripts;
2930 std::vector<int> Sizes;
2931 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
2932 auto BasePtr = GEP->getOperand(0);
2933
2934 std::vector<const SCEV *> SizesSCEV;
2935
2936 bool AllAffineSubcripts = true;
2937 for (auto Subscript : Subscripts)
2938 if (!isAffineExpr(R, Subscript, *SE)) {
2939 AllAffineSubcripts = false;
2940 break;
2941 }
2942
2943 if (AllAffineSubcripts && Sizes.size() > 0) {
2944 for (auto V : Sizes)
2945 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
2946 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
2947 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
2948 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
2949
2950 return IRAccess(Type, BasePointer->getValue(), AccessFunction, Size, true,
2951 Subscripts, SizesSCEV, Val);
2952 }
2953 }
2954
Michael Kruse7bf39442015-09-10 12:46:52 +00002955 auto AccItr = InsnToMemAcc.find(Inst);
2956 if (PollyDelinearize && AccItr != InsnToMemAcc.end())
2957 return IRAccess(Type, BasePointer->getValue(), AccessFunction, Size, true,
2958 AccItr->second.DelinearizedSubscripts,
2959 AccItr->second.Shape->DelinearizedSizes, Val);
2960
2961 // Check if the access depends on a loop contained in a non-affine subregion.
2962 bool isVariantInNonAffineLoop = false;
2963 if (BoxedLoops) {
2964 SetVector<const Loop *> Loops;
2965 findLoops(AccessFunction, Loops);
2966 for (const Loop *L : Loops)
2967 if (BoxedLoops->count(L))
2968 isVariantInNonAffineLoop = true;
2969 }
2970
2971 bool IsAffine = !isVariantInNonAffineLoop &&
2972 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue());
2973
2974 SmallVector<const SCEV *, 4> Subscripts, Sizes;
2975 Subscripts.push_back(AccessFunction);
2976 Sizes.push_back(SE->getConstant(ZeroOffset->getType(), Size));
2977
2978 if (!IsAffine && Type == IRAccess::MUST_WRITE)
2979 Type = IRAccess::MAY_WRITE;
2980
2981 return IRAccess(Type, BasePointer->getValue(), AccessFunction, Size, IsAffine,
2982 Subscripts, Sizes, Val);
2983}
2984
Michael Krused868b5d2015-09-10 15:25:24 +00002985void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002986
2987 if (SD->isNonAffineSubRegion(&SR, &R)) {
2988 for (BasicBlock *BB : SR.blocks())
2989 buildAccessFunctions(R, *BB, &SR);
2990 return;
2991 }
2992
2993 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
2994 if (I->isSubRegion())
2995 buildAccessFunctions(R, *I->getNodeAs<Region>());
2996 else
2997 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
2998}
2999
Michael Krused868b5d2015-09-10 15:25:24 +00003000void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
3001 Region *NonAffineSubRegion,
3002 bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003003 AccFuncSetType Functions;
3004 Loop *L = LI->getLoopFor(&BB);
3005
3006 // The set of loops contained in non-affine subregions that are part of R.
3007 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3008
3009 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
3010 Instruction *Inst = I;
3011
3012 PHINode *PHI = dyn_cast<PHINode>(Inst);
3013 if (PHI)
3014 buildPHIAccesses(PHI, R, Functions, NonAffineSubRegion, IsExitBlock);
3015
3016 // For the exit block we stop modeling after the last PHI node.
3017 if (!PHI && IsExitBlock)
3018 break;
3019
3020 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
3021 Functions.push_back(
3022 std::make_pair(buildIRAccess(Inst, L, &R, BoxedLoops), Inst));
3023
3024 if (isIgnoredIntrinsic(Inst))
3025 continue;
3026
3027 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
3028 // If the Instruction is used outside the statement, we need to build the
3029 // write access.
3030 if (!isa<StoreInst>(Inst)) {
3031 IRAccess ScalarAccess(IRAccess::MUST_WRITE, Inst, ZeroOffset, 1, true,
3032 Inst);
3033 Functions.push_back(std::make_pair(ScalarAccess, Inst));
3034 }
3035 }
3036 }
3037
3038 if (Functions.empty())
3039 return;
3040
3041 AccFuncSetType &Accs = AccFuncMap[&BB];
3042 Accs.insert(Accs.end(), Functions.begin(), Functions.end());
3043}
3044
Michael Kruse9d080092015-09-11 21:41:48 +00003045Scop *ScopInfo::buildScop(Region &R, DominatorTree &DT) {
3046 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
3047 Scop *S = new Scop(R, AccFuncMap, *SE, DT, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00003048
3049 buildAccessFunctions(R, R);
3050
3051 // In case the region does not have an exiting block we will later (during
3052 // code generation) split the exit block. This will move potential PHI nodes
3053 // from the current exit block into the new region exiting block. Hence, PHI
3054 // nodes that are at this point not part of the region will be.
3055 // To handle these PHI nodes later we will now model their operands as scalar
3056 // accesses. Note that we do not model anything in the exit block if we have
3057 // an exiting block in the region, as there will not be any splitting later.
3058 if (!R.getExitingBlock())
3059 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
3060
Michael Kruse9d080092015-09-11 21:41:48 +00003061 S->init(*LI, *SD, *AA);
3062 return S;
Michael Kruse7bf39442015-09-10 12:46:52 +00003063}
3064
Michael Krused868b5d2015-09-10 15:25:24 +00003065void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00003066 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00003067 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00003068 return;
3069 }
3070
3071 scop->printIRAccesses(OS, SE, LI);
3072 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00003073}
3074
Michael Krused868b5d2015-09-10 15:25:24 +00003075void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00003076 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00003077 if (scop) {
3078 delete scop;
3079 scop = 0;
3080 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003081}
3082
3083//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00003084ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00003085 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00003086 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00003087}
3088
3089ScopInfo::~ScopInfo() {
3090 clear();
3091 isl_ctx_free(ctx);
3092}
3093
Tobias Grosser75805372011-04-29 06:27:02 +00003094void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Michael Krused868b5d2015-09-10 15:25:24 +00003095 AU.addRequiredID(IndependentBlocksID);
Chandler Carruthf5579872015-01-17 14:16:56 +00003096 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00003097 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00003098 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00003099 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
3100 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003101 AU.addRequired<AAResultsWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00003102 AU.setPreservesAll();
3103}
3104
3105bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00003106 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00003107
Michael Krused868b5d2015-09-10 15:25:24 +00003108 if (!SD->isMaxRegionInScop(*R))
3109 return false;
3110
3111 Function *F = R->getEntry()->getParent();
3112 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3113 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3114 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3115 TD = &F->getParent()->getDataLayout();
3116 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3117 ZeroOffset = SE->getConstant(TD->getIntPtrType(F->getContext()), 0);
3118
Michael Kruse9d080092015-09-11 21:41:48 +00003119 scop = buildScop(*R, DT);
Tobias Grosser75805372011-04-29 06:27:02 +00003120
Tobias Grosserd6a50b32015-05-30 06:26:21 +00003121 DEBUG(scop->print(dbgs()));
3122
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003123 if (!scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003124 delete scop;
3125 scop = nullptr;
3126 return false;
3127 }
3128
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003129 // Statistics.
3130 ++ScopFound;
3131 if (scop->getMaxLoopDepth() > 0)
3132 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00003133 return false;
3134}
3135
3136char ScopInfo::ID = 0;
3137
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003138Pass *polly::createScopInfoPass() { return new ScopInfo(); }
3139
Tobias Grosser73600b82011-10-08 00:30:40 +00003140INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
3141 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003142 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003143INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00003144INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00003145INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00003146INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003147INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003148INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00003149INITIALIZE_PASS_END(ScopInfo, "polly-scops",
3150 "Polly - Create polyhedral description of Scops", false,
3151 false)