blob: fb87fe1768ba5cebe002bbd27191961629c2e962 [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 Grosser75805372011-04-29 06:27:02 +0000292//===----------------------------------------------------------------------===//
293
294MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000295 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000296 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000297 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000298}
299
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000300static MemoryAccess::AccessType getMemoryAccessType(const IRAccess &Access) {
301 switch (Access.getType()) {
302 case IRAccess::READ:
303 return MemoryAccess::READ;
304 case IRAccess::MUST_WRITE:
305 return MemoryAccess::MUST_WRITE;
306 case IRAccess::MAY_WRITE:
307 return MemoryAccess::MAY_WRITE;
308 }
309 llvm_unreachable("Unknown IRAccess type!");
310}
311
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000312const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
313 isl_id *ArrayId = getArrayId();
314 void *User = isl_id_get_user(ArrayId);
315 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
316 isl_id_free(ArrayId);
317 return SAI;
318}
319
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000320__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000321 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
322}
323
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000324__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
325 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000326 isl_map *Schedule, *ScheduledAccRel;
327 isl_union_set *UDomain;
328
329 UDomain = isl_union_set_from_set(getStatement()->getDomain());
330 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
331 Schedule = isl_map_from_union_map(USchedule);
332 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
333 return isl_pw_multi_aff_from_map(ScheduledAccRel);
334}
335
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000336__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000337 return isl_map_copy(AccessRelation);
338}
339
Johannes Doerferta99130f2014-10-13 12:58:03 +0000340std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000341 return stringFromIslObj(AccessRelation);
342}
343
Johannes Doerferta99130f2014-10-13 12:58:03 +0000344__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000345 return isl_map_get_space(AccessRelation);
346}
347
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000348__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000349 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000350}
351
Tobias Grosser6f730082015-09-05 07:46:47 +0000352std::string MemoryAccess::getNewAccessRelationStr() const {
353 return stringFromIslObj(NewAccessRelation);
354}
355
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000356__isl_give isl_basic_map *
357MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000358 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000359 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000360
Tobias Grosser084d8f72012-05-29 09:29:44 +0000361 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000362 isl_basic_set_universe(Statement->getDomainSpace()),
363 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000364}
365
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000366// Formalize no out-of-bound access assumption
367//
368// When delinearizing array accesses we optimistically assume that the
369// delinearized accesses do not access out of bound locations (the subscript
370// expression of each array evaluates for each statement instance that is
371// executed to a value that is larger than zero and strictly smaller than the
372// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000373// dimension for which we do not need to assume any upper bound. At this point
374// we formalize this assumption to ensure that at code generation time the
375// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000376//
377// To find the set of constraints necessary to avoid out of bound accesses, we
378// first build the set of data locations that are not within array bounds. We
379// then apply the reverse access relation to obtain the set of iterations that
380// may contain invalid accesses and reduce this set of iterations to the ones
381// that are actually executed by intersecting them with the domain of the
382// statement. If we now project out all loop dimensions, we obtain a set of
383// parameters that may cause statement instances to be executed that may
384// possibly yield out of bound memory accesses. The complement of these
385// constraints is the set of constraints that needs to be assumed to ensure such
386// statement instances are never executed.
387void MemoryAccess::assumeNoOutOfBound(const IRAccess &Access) {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000388 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000389 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000390 for (int i = 1, Size = Access.Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000391 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
392 isl_pw_aff *Var =
393 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
394 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
395
396 isl_set *DimOutside;
397
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000398 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfert574182d2015-08-12 10:19:50 +0000399 isl_pw_aff *SizeE = Statement->getPwAff(Access.Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000400
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000401 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
402 Statement->getNumIterators());
403 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
404 isl_space_dim(Space, isl_dim_set));
405 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
406 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000407
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000408 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000409
410 Outside = isl_set_union(Outside, DimOutside);
411 }
412
413 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
414 Outside = isl_set_intersect(Outside, Statement->getDomain());
415 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000416
417 // Remove divs to avoid the construction of overly complicated assumptions.
418 // Doing so increases the set of parameter combinations that are assumed to
419 // not appear. This is always save, but may make the resulting run-time check
420 // bail out more often than strictly necessary.
421 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000422 Outside = isl_set_complement(Outside);
423 Statement->getParent()->addAssumption(Outside);
424 isl_space_free(Space);
425}
426
Johannes Doerferte7044942015-02-24 11:58:30 +0000427void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
428 ScalarEvolution *SE = Statement->getParent()->getSE();
429
430 Value *Ptr = getPointerOperand(*getAccessInstruction());
431 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
432 return;
433
434 auto *PtrSCEV = SE->getSCEV(Ptr);
435 if (isa<SCEVCouldNotCompute>(PtrSCEV))
436 return;
437
438 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
439 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
440 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
441
442 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
443 if (Range.isFullSet())
444 return;
445
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000446 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000447 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000448 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
449 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
450
451 auto Min = LB.sdiv(APInt(BW, ElementSize));
452 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000453
454 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
455 AccessRange =
456 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
457 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
458}
459
Tobias Grosser619190d2015-03-30 17:22:28 +0000460__isl_give isl_map *MemoryAccess::foldAccess(const IRAccess &Access,
461 __isl_take isl_map *AccessRelation,
462 ScopStmt *Statement) {
463 int Size = Access.Subscripts.size();
464
465 for (int i = Size - 2; i >= 0; --i) {
466 isl_space *Space;
467 isl_map *MapOne, *MapTwo;
Johannes Doerfert574182d2015-08-12 10:19:50 +0000468 isl_pw_aff *DimSize = Statement->getPwAff(Access.Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000469
470 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
471 isl_pw_aff_free(DimSize);
472 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
473
474 Space = isl_map_get_space(AccessRelation);
475 Space = isl_space_map_from_set(isl_space_range(Space));
476 Space = isl_space_align_params(Space, SpaceSize);
477
478 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
479 isl_id_free(ParamId);
480
481 MapOne = isl_map_universe(isl_space_copy(Space));
482 for (int j = 0; j < Size; ++j)
483 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
484 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
485
486 MapTwo = isl_map_universe(isl_space_copy(Space));
487 for (int j = 0; j < Size; ++j)
488 if (j < i || j > i + 1)
489 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
490
491 isl_local_space *LS = isl_local_space_from_space(Space);
492 isl_constraint *C;
493 C = isl_equality_alloc(isl_local_space_copy(LS));
494 C = isl_constraint_set_constant_si(C, -1);
495 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
496 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
497 MapTwo = isl_map_add_constraint(MapTwo, C);
498 C = isl_equality_alloc(LS);
499 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
500 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
501 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
502 MapTwo = isl_map_add_constraint(MapTwo, C);
503 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
504
505 MapOne = isl_map_union(MapOne, MapTwo);
506 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
507 }
508 return AccessRelation;
509}
510
Johannes Doerfert13c8cf22014-08-10 08:09:38 +0000511MemoryAccess::MemoryAccess(const IRAccess &Access, Instruction *AccInst,
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000512 ScopStmt *Statement, const ScopArrayInfo *SAI,
513 int Identifier)
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000514 : AccType(getMemoryAccessType(Access)), Statement(Statement),
515 AccessInstruction(AccInst), AccessValue(Access.getAccessValue()),
Tobias Grosser166c4222015-09-05 07:46:40 +0000516 NewAccessRelation(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +0000517
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000518 isl_ctx *Ctx = Statement->getIslCtx();
Tobias Grosser9759f852011-11-10 12:44:55 +0000519 BaseAddr = Access.getBase();
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000520 BaseName = getIslCompatibleName("MemRef_", getBaseAddr(), "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000521
522 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000523
Tobias Grosserac3a95f2015-08-03 17:53:21 +0000524 auto IdName = "__polly_array_ref_" + std::to_string(Identifier);
Tobias Grossere29d31c2015-05-15 12:24:09 +0000525 Id = isl_id_alloc(Ctx, IdName.c_str(), nullptr);
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000526
Tobias Grossera1879642011-12-20 10:43:14 +0000527 if (!Access.isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000528 // We overapproximate non-affine accesses with a possible access to the
529 // whole array. For read accesses it does not make a difference, if an
530 // access must or may happen. However, for write accesses it is important to
531 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000532 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000533 AccessRelation =
534 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000535
536 computeBoundsOnAccessRelation(Access.getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000537 return;
538 }
539
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000540 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000541 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000542
Tobias Grosser79baa212014-04-10 08:38:02 +0000543 for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000544 isl_pw_aff *Affine = Statement->getPwAff(Access.Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000545
Sebastian Pop422e33f2014-06-03 18:16:31 +0000546 if (Size == 1) {
547 // For the non delinearized arrays, divide the access function of the last
548 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000549 //
550 // A stride one array access in C expressed as A[i] is expressed in
551 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
552 // two subsequent values of 'i' index two values that are stored next to
553 // each other in memory. By this division we make this characteristic
554 // obvious again.
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000555 isl_val *v = isl_val_int_from_si(Ctx, Access.getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000556 Affine = isl_pw_aff_scale_down_val(Affine, v);
557 }
558
559 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
560
Tobias Grosser79baa212014-04-10 08:38:02 +0000561 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000562 }
563
Tobias Grosser619190d2015-03-30 17:22:28 +0000564 AccessRelation = foldAccess(Access, AccessRelation, Statement);
565
Tobias Grosser79baa212014-04-10 08:38:02 +0000566 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000567 AccessRelation = isl_map_set_tuple_id(
568 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000569 AccessRelation =
570 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
571
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000572 assumeNoOutOfBound(Access);
Tobias Grosseraa660a92015-03-30 00:07:50 +0000573 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000574 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000575}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000576
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000577void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000578 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000579 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000580}
581
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000582const std::string MemoryAccess::getReductionOperatorStr() const {
583 return MemoryAccess::getReductionOperatorStr(getReductionType());
584}
585
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000586__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
587
Johannes Doerfertf6183392014-07-01 20:52:51 +0000588raw_ostream &polly::operator<<(raw_ostream &OS,
589 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000590 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000591 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000592 else
593 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000594 return OS;
595}
596
Tobias Grosser75805372011-04-29 06:27:02 +0000597void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000598 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000599 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000600 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000601 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000602 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000603 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000604 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000605 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000606 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000607 break;
608 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000609 OS << "[Reduction Type: " << getReductionType() << "] ";
610 OS << "[Scalar: " << isScalar() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000611 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000612 if (hasNewAccessRelation())
613 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000614}
615
Tobias Grosser74394f02013-01-14 22:40:23 +0000616void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000617
618// Create a map in the size of the provided set domain, that maps from the
619// one element of the provided set domain to another element of the provided
620// set domain.
621// The mapping is limited to all points that are equal in all but the last
622// dimension and for which the last dimension of the input is strict smaller
623// than the last dimension of the output.
624//
625// getEqualAndLarger(set[i0, i1, ..., iX]):
626//
627// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
628// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
629//
Tobias Grosserf5338802011-10-06 00:03:35 +0000630static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000631 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000632 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000633 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000634
635 // Set all but the last dimension to be equal for the input and output
636 //
637 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
638 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000639 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000640 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000641
642 // Set the last dimension of the input to be strict smaller than the
643 // last dimension of the output.
644 //
645 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000646 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
647 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000648 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000649}
650
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000651__isl_give isl_set *
652MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000653 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000654 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000655 isl_space *Space = isl_space_range(isl_map_get_space(S));
656 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000657
Sebastian Popa00a0292012-12-18 07:46:06 +0000658 S = isl_map_reverse(S);
659 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000660
Sebastian Popa00a0292012-12-18 07:46:06 +0000661 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
662 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
663 NextScatt = isl_map_apply_domain(NextScatt, S);
664 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000665
Sebastian Popa00a0292012-12-18 07:46:06 +0000666 isl_set *Deltas = isl_map_deltas(NextScatt);
667 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000668}
669
Sebastian Popa00a0292012-12-18 07:46:06 +0000670bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000671 int StrideWidth) const {
672 isl_set *Stride, *StrideX;
673 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000674
Sebastian Popa00a0292012-12-18 07:46:06 +0000675 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000676 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000677 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
678 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
679 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
680 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000681 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000682
Tobias Grosser28dd4862012-01-24 16:42:16 +0000683 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000684 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000685
Tobias Grosser28dd4862012-01-24 16:42:16 +0000686 return IsStrideX;
687}
688
Sebastian Popa00a0292012-12-18 07:46:06 +0000689bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
690 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000691}
692
Tobias Grosser79baa212014-04-10 08:38:02 +0000693bool MemoryAccess::isScalar() const {
694 return isl_map_n_out(AccessRelation) == 0;
695}
696
Sebastian Popa00a0292012-12-18 07:46:06 +0000697bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
698 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000699}
700
Tobias Grosser166c4222015-09-05 07:46:40 +0000701void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
702 isl_map_free(NewAccessRelation);
703 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000704}
Tobias Grosser75805372011-04-29 06:27:02 +0000705
706//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000707
Tobias Grosser808cd692015-07-14 09:33:13 +0000708isl_map *ScopStmt::getSchedule() const {
709 isl_set *Domain = getDomain();
710 if (isl_set_is_empty(Domain)) {
711 isl_set_free(Domain);
712 return isl_map_from_aff(
713 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
714 }
715 auto *Schedule = getParent()->getSchedule();
716 Schedule = isl_union_map_intersect_domain(
717 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
718 if (isl_union_map_is_empty(Schedule)) {
719 isl_set_free(Domain);
720 isl_union_map_free(Schedule);
721 return isl_map_from_aff(
722 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
723 }
724 auto *M = isl_map_from_union_map(Schedule);
725 M = isl_map_coalesce(M);
726 M = isl_map_gist_domain(M, Domain);
727 M = isl_map_coalesce(M);
728 return M;
729}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000730
Johannes Doerfert574182d2015-08-12 10:19:50 +0000731__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000732 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
733 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000734}
735
Tobias Grosser37eb4222014-02-20 21:43:54 +0000736void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
737 assert(isl_set_is_subset(NewDomain, Domain) &&
738 "New domain is not a subset of old domain!");
739 isl_set_free(Domain);
740 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000741}
742
Michael Kruse9d080092015-09-11 21:41:48 +0000743void ScopStmt::buildAccesses(BasicBlock *Block, bool isApproximated) {
744 AccFuncSetType *AFS = Parent.getAccessFunctions(Block);
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000745 if (!AFS)
746 return;
747
748 for (auto &AccessPair : *AFS) {
749 IRAccess &Access = AccessPair.first;
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000750 Instruction *AccessInst = AccessPair.second;
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000751 Type *ElementType = Access.getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000752
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000753 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Tobias Grosser92245222015-07-28 14:53:44 +0000754 Access.getBase(), ElementType, Access.Sizes, Access.isPHI());
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000755
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000756 if (isApproximated && Access.isWrite())
757 Access.setMayWrite();
758
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000759 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
760 if (!MAL)
761 MAL = new MemoryAccessList();
762 MAL->emplace_front(Access, AccessInst, this, SAI, MemAccs.size());
763 MemAccs.push_back(&MAL->front());
Tobias Grosser75805372011-04-29 06:27:02 +0000764 }
765}
766
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000767void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000768 for (MemoryAccess *MA : *this)
769 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000770
771 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000772}
773
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000774/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
775static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
776 void *User) {
777 isl_set **BoundedParts = static_cast<isl_set **>(User);
778 if (isl_basic_set_is_bounded(BSet))
779 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
780 else
781 isl_basic_set_free(BSet);
782 return isl_stat_ok;
783}
784
785/// @brief Return the bounded parts of @p S.
786static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
787 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
788 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
789 isl_set_free(S);
790 return BoundedParts;
791}
792
793/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
794///
795/// @returns A separation of @p S into first an unbounded then a bounded subset,
796/// both with regards to the dimension @p Dim.
797static std::pair<__isl_give isl_set *, __isl_give isl_set *>
798partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
799
800 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertca1e38f2015-09-14 11:12:52 +0000801 S = isl_set_lower_bound_si(S, isl_dim_set, u, u == Dim ? -1 : 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000802
803 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertca1e38f2015-09-14 11:12:52 +0000804 isl_set *OnlyDimS = S;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000805
806 // Remove dimensions that are greater than Dim as they are not interesting.
807 assert(NumDimsS >= Dim + 1);
808 OnlyDimS =
809 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
810
811 // Create artificial parametric upper bounds for dimensions smaller than Dim
812 // as we are not interested in them.
813 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
814 for (unsigned u = 0; u < Dim; u++) {
815 isl_constraint *C = isl_inequality_alloc(
816 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
817 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
818 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
819 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
820 }
821
822 // Collect all bounded parts of OnlyDimS.
823 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
824
825 // Create the dimensions greater than Dim again.
826 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
827 NumDimsS - Dim - 1);
828
829 // Remove the artificial upper bound parameters again.
830 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
831
Johannes Doerfertca1e38f2015-09-14 11:12:52 +0000832 isl_set *UnboundedParts = isl_set_complement(isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000833 return std::make_pair(UnboundedParts, BoundedParts);
834}
835
Johannes Doerfert96425c22015-08-30 21:13:53 +0000836static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
837 isl_pw_aff *L, isl_pw_aff *R) {
838 switch (Pred) {
839 case ICmpInst::ICMP_EQ:
840 return isl_pw_aff_eq_set(L, R);
841 case ICmpInst::ICMP_NE:
842 return isl_pw_aff_ne_set(L, R);
843 case ICmpInst::ICMP_SLT:
844 return isl_pw_aff_lt_set(L, R);
845 case ICmpInst::ICMP_SLE:
846 return isl_pw_aff_le_set(L, R);
847 case ICmpInst::ICMP_SGT:
848 return isl_pw_aff_gt_set(L, R);
849 case ICmpInst::ICMP_SGE:
850 return isl_pw_aff_ge_set(L, R);
851 case ICmpInst::ICMP_ULT:
852 return isl_pw_aff_lt_set(L, R);
853 case ICmpInst::ICMP_UGT:
854 return isl_pw_aff_gt_set(L, R);
855 case ICmpInst::ICMP_ULE:
856 return isl_pw_aff_le_set(L, R);
857 case ICmpInst::ICMP_UGE:
858 return isl_pw_aff_ge_set(L, R);
859 default:
860 llvm_unreachable("Non integer predicate not supported");
861 }
862}
863
864/// @brief Build the conditions sets for the branch @p BI in the @p Domain.
865///
866/// This will fill @p ConditionSets with the conditions under which control
867/// will be moved from @p BI to its successors. Hence, @p ConditionSets will
868/// have as many elements as @p BI has successors.
869static void
870buildConditionSets(Scop &S, BranchInst *BI, Loop *L, __isl_keep isl_set *Domain,
871 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
872
873 if (BI->isUnconditional()) {
874 ConditionSets.push_back(isl_set_copy(Domain));
875 return;
876 }
877
878 Value *Condition = BI->getCondition();
879
880 isl_set *ConsequenceCondSet = nullptr;
881 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
882 if (CCond->isZero())
883 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
884 else
885 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
886 } else {
887 auto *ICond = dyn_cast<ICmpInst>(Condition);
888 assert(ICond &&
889 "Condition of exiting branch was neither constant nor ICmp!");
890
891 ScalarEvolution &SE = *S.getSE();
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000892 BasicBlock *BB = BI->getParent();
Johannes Doerfert96425c22015-08-30 21:13:53 +0000893 isl_pw_aff *LHS, *RHS;
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000894 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
895 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
Johannes Doerfert96425c22015-08-30 21:13:53 +0000896 ConsequenceCondSet = buildConditionSet(ICond->getPredicate(), LHS, RHS);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000897
898 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
899 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
900 ConsequenceCondSet =
901 isl_set_set_dim_id(ConsequenceCondSet, isl_dim_set, u, DimId);
902 }
Johannes Doerfert96425c22015-08-30 21:13:53 +0000903 }
904
905 assert(ConsequenceCondSet);
906 isl_set *AlternativeCondSet =
907 isl_set_complement(isl_set_copy(ConsequenceCondSet));
908
909 ConditionSets.push_back(isl_set_coalesce(
910 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
911 ConditionSets.push_back(isl_set_coalesce(
912 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
913}
914
Johannes Doerfert32ae76e2015-09-10 13:12:02 +0000915void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000916 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000917
Tobias Grosser084d8f72012-05-29 09:29:44 +0000918 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
919
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000920 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +0000921 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +0000922}
923
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000924void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
925 int Dimension = 0;
926 isl_ctx *Ctx = Parent.getIslCtx();
927 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
928 Type *Ty = GEP->getPointerOperandType();
929 ScalarEvolution &SE = *Parent.getSE();
930
931 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
932 Dimension = 1;
933 Ty = PtrTy->getElementType();
934 }
935
936 while (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
937 unsigned int Operand = 1 + Dimension;
938
939 if (GEP->getNumOperands() <= Operand)
940 break;
941
942 const SCEV *Expr = SE.getSCEV(GEP->getOperand(Operand));
943
944 if (isAffineExpr(&Parent.getRegion(), Expr, SE)) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000945 isl_pw_aff *AccessOffset = getPwAff(Expr);
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000946 AccessOffset =
947 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
948
949 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
950 isl_local_space_copy(LSpace),
951 isl_val_int_from_si(Ctx, ArrayTy->getNumElements())));
952
953 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
954 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
955 OutOfBound = isl_set_params(OutOfBound);
956 isl_set *InBound = isl_set_complement(OutOfBound);
957 isl_set *Executed = isl_set_params(getDomain());
958
959 // A => B == !A or B
960 isl_set *InBoundIfExecuted =
961 isl_set_union(isl_set_complement(Executed), InBound);
962
963 Parent.addAssumption(InBoundIfExecuted);
964 }
965
966 Dimension += 1;
967 Ty = ArrayTy->getElementType();
968 }
969
970 isl_local_space_free(LSpace);
971}
972
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000973void ScopStmt::deriveAssumptions(BasicBlock *Block) {
974 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000975 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
976 deriveAssumptionsFromGEP(GEP);
977}
978
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000979void ScopStmt::collectSurroundingLoops() {
980 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
981 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
982 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
983 isl_id_free(DimId);
984 }
985}
986
Michael Kruse9d080092015-09-11 21:41:48 +0000987ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000988 : Parent(parent), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000989
Tobias Grosser16c44032015-07-09 07:31:45 +0000990 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000991
Johannes Doerfert32ae76e2015-09-10 13:12:02 +0000992 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000993 collectSurroundingLoops();
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000994
995 BasicBlock *EntryBB = R.getEntry();
996 for (BasicBlock *Block : R.blocks()) {
Michael Kruse9d080092015-09-11 21:41:48 +0000997 buildAccesses(Block, Block != EntryBB);
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000998 deriveAssumptions(Block);
999 }
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001000 if (DetectReductions)
1001 checkForReductions();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001002}
1003
Michael Kruse9d080092015-09-11 21:41:48 +00001004ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001005 : Parent(parent), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001006
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001007 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +00001008
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001009 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001010 collectSurroundingLoops();
Michael Kruse9d080092015-09-11 21:41:48 +00001011 buildAccesses(BB);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001012 deriveAssumptions(BB);
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001013 if (DetectReductions)
1014 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001015}
1016
Johannes Doerferte58a0122014-06-27 20:31:28 +00001017/// @brief Collect loads which might form a reduction chain with @p StoreMA
1018///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001019/// Check if the stored value for @p StoreMA is a binary operator with one or
1020/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001021/// used only once (by @p StoreMA) and its load operands are also used only
1022/// once, we have found a possible reduction chain. It starts at an operand
1023/// load and includes the binary operator and @p StoreMA.
1024///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001025/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001026/// escape this block or into any other store except @p StoreMA.
1027void ScopStmt::collectCandiateReductionLoads(
1028 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1029 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1030 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001031 return;
1032
1033 // Skip if there is not one binary operator between the load and the store
1034 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001035 if (!BinOp)
1036 return;
1037
1038 // Skip if the binary operators has multiple uses
1039 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001040 return;
1041
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001042 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001043 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1044 return;
1045
Johannes Doerfert9890a052014-07-01 00:32:29 +00001046 // Skip if the binary operator is outside the current SCoP
1047 if (BinOp->getParent() != Store->getParent())
1048 return;
1049
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001050 // Skip if it is a multiplicative reduction and we disabled them
1051 if (DisableMultiplicativeReductions &&
1052 (BinOp->getOpcode() == Instruction::Mul ||
1053 BinOp->getOpcode() == Instruction::FMul))
1054 return;
1055
Johannes Doerferte58a0122014-06-27 20:31:28 +00001056 // Check the binary operator operands for a candidate load
1057 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1058 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1059 if (!PossibleLoad0 && !PossibleLoad1)
1060 return;
1061
1062 // A load is only a candidate if it cannot escape (thus has only this use)
1063 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001064 if (PossibleLoad0->getParent() == Store->getParent())
1065 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001066 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001067 if (PossibleLoad1->getParent() == Store->getParent())
1068 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001069}
1070
1071/// @brief Check for reductions in this ScopStmt
1072///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001073/// Iterate over all store memory accesses and check for valid binary reduction
1074/// like chains. For all candidates we check if they have the same base address
1075/// and there are no other accesses which overlap with them. The base address
1076/// check rules out impossible reductions candidates early. The overlap check,
1077/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001078/// guarantees that none of the intermediate results will escape during
1079/// execution of the loop nest. We basically check here that no other memory
1080/// access can access the same memory as the potential reduction.
1081void ScopStmt::checkForReductions() {
1082 SmallVector<MemoryAccess *, 2> Loads;
1083 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1084
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001085 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001086 // stores and collecting possible reduction loads.
1087 for (MemoryAccess *StoreMA : MemAccs) {
1088 if (StoreMA->isRead())
1089 continue;
1090
1091 Loads.clear();
1092 collectCandiateReductionLoads(StoreMA, Loads);
1093 for (MemoryAccess *LoadMA : Loads)
1094 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1095 }
1096
1097 // Then check each possible candidate pair.
1098 for (const auto &CandidatePair : Candidates) {
1099 bool Valid = true;
1100 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1101 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1102
1103 // Skip those with obviously unequal base addresses.
1104 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1105 isl_map_free(LoadAccs);
1106 isl_map_free(StoreAccs);
1107 continue;
1108 }
1109
1110 // And check if the remaining for overlap with other memory accesses.
1111 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1112 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1113 isl_set *AllAccs = isl_map_range(AllAccsRel);
1114
1115 for (MemoryAccess *MA : MemAccs) {
1116 if (MA == CandidatePair.first || MA == CandidatePair.second)
1117 continue;
1118
1119 isl_map *AccRel =
1120 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1121 isl_set *Accs = isl_map_range(AccRel);
1122
1123 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1124 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1125 Valid = Valid && isl_set_is_empty(OverlapAccs);
1126 isl_set_free(OverlapAccs);
1127 }
1128 }
1129
1130 isl_set_free(AllAccs);
1131 if (!Valid)
1132 continue;
1133
Johannes Doerfertf6183392014-07-01 20:52:51 +00001134 const LoadInst *Load =
1135 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1136 MemoryAccess::ReductionType RT =
1137 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1138
Johannes Doerferte58a0122014-06-27 20:31:28 +00001139 // If no overlapping access was found we mark the load and store as
1140 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001141 CandidatePair.first->markAsReductionLike(RT);
1142 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001143 }
Tobias Grosser75805372011-04-29 06:27:02 +00001144}
1145
Tobias Grosser74394f02013-01-14 22:40:23 +00001146std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001147
Tobias Grosser54839312015-04-21 11:37:25 +00001148std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001149 auto *S = getSchedule();
1150 auto Str = stringFromIslObj(S);
1151 isl_map_free(S);
1152 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001153}
1154
Tobias Grosser74394f02013-01-14 22:40:23 +00001155unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001156
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001157unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001158
Tobias Grosser75805372011-04-29 06:27:02 +00001159const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1160
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001161const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001162 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001163}
1164
Tobias Grosser74394f02013-01-14 22:40:23 +00001165isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001166
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001167__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001168
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001169__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001170 return isl_set_get_space(Domain);
1171}
1172
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001173__isl_give isl_id *ScopStmt::getDomainId() const {
1174 return isl_set_get_tuple_id(Domain);
1175}
Tobias Grossercd95b772012-08-30 11:49:38 +00001176
Tobias Grosser75805372011-04-29 06:27:02 +00001177ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001178 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001179 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001180}
1181
1182void ScopStmt::print(raw_ostream &OS) const {
1183 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001184 OS.indent(12) << "Domain :=\n";
1185
1186 if (Domain) {
1187 OS.indent(16) << getDomainStr() << ";\n";
1188 } else
1189 OS.indent(16) << "n/a\n";
1190
Tobias Grosser54839312015-04-21 11:37:25 +00001191 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001192
1193 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001194 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001195 } else
1196 OS.indent(16) << "n/a\n";
1197
Tobias Grosser083d3d32014-06-28 08:59:45 +00001198 for (MemoryAccess *Access : MemAccs)
1199 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001200}
1201
1202void ScopStmt::dump() const { print(dbgs()); }
1203
1204//===----------------------------------------------------------------------===//
1205/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001206
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001207void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001208 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1209 isl_set_free(Context);
1210 Context = NewContext;
1211}
1212
Tobias Grosserabfbe632013-02-05 12:09:06 +00001213void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001214 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001215 Parameter = extractConstantFactor(Parameter, *SE).second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001216 if (ParameterIds.find(Parameter) != ParameterIds.end())
1217 continue;
1218
1219 int dimension = Parameters.size();
1220
1221 Parameters.push_back(Parameter);
1222 ParameterIds[Parameter] = dimension;
1223 }
1224}
1225
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001226__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1227 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001228
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001229 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001230 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001231
Tobias Grosser8f99c162011-11-15 11:38:55 +00001232 std::string ParameterName;
1233
1234 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1235 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001236 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001237 }
1238
1239 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001240 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001241
Tobias Grosser20532b82014-04-11 17:56:49 +00001242 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1243 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001244}
Tobias Grosser75805372011-04-29 06:27:02 +00001245
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001246isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1247 isl_set *DomainContext = isl_union_set_params(getDomains());
1248 return isl_set_intersect_params(C, DomainContext);
1249}
1250
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001251void Scop::buildBoundaryContext() {
1252 BoundaryContext = Affinator.getWrappingContext();
1253 BoundaryContext = isl_set_complement(BoundaryContext);
1254 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
1255}
1256
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001257void Scop::addUserContext() {
1258 if (UserContextStr.empty())
1259 return;
1260
1261 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1262 isl_space *Space = getParamSpace();
1263 if (isl_space_dim(Space, isl_dim_param) !=
1264 isl_set_dim(UserContext, isl_dim_param)) {
1265 auto SpaceStr = isl_space_to_str(Space);
1266 errs() << "Error: the context provided in -polly-context has not the same "
1267 << "number of dimensions than the computed context. Due to this "
1268 << "mismatch, the -polly-context option is ignored. Please provide "
1269 << "the context in the parameter space: " << SpaceStr << ".\n";
1270 free(SpaceStr);
1271 isl_set_free(UserContext);
1272 isl_space_free(Space);
1273 return;
1274 }
1275
1276 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1277 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1278 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1279
1280 if (strcmp(NameContext, NameUserContext) != 0) {
1281 auto SpaceStr = isl_space_to_str(Space);
1282 errs() << "Error: the name of dimension " << i
1283 << " provided in -polly-context "
1284 << "is '" << NameUserContext << "', but the name in the computed "
1285 << "context is '" << NameContext
1286 << "'. Due to this name mismatch, "
1287 << "the -polly-context option is ignored. Please provide "
1288 << "the context in the parameter space: " << SpaceStr << ".\n";
1289 free(SpaceStr);
1290 isl_set_free(UserContext);
1291 isl_space_free(Space);
1292 return;
1293 }
1294
1295 UserContext =
1296 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1297 isl_space_get_dim_id(Space, isl_dim_param, i));
1298 }
1299
1300 Context = isl_set_intersect(Context, UserContext);
1301 isl_space_free(Space);
1302}
1303
Tobias Grosser6be480c2011-11-08 15:41:13 +00001304void Scop::buildContext() {
1305 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001306 Context = isl_set_universe(isl_space_copy(Space));
1307 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001308}
1309
Tobias Grosser18daaca2012-05-22 10:47:27 +00001310void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001311 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001312 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001313
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001314 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001315
Johannes Doerferte7044942015-02-24 11:58:30 +00001316 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001317 }
1318}
1319
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001320void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001321 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001322 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001323
Tobias Grosser083d3d32014-06-28 08:59:45 +00001324 for (const auto &ParamID : ParameterIds) {
1325 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001326 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001327 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001328 }
1329
1330 // Align the parameters of all data structures to the model.
1331 Context = isl_set_align_params(Context, Space);
1332
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001333 for (ScopStmt &Stmt : *this)
1334 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001335}
1336
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001337static __isl_give isl_set *
1338simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1339 const Scop &S) {
1340 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1341 AssumptionContext = isl_set_gist_params(AssumptionContext, DomainParameters);
1342 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1343 return AssumptionContext;
1344}
1345
1346void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001347 // The parameter constraints of the iteration domains give us a set of
1348 // constraints that need to hold for all cases where at least a single
1349 // statement iteration is executed in the whole scop. We now simplify the
1350 // assumed context under the assumption that such constraints hold and at
1351 // least a single statement iteration is executed. For cases where no
1352 // statement instances are executed, the assumptions we have taken about
1353 // the executed code do not matter and can be changed.
1354 //
1355 // WARNING: This only holds if the assumptions we have taken do not reduce
1356 // the set of statement instances that are executed. Otherwise we
1357 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001358 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001359 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001360 // performed. In such a case, modifying the run-time conditions and
1361 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001362 // to not be executed.
1363 //
1364 // Example:
1365 //
1366 // When delinearizing the following code:
1367 //
1368 // for (long i = 0; i < 100; i++)
1369 // for (long j = 0; j < m; j++)
1370 // A[i+p][j] = 1.0;
1371 //
1372 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001373 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001374 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001375 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1376 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001377}
1378
Johannes Doerfertb164c792014-09-18 11:17:17 +00001379/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001380static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001381 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1382 isl_pw_multi_aff *MinPMA, *MaxPMA;
1383 isl_pw_aff *LastDimAff;
1384 isl_aff *OneAff;
1385 unsigned Pos;
1386
Johannes Doerfert9143d672014-09-27 11:02:39 +00001387 // Restrict the number of parameters involved in the access as the lexmin/
1388 // lexmax computation will take too long if this number is high.
1389 //
1390 // Experiments with a simple test case using an i7 4800MQ:
1391 //
1392 // #Parameters involved | Time (in sec)
1393 // 6 | 0.01
1394 // 7 | 0.04
1395 // 8 | 0.12
1396 // 9 | 0.40
1397 // 10 | 1.54
1398 // 11 | 6.78
1399 // 12 | 30.38
1400 //
1401 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1402 unsigned InvolvedParams = 0;
1403 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1404 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1405 InvolvedParams++;
1406
1407 if (InvolvedParams > RunTimeChecksMaxParameters) {
1408 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001409 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001410 }
1411 }
1412
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001413 Set = isl_set_remove_divs(Set);
1414
Johannes Doerfertb164c792014-09-18 11:17:17 +00001415 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1416 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1417
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001418 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1419 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1420
Johannes Doerfertb164c792014-09-18 11:17:17 +00001421 // Adjust the last dimension of the maximal access by one as we want to
1422 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1423 // we test during code generation might now point after the end of the
1424 // allocated array but we will never dereference it anyway.
1425 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1426 "Assumed at least one output dimension");
1427 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1428 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1429 OneAff = isl_aff_zero_on_domain(
1430 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1431 OneAff = isl_aff_add_constant_si(OneAff, 1);
1432 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1433 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1434
1435 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1436
1437 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001438 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001439}
1440
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001441static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1442 isl_set *Domain = MA->getStatement()->getDomain();
1443 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1444 return isl_set_reset_tuple_id(Domain);
1445}
1446
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001447/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1448static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001449 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001450 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001451
1452 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1453 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001454 Locations = isl_union_set_coalesce(Locations);
1455 Locations = isl_union_set_detect_equalities(Locations);
1456 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001457 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001458 isl_union_set_free(Locations);
1459 return Valid;
1460}
1461
Johannes Doerfert96425c22015-08-30 21:13:53 +00001462/// @brief Helper to treat non-affine regions and basic blocks the same.
1463///
1464///{
1465
1466/// @brief Return the block that is the representing block for @p RN.
1467static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1468 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1469 : RN->getNodeAs<BasicBlock>();
1470}
1471
1472/// @brief Return the @p idx'th block that is executed after @p RN.
1473static inline BasicBlock *getRegionNodeSuccessor(RegionNode *RN, BranchInst *BI,
1474 unsigned idx) {
1475 if (RN->isSubRegion()) {
1476 assert(idx == 0);
1477 return RN->getNodeAs<Region>()->getExit();
1478 }
1479 return BI->getSuccessor(idx);
1480}
1481
1482/// @brief Return the smallest loop surrounding @p RN.
1483static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1484 if (!RN->isSubRegion())
1485 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1486
1487 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1488 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1489 while (L && NonAffineSubRegion->contains(L))
1490 L = L->getParentLoop();
1491 return L;
1492}
1493
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001494static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1495 if (!RN->isSubRegion())
1496 return 1;
1497
1498 unsigned NumBlocks = 0;
1499 Region *R = RN->getNodeAs<Region>();
1500 for (auto BB : R->blocks()) {
1501 (void)BB;
1502 NumBlocks++;
1503 }
1504 return NumBlocks;
1505}
1506
Johannes Doerfert96425c22015-08-30 21:13:53 +00001507///}
1508
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001509static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1510 unsigned Dim, Loop *L) {
1511 isl_id *DimId =
1512 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
1513 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
1514}
1515
Johannes Doerfert96425c22015-08-30 21:13:53 +00001516isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1517 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1518 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00001519 return getDomainConditions(BB);
1520}
1521
1522isl_set *Scop::getDomainConditions(BasicBlock *BB) {
1523 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001524 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001525}
1526
1527void Scop::buildDomains(Region *R, LoopInfo &LI, ScopDetection &SD,
1528 DominatorTree &DT) {
1529
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001530 auto *EntryBB = R->getEntry();
1531 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
1532 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001533
1534 Loop *L = LI.getLoopFor(EntryBB);
1535 while (LD-- >= 0) {
1536 S = addDomainDimId(S, LD + 1, L);
1537 L = L->getParentLoop();
1538 }
1539
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001540 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001541
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00001542 if (SD.isNonAffineSubRegion(R, R))
1543 return;
1544
Johannes Doerfert96425c22015-08-30 21:13:53 +00001545 buildDomainsWithBranchConstraints(R, LI, SD, DT);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001546 addLoopBoundsToHeaderDomains(LI, SD, DT);
1547 propagateDomainConstraints(R, LI, SD, DT);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001548}
1549
1550void Scop::buildDomainsWithBranchConstraints(Region *R, LoopInfo &LI,
1551 ScopDetection &SD,
1552 DominatorTree &DT) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001553 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00001554
1555 // To create the domain for each block in R we iterate over all blocks and
1556 // subregions in R and propagate the conditions under which the current region
1557 // element is executed. To this end we iterate in reverse post order over R as
1558 // it ensures that we first visit all predecessors of a region node (either a
1559 // basic block or a subregion) before we visit the region node itself.
1560 // Initially, only the domain for the SCoP region entry block is set and from
1561 // there we propagate the current domain to all successors, however we add the
1562 // condition that the successor is actually executed next.
1563 // As we are only interested in non-loop carried constraints here we can
1564 // simply skip loop back edges.
1565
1566 ReversePostOrderTraversal<Region *> RTraversal(R);
1567 for (auto *RN : RTraversal) {
1568
1569 // Recurse for affine subregions but go on for basic blocks and non-affine
1570 // subregions.
1571 if (RN->isSubRegion()) {
1572 Region *SubRegion = RN->getNodeAs<Region>();
1573 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
1574 buildDomainsWithBranchConstraints(SubRegion, LI, SD, DT);
1575 continue;
1576 }
1577 }
1578
1579 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001580 TerminatorInst *TI = BB->getTerminator();
1581
1582 // Unreachable instructions do not have successors so we can skip them.
1583 if (isa<UnreachableInst>(TI)) {
1584 // Assume unreachables only in error blocks.
1585 assert(isErrorBlock(*BB));
1586 continue;
1587 }
1588
Johannes Doerfert96425c22015-08-30 21:13:53 +00001589 isl_set *Domain = DomainMap[BB];
1590 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
1591 assert(Domain && "Due to reverse post order traversal of the region all "
1592 "predecessor of the current region node should have been "
1593 "visited and a domain for this region node should have "
1594 "been set.");
1595
1596 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1597 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1598
1599 // Build the condition sets for the successor nodes of the current region
1600 // node. If it is a non-affine subregion we will always execute the single
1601 // exit node, hence the single entry node domain is the condition set. For
1602 // basic blocks we use the helper function buildConditionSets.
1603 SmallVector<isl_set *, 2> ConditionSets;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001604 BranchInst *BI = cast<BranchInst>(TI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001605 if (RN->isSubRegion())
1606 ConditionSets.push_back(isl_set_copy(Domain));
1607 else
1608 buildConditionSets(*this, BI, BBLoop, Domain, ConditionSets);
1609
1610 // Now iterate over the successors and set their initial domain based on
1611 // their condition set. We skip back edges here and have to be careful when
1612 // we leave a loop not to keep constraints over a dimension that doesn't
1613 // exist anymore.
1614 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
1615 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, BI, u);
1616 isl_set *CondSet = ConditionSets[u];
1617
1618 // Skip back edges.
1619 if (DT.dominates(SuccBB, BB)) {
1620 isl_set_free(CondSet);
1621 continue;
1622 }
1623
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001624 // Do not adjust the number of dimensions if we enter a boxed loop or are
1625 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001626 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001627 Region *SuccRegion = RI.getRegionFor(SuccBB);
1628 if (BBLoop != SuccBBLoop && !RN->isSubRegion() &&
1629 !(SD.isNonAffineSubRegion(SuccRegion, &getRegion()) &&
1630 SuccRegion->contains(SuccBBLoop))) {
1631
1632 // Check if the edge to SuccBB is a loop entry or exit edge. If so
1633 // adjust the dimensionality accordingly. Lastly, if we leave a loop
1634 // and enter a new one we need to drop the old constraints.
1635 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001636 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001637 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001638 CondSet = isl_set_project_out(CondSet, isl_dim_set,
1639 isl_set_n_dim(CondSet) - LoopDepthDiff,
1640 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001641 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001642 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001643 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001644 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001645 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001646 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001647 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
1648 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001649 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001650 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00001651 }
1652
1653 // Set the domain for the successor or merge it with an existing domain in
1654 // case there are multiple paths (without loop back edges) to the
1655 // successor block.
1656 isl_set *&SuccDomain = DomainMap[SuccBB];
1657 if (!SuccDomain)
1658 SuccDomain = CondSet;
1659 else
1660 SuccDomain = isl_set_union(SuccDomain, CondSet);
1661
1662 SuccDomain = isl_set_coalesce(SuccDomain);
1663 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : " << Domain
1664 << "\n");
1665 }
1666 }
1667}
1668
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001669/// @brief Return the domain for @p BB wrt @p DomainMap.
1670///
1671/// This helper function will lookup @p BB in @p DomainMap but also handle the
1672/// case where @p BB is contained in a non-affine subregion using the region
1673/// tree obtained by @p RI.
1674static __isl_give isl_set *
1675getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
1676 RegionInfo &RI) {
1677 auto DIt = DomainMap.find(BB);
1678 if (DIt != DomainMap.end())
1679 return isl_set_copy(DIt->getSecond());
1680
1681 Region *R = RI.getRegionFor(BB);
1682 while (R->getEntry() == BB)
1683 R = R->getParent();
1684 return getDomainForBlock(R->getEntry(), DomainMap, RI);
1685}
1686
Johannes Doerferte114dc02015-09-14 11:15:58 +00001687static bool containsErrorBlock(RegionNode *RN) {
1688 if (!RN->isSubRegion())
1689 return isErrorBlock(*RN->getNodeAs<BasicBlock>());
1690 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
1691 if (isErrorBlock(*BB))
1692 return true;
1693 return false;
1694}
1695
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001696void Scop::propagateDomainConstraints(Region *R, LoopInfo &LI,
1697 ScopDetection &SD, DominatorTree &DT) {
1698 // Iterate over the region R and propagate the domain constrains from the
1699 // predecessors to the current node. In contrast to the
1700 // buildDomainsWithBranchConstraints function, this one will pull the domain
1701 // information from the predecessors instead of pushing it to the successors.
1702 // Additionally, we assume the domains to be already present in the domain
1703 // map here. However, we iterate again in reverse post order so we know all
1704 // predecessors have been visited before a block or non-affine subregion is
1705 // visited.
1706
1707 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
1708 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
1709
1710 ReversePostOrderTraversal<Region *> RTraversal(R);
1711 for (auto *RN : RTraversal) {
1712
1713 // Recurse for affine subregions but go on for basic blocks and non-affine
1714 // subregions.
1715 if (RN->isSubRegion()) {
1716 Region *SubRegion = RN->getNodeAs<Region>();
1717 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
1718 propagateDomainConstraints(SubRegion, LI, SD, DT);
1719 continue;
1720 }
1721 }
1722
1723 BasicBlock *BB = getRegionNodeBasicBlock(RN);
1724 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1725 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1726
1727 isl_set *&Domain = DomainMap[BB];
1728 assert(Domain && "Due to reverse post order traversal of the region all "
1729 "predecessor of the current region node should have been "
1730 "visited and a domain for this region node should have "
1731 "been set.");
1732
1733 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
1734 for (auto *PredBB : predecessors(BB)) {
1735
1736 // Skip backedges
1737 if (DT.dominates(BB, PredBB))
1738 continue;
1739
1740 isl_set *PredBBDom = nullptr;
1741
1742 // Handle the SCoP entry block with its outside predecessors.
1743 if (!getRegion().contains(PredBB))
1744 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
1745
1746 if (!PredBBDom) {
1747 // Determine the loop depth of the predecessor and adjust its domain to
1748 // the domain of the current block. This can mean we have to:
1749 // o) Drop a dimension if this block is the exit of a loop, not the
1750 // header of a new loop and the predecessor was part of the loop.
1751 // o) Add an unconstrainted new dimension if this block is the header
1752 // of a loop and the predecessor is not part of it.
1753 // o) Drop the information about the innermost loop dimension when the
1754 // predecessor and the current block are surrounded by different
1755 // loops in the same depth.
1756 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
1757 Loop *PredBBLoop = LI.getLoopFor(PredBB);
1758 while (BoxedLoops.count(PredBBLoop))
1759 PredBBLoop = PredBBLoop->getParentLoop();
1760
1761 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001762 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001763 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001764 PredBBDom = isl_set_project_out(
1765 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
1766 LoopDepthDiff);
1767 else if (PredBBLoopDepth < BBLoopDepth) {
1768 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001769 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001770 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
1771 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001772 PredBBDom = isl_set_drop_constraints_involving_dims(
1773 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001774 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001775 }
1776
1777 PredDom = isl_set_union(PredDom, PredBBDom);
1778 }
1779
1780 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00001781 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001782
1783 // Add assumptions for error blocks.
Johannes Doerferte114dc02015-09-14 11:15:58 +00001784 if (containsErrorBlock(RN)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001785 IsOptimized = true;
1786 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
1787 addAssumption(isl_set_complement(DomPar));
1788 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001789 }
1790}
1791
1792/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
1793/// is incremented by one and all other dimensions are equal, e.g.,
1794/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
1795/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
1796static __isl_give isl_map *
1797createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
1798 auto *MapSpace = isl_space_map_from_set(SetSpace);
1799 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
1800 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
1801 if (u != Dim)
1802 NextIterationMap =
1803 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
1804 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
1805 C = isl_constraint_set_constant_si(C, 1);
1806 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
1807 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
1808 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
1809 return NextIterationMap;
1810}
1811
1812/// @brief Add @p L & all children to @p Loops if they are not in @p BoxedLoops.
1813static inline void
1814addLoopAndSubloops(Loop *L, SmallVectorImpl<Loop *> &Loops,
1815 const ScopDetection::BoxedLoopsSetTy &BoxedLoops) {
1816 if (BoxedLoops.count(L))
1817 return;
1818
1819 Loops.push_back(L);
1820 for (Loop *Subloop : *L)
1821 addLoopAndSubloops(Subloop, Loops, BoxedLoops);
1822}
1823
1824/// @brief Add loops in @p R to @p RegionLoops if they are not in @p BoxedLoops.
1825static inline void
1826collectLoopsInRegion(Region &R, LoopInfo &LI,
1827 SmallVector<Loop *, 8> &RegionLoops,
1828 const ScopDetection::BoxedLoopsSetTy &BoxedLoops) {
1829
1830 SmallVector<Loop *, 8> Loops(LI.begin(), LI.end());
1831 while (!Loops.empty()) {
1832 Loop *L = Loops.pop_back_val();
1833
1834 if (R.contains(L))
1835 addLoopAndSubloops(L, RegionLoops, BoxedLoops);
1836 else if (L->contains(R.getEntry()))
1837 Loops.append(L->begin(), L->end());
1838 }
1839}
1840
1841/// @brief Create a set from @p Space with @p Dim fixed to 0.
1842static __isl_give isl_set *
1843createFirstIterationDomain(__isl_take isl_space *Space, unsigned Dim) {
1844 auto *Domain = isl_set_universe(Space);
1845 Domain = isl_set_fix_si(Domain, isl_dim_set, Dim, 0);
1846 return Domain;
1847}
1848
1849void Scop::addLoopBoundsToHeaderDomains(LoopInfo &LI, ScopDetection &SD,
1850 DominatorTree &DT) {
1851 // We iterate over all loops in the SCoP, create the condition set under which
1852 // we will take the back edge, and then apply these restrictions to the
1853 // header.
1854
1855 Region &R = getRegion();
1856 SmallVector<Loop *, 8> RegionLoops;
1857 collectLoopsInRegion(R, LI, RegionLoops, *SD.getBoxedLoops(&R));
1858
1859 while (!RegionLoops.empty()) {
1860 Loop *L = RegionLoops.pop_back_val();
1861 int LoopDepth = getRelativeLoopDepth(L);
1862 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
1863
1864 BasicBlock *LatchBB = L->getLoopLatch();
1865 assert(LatchBB && "TODO implement multiple exit loop handling");
1866
1867 isl_set *LatchBBDom = DomainMap[LatchBB];
1868 isl_set *BackedgeCondition = nullptr;
1869
1870 BasicBlock *HeaderBB = L->getHeader();
1871
1872 BranchInst *BI = cast<BranchInst>(LatchBB->getTerminator());
1873 if (BI->isUnconditional())
1874 BackedgeCondition = isl_set_copy(LatchBBDom);
1875 else {
1876 SmallVector<isl_set *, 2> ConditionSets;
1877 int idx = BI->getSuccessor(0) != HeaderBB;
1878 buildConditionSets(*this, BI, L, LatchBBDom, ConditionSets);
1879
1880 // Free the non back edge condition set as we do not need it.
1881 isl_set_free(ConditionSets[1 - idx]);
1882
1883 BackedgeCondition = ConditionSets[idx];
1884 }
1885
1886 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
1887 isl_set *FirstIteration =
1888 createFirstIterationDomain(isl_set_get_space(HeaderBBDom), LoopDepth);
1889
1890 isl_map *NextIterationMap =
1891 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
1892
1893 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
1894 assert(LatchLoopDepth >= LoopDepth);
1895 BackedgeCondition =
1896 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
1897 LatchLoopDepth - LoopDepth);
1898
Johannes Doerfertca1e38f2015-09-14 11:12:52 +00001899 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
1900 for (int i = 0; i < LoopDepth; i++)
1901 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
1902
1903 isl_set *BackedgeConditionComplement =
1904 isl_set_complement(BackedgeCondition);
1905 BackedgeConditionComplement = isl_set_lower_bound_si(
1906 BackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
1907 BackedgeConditionComplement =
1908 isl_set_apply(BackedgeConditionComplement, ForwardMap);
1909 HeaderBBDom = isl_set_subtract(HeaderBBDom, BackedgeConditionComplement);
1910
1911 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001912
1913 // If a loop has an unbounded back edge condition part (here Parts.first)
1914 // we do not want to assume the header will even be executed for the first
1915 // iteration of an execution that will lead to an infinite loop. While it
1916 // would not be wrong to do so, it does not seem helpful.
Johannes Doerfertca1e38f2015-09-14 11:12:52 +00001917 // TODO: Use the unbounded part to build runtime assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001918 FirstIteration = isl_set_subtract(FirstIteration, Parts.first);
1919
Johannes Doerfertca1e38f2015-09-14 11:12:52 +00001920 HeaderBBDom = isl_set_apply(Parts.second, NextIterationMap);
1921 HeaderBBDom = isl_set_coalesce(isl_set_union(HeaderBBDom, FirstIteration));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001922 }
1923}
1924
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001925void Scop::buildAliasChecks(AliasAnalysis &AA) {
1926 if (!PollyUseRuntimeAliasChecks)
1927 return;
1928
1929 if (buildAliasGroups(AA))
1930 return;
1931
1932 // If a problem occurs while building the alias groups we need to delete
1933 // this SCoP and pretend it wasn't valid in the first place. To this end
1934 // we make the assumed context infeasible.
1935 addAssumption(isl_set_empty(getParamSpace()));
1936
1937 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
1938 << " could not be created as the number of parameters involved "
1939 "is too high. The SCoP will be "
1940 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
1941 "the maximal number of parameters but be advised that the "
1942 "compile time might increase exponentially.\n\n");
1943}
1944
Johannes Doerfert9143d672014-09-27 11:02:39 +00001945bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001946 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001947 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00001948 // for all memory accesses inside the SCoP.
1949 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001950 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00001951 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001952 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001953 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001954 // if their access domains intersect, otherwise they are in different
1955 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001956 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001957 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001958 // and maximal accesses to each array of a group in read only and non
1959 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00001960 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
1961
1962 AliasSetTracker AST(AA);
1963
1964 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00001965 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001966 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001967
1968 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001969 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001970 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
1971 isl_set_free(StmtDomain);
1972 if (StmtDomainEmpty)
1973 continue;
1974
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001975 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001976 if (MA->isScalar())
1977 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00001978 if (!MA->isRead())
1979 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001980 Instruction *Acc = MA->getAccessInstruction();
1981 PtrToAcc[getPointerOperand(*Acc)] = MA;
1982 AST.add(Acc);
1983 }
1984 }
1985
1986 SmallVector<AliasGroupTy, 4> AliasGroups;
1987 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00001988 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00001989 continue;
1990 AliasGroupTy AG;
1991 for (auto PR : AS)
1992 AG.push_back(PtrToAcc[PR.getValue()]);
1993 assert(AG.size() > 1 &&
1994 "Alias groups should contain at least two accesses");
1995 AliasGroups.push_back(std::move(AG));
1996 }
1997
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001998 // Split the alias groups based on their domain.
1999 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2000 AliasGroupTy NewAG;
2001 AliasGroupTy &AG = AliasGroups[u];
2002 AliasGroupTy::iterator AGI = AG.begin();
2003 isl_set *AGDomain = getAccessDomain(*AGI);
2004 while (AGI != AG.end()) {
2005 MemoryAccess *MA = *AGI;
2006 isl_set *MADomain = getAccessDomain(MA);
2007 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2008 NewAG.push_back(MA);
2009 AGI = AG.erase(AGI);
2010 isl_set_free(MADomain);
2011 } else {
2012 AGDomain = isl_set_union(AGDomain, MADomain);
2013 AGI++;
2014 }
2015 }
2016 if (NewAG.size() > 1)
2017 AliasGroups.push_back(std::move(NewAG));
2018 isl_set_free(AGDomain);
2019 }
2020
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002021 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002022 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2023 for (AliasGroupTy &AG : AliasGroups) {
2024 NonReadOnlyBaseValues.clear();
2025 ReadOnlyPairs.clear();
2026
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002027 if (AG.size() < 2) {
2028 AG.clear();
2029 continue;
2030 }
2031
Johannes Doerfert13771732014-10-01 12:40:46 +00002032 for (auto II = AG.begin(); II != AG.end();) {
2033 Value *BaseAddr = (*II)->getBaseAddr();
2034 if (HasWriteAccess.count(BaseAddr)) {
2035 NonReadOnlyBaseValues.insert(BaseAddr);
2036 II++;
2037 } else {
2038 ReadOnlyPairs[BaseAddr].insert(*II);
2039 II = AG.erase(II);
2040 }
2041 }
2042
2043 // If we don't have read only pointers check if there are at least two
2044 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002045 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002046 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002047 continue;
2048 }
2049
2050 // If we don't have non read only pointers clear the alias group.
2051 if (NonReadOnlyBaseValues.empty()) {
2052 AG.clear();
2053 continue;
2054 }
2055
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002056 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002057 MinMaxAliasGroups.emplace_back();
2058 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2059 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2060 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2061 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002062
2063 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002064
2065 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002066 for (MemoryAccess *MA : AG)
2067 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002068
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002069 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2070 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002071
2072 // Bail out if the number of values we need to compare is too large.
2073 // This is important as the number of comparisions grows quadratically with
2074 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002075 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2076 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002077 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002078
2079 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002080 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002081 Accesses = isl_union_map_empty(getParamSpace());
2082
2083 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2084 for (MemoryAccess *MA : ReadOnlyPair.second)
2085 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2086
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002087 Valid =
2088 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002089
2090 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002091 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002092 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002093
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002094 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002095}
2096
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002097static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
2098 Loop *L = LI.getLoopFor(R.getEntry());
2099 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2100}
2101
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002102static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2103 ScopDetection &SD) {
2104
2105 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2106
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002107 unsigned MinLD = INT_MAX, MaxLD = 0;
2108 for (BasicBlock *BB : R.blocks()) {
2109 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002110 if (!R.contains(L))
2111 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002112 if (BoxedLoops && BoxedLoops->count(L))
2113 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002114 unsigned LD = L->getLoopDepth();
2115 MinLD = std::min(MinLD, LD);
2116 MaxLD = std::max(MaxLD, LD);
2117 }
2118 }
2119
2120 // Handle the case that there is no loop in the SCoP first.
2121 if (MaxLD == 0)
2122 return 1;
2123
2124 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2125 assert(MaxLD >= MinLD &&
2126 "Maximal loop depth was smaller than mininaml loop depth?");
2127 return MaxLD - MinLD + 1;
2128}
2129
Michael Kruse9d080092015-09-11 21:41:48 +00002130Scop::Scop(Region &R, AccFuncMapType &AccFuncMap,
2131 ScalarEvolution &ScalarEvolution, DominatorTree &DT,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002132 isl_ctx *Context, unsigned MaxLoopDepth)
Michael Kruse9d080092015-09-11 21:41:48 +00002133 : DT(DT), SE(&ScalarEvolution), R(R), AccFuncMap(AccFuncMap),
2134 IsOptimized(false), HasSingleExitEdge(R.getExitingBlock()),
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002135 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Affinator(this),
2136 BoundaryContext(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002137
Michael Kruse9d080092015-09-11 21:41:48 +00002138void Scop::init(LoopInfo &LI, ScopDetection &SD, AliasAnalysis &AA) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002139 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00002140
Johannes Doerfert96425c22015-08-30 21:13:53 +00002141 buildDomains(&R, LI, SD, DT);
2142
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002143 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
Tobias Grosser75805372011-04-29 06:27:02 +00002144
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002145 Loop *L = getLoopSurroundingRegion(R, LI);
2146 LoopSchedules[L];
Michael Kruse9d080092015-09-11 21:41:48 +00002147 buildSchedule(&R, LI, SD, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002148 Schedule = LoopSchedules[L].first;
Tobias Grosser75805372011-04-29 06:27:02 +00002149
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002150 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002151 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002152 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002153 buildBoundaryContext();
2154 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002155 buildAliasChecks(AA);
Tobias Grosser75805372011-04-29 06:27:02 +00002156}
2157
2158Scop::~Scop() {
2159 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002160 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002161 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002162 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002163
Johannes Doerfert96425c22015-08-30 21:13:53 +00002164 for (auto It : DomainMap)
2165 isl_set_free(It.second);
2166
Johannes Doerfertb164c792014-09-18 11:17:17 +00002167 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002168 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002169 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002170 isl_pw_multi_aff_free(MMA.first);
2171 isl_pw_multi_aff_free(MMA.second);
2172 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002173 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002174 isl_pw_multi_aff_free(MMA.first);
2175 isl_pw_multi_aff_free(MMA.second);
2176 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002177 }
Tobias Grosser75805372011-04-29 06:27:02 +00002178}
2179
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002180const ScopArrayInfo *
2181Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Michael Kruse28468772015-09-14 15:45:33 +00002182 ArrayRef<const SCEV *> Sizes, bool IsPHI) {
Tobias Grosser92245222015-07-28 14:53:44 +00002183 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)];
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002184 if (!SAI)
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002185 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, IsPHI,
2186 this));
Tobias Grosserab671442015-05-23 05:58:27 +00002187 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002188}
2189
Tobias Grosser92245222015-07-28 14:53:44 +00002190const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, bool IsPHI) {
2191 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002192 assert(SAI && "No ScopArrayInfo available for this base pointer");
2193 return SAI;
2194}
2195
Tobias Grosser74394f02013-01-14 22:40:23 +00002196std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002197std::string Scop::getAssumedContextStr() const {
2198 return stringFromIslObj(AssumedContext);
2199}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002200std::string Scop::getBoundaryContextStr() const {
2201 return stringFromIslObj(BoundaryContext);
2202}
Tobias Grosser75805372011-04-29 06:27:02 +00002203
2204std::string Scop::getNameStr() const {
2205 std::string ExitName, EntryName;
2206 raw_string_ostream ExitStr(ExitName);
2207 raw_string_ostream EntryStr(EntryName);
2208
Tobias Grosserf240b482014-01-09 10:42:15 +00002209 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002210 EntryStr.str();
2211
2212 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00002213 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002214 ExitStr.str();
2215 } else
2216 ExitName = "FunctionExit";
2217
2218 return EntryName + "---" + ExitName;
2219}
2220
Tobias Grosser74394f02013-01-14 22:40:23 +00002221__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00002222__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002223 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00002224}
2225
Tobias Grossere86109f2013-10-29 21:05:49 +00002226__isl_give isl_set *Scop::getAssumedContext() const {
2227 return isl_set_copy(AssumedContext);
2228}
2229
Johannes Doerfert43788c52015-08-20 05:58:56 +00002230__isl_give isl_set *Scop::getRuntimeCheckContext() const {
2231 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002232 RuntimeCheckContext =
2233 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
2234 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002235 return RuntimeCheckContext;
2236}
2237
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002238bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002239 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002240 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002241 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
2242 isl_set_free(RuntimeCheckContext);
2243 return IsFeasible;
2244}
2245
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002246void Scop::addAssumption(__isl_take isl_set *Set) {
2247 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00002248 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002249}
2250
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002251__isl_give isl_set *Scop::getBoundaryContext() const {
2252 return isl_set_copy(BoundaryContext);
2253}
2254
Tobias Grosser75805372011-04-29 06:27:02 +00002255void Scop::printContext(raw_ostream &OS) const {
2256 OS << "Context:\n";
2257
2258 if (!Context) {
2259 OS.indent(4) << "n/a\n\n";
2260 return;
2261 }
2262
2263 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00002264
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002265 OS.indent(4) << "Assumed Context:\n";
2266 if (!AssumedContext) {
2267 OS.indent(4) << "n/a\n\n";
2268 return;
2269 }
2270
2271 OS.indent(4) << getAssumedContextStr() << "\n";
2272
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002273 OS.indent(4) << "Boundary Context:\n";
2274 if (!BoundaryContext) {
2275 OS.indent(4) << "n/a\n\n";
2276 return;
2277 }
2278
2279 OS.indent(4) << getBoundaryContextStr() << "\n";
2280
Tobias Grosser083d3d32014-06-28 08:59:45 +00002281 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00002282 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00002283 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
2284 }
Tobias Grosser75805372011-04-29 06:27:02 +00002285}
2286
Johannes Doerfertb164c792014-09-18 11:17:17 +00002287void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002288 int noOfGroups = 0;
2289 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002290 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002291 noOfGroups += 1;
2292 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002293 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002294 }
2295
Tobias Grosserbb853c22015-07-25 12:31:03 +00002296 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00002297 if (MinMaxAliasGroups.empty()) {
2298 OS.indent(8) << "n/a\n";
2299 return;
2300 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002301
Tobias Grosserbb853c22015-07-25 12:31:03 +00002302 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002303
2304 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002305 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002306 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002307 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002308 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2309 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002310 }
2311 OS << " ]]\n";
2312 }
2313
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002314 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002315 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00002316 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002317 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002318 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2319 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002320 }
2321 OS << " ]]\n";
2322 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002323 }
2324}
2325
Tobias Grosser75805372011-04-29 06:27:02 +00002326void Scop::printStatements(raw_ostream &OS) const {
2327 OS << "Statements {\n";
2328
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002329 for (const ScopStmt &Stmt : *this)
2330 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00002331
2332 OS.indent(4) << "}\n";
2333}
2334
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002335void Scop::printArrayInfo(raw_ostream &OS) const {
2336 OS << "Arrays {\n";
2337
Tobias Grosserab671442015-05-23 05:58:27 +00002338 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002339 Array.second->print(OS);
2340
2341 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002342
2343 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
2344
2345 for (auto &Array : arrays())
2346 Array.second->print(OS, /* SizeAsPwAff */ true);
2347
2348 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002349}
2350
Tobias Grosser75805372011-04-29 06:27:02 +00002351void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00002352 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
2353 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00002354 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00002355 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00002356 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002357 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002358 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00002359 printStatements(OS.indent(4));
2360}
2361
2362void Scop::dump() const { print(dbgs()); }
2363
Tobias Grosser9a38ab82011-11-08 15:41:03 +00002364isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00002365
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002366__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
2367 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00002368}
2369
Tobias Grosser808cd692015-07-14 09:33:13 +00002370__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002371 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002372
Tobias Grosser808cd692015-07-14 09:33:13 +00002373 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002374 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002375
2376 return Domain;
2377}
2378
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002379__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002380 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002381
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002382 for (ScopStmt &Stmt : *this) {
2383 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002384 if (!MA->isMustWrite())
2385 continue;
2386
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002387 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002388 isl_map *AccessDomain = MA->getAccessRelation();
2389 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2390 Write = isl_union_map_add_map(Write, AccessDomain);
2391 }
2392 }
2393 return isl_union_map_coalesce(Write);
2394}
2395
2396__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002397 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002398
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002399 for (ScopStmt &Stmt : *this) {
2400 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002401 if (!MA->isMayWrite())
2402 continue;
2403
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002404 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002405 isl_map *AccessDomain = MA->getAccessRelation();
2406 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2407 Write = isl_union_map_add_map(Write, AccessDomain);
2408 }
2409 }
2410 return isl_union_map_coalesce(Write);
2411}
2412
Tobias Grosser37eb4222014-02-20 21:43:54 +00002413__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002414 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002415
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002416 for (ScopStmt &Stmt : *this) {
2417 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002418 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002419 continue;
2420
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002421 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002422 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002423 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2424 Write = isl_union_map_add_map(Write, AccessDomain);
2425 }
2426 }
2427 return isl_union_map_coalesce(Write);
2428}
2429
2430__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002431 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002432
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002433 for (ScopStmt &Stmt : *this) {
2434 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002435 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002436 continue;
2437
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002438 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002439 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002440
2441 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2442 Read = isl_union_map_add_map(Read, AccessDomain);
2443 }
2444 }
2445 return isl_union_map_coalesce(Read);
2446}
2447
Tobias Grosser808cd692015-07-14 09:33:13 +00002448__isl_give isl_union_map *Scop::getSchedule() const {
2449 auto Tree = getScheduleTree();
2450 auto S = isl_schedule_get_map(Tree);
2451 isl_schedule_free(Tree);
2452 return S;
2453}
Tobias Grosser37eb4222014-02-20 21:43:54 +00002454
Tobias Grosser808cd692015-07-14 09:33:13 +00002455__isl_give isl_schedule *Scop::getScheduleTree() const {
2456 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
2457 getDomains());
2458}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002459
Tobias Grosser808cd692015-07-14 09:33:13 +00002460void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
2461 auto *S = isl_schedule_from_domain(getDomains());
2462 S = isl_schedule_insert_partial_schedule(
2463 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
2464 isl_schedule_free(Schedule);
2465 Schedule = S;
2466}
2467
2468void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
2469 isl_schedule_free(Schedule);
2470 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00002471}
2472
2473bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
2474 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002475 for (ScopStmt &Stmt : *this) {
2476 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002477 isl_union_set *NewStmtDomain = isl_union_set_intersect(
2478 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
2479
2480 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
2481 isl_union_set_free(StmtDomain);
2482 isl_union_set_free(NewStmtDomain);
2483 continue;
2484 }
2485
2486 Changed = true;
2487
2488 isl_union_set_free(StmtDomain);
2489 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
2490
2491 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002492 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002493 isl_union_set_free(NewStmtDomain);
2494 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002495 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002496 }
2497 isl_union_set_free(Domain);
2498 return Changed;
2499}
2500
Tobias Grosser75805372011-04-29 06:27:02 +00002501ScalarEvolution *Scop::getSE() const { return SE; }
2502
Michael Kruse9d080092015-09-11 21:41:48 +00002503bool Scop::isTrivialBB(BasicBlock *BB) {
2504 if (getAccessFunctions(BB) && !isErrorBlock(*BB))
Tobias Grosser75805372011-04-29 06:27:02 +00002505 return false;
2506
2507 return true;
2508}
2509
Tobias Grosser808cd692015-07-14 09:33:13 +00002510struct MapToDimensionDataTy {
2511 int N;
2512 isl_union_pw_multi_aff *Res;
2513};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002514
Tobias Grosser808cd692015-07-14 09:33:13 +00002515// @brief Create a function that maps the elements of 'Set' to its N-th
2516// dimension.
2517//
2518// The result is added to 'User->Res'.
2519//
2520// @param Set The input set.
2521// @param N The dimension to map to.
2522//
2523// @returns Zero if no error occurred, non-zero otherwise.
2524static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
2525 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
2526 int Dim;
2527 isl_space *Space;
2528 isl_pw_multi_aff *PMA;
2529
2530 Dim = isl_set_dim(Set, isl_dim_set);
2531 Space = isl_set_get_space(Set);
2532 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
2533 Dim - Data->N);
2534 if (Data->N > 1)
2535 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
2536 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
2537
2538 isl_set_free(Set);
2539
2540 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002541}
2542
Tobias Grosser808cd692015-07-14 09:33:13 +00002543// @brief Create a function that maps the elements of Domain to their Nth
2544// dimension.
2545//
2546// @param Domain The set of elements to map.
2547// @param N The dimension to map to.
2548static __isl_give isl_multi_union_pw_aff *
2549mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002550 if (N <= 0 || isl_union_set_is_empty(Domain)) {
2551 isl_union_set_free(Domain);
2552 return nullptr;
2553 }
2554
Tobias Grosser808cd692015-07-14 09:33:13 +00002555 struct MapToDimensionDataTy Data;
2556 isl_space *Space;
2557
2558 Space = isl_union_set_get_space(Domain);
2559 Data.N = N;
2560 Data.Res = isl_union_pw_multi_aff_empty(Space);
2561 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
2562 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
2563
2564 isl_union_set_free(Domain);
2565 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
2566}
2567
Michael Kruse9d080092015-09-11 21:41:48 +00002568ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00002569 ScopStmt *Stmt;
2570 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00002571 Stmts.emplace_back(*this, *BB);
Tobias Grosser808cd692015-07-14 09:33:13 +00002572 Stmt = &Stmts.back();
2573 StmtMap[BB] = Stmt;
2574 } else {
2575 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00002576 Stmts.emplace_back(*this, *R);
Tobias Grosser808cd692015-07-14 09:33:13 +00002577 Stmt = &Stmts.back();
2578 for (BasicBlock *BB : R->blocks())
2579 StmtMap[BB] = Stmt;
2580 }
2581 return Stmt;
2582}
2583
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002584void Scop::buildSchedule(
Michael Kruse9d080092015-09-11 21:41:48 +00002585 Region *R, LoopInfo &LI, ScopDetection &SD,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002586 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00002587
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002588 if (SD.isNonAffineSubRegion(R, &getRegion())) {
2589 auto *Stmt = addScopStmt(nullptr, R);
2590 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
2591 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
2592 auto &LSchedulePair = LoopSchedules[nullptr];
2593 LSchedulePair.first = StmtSchedule;
2594 return;
2595 }
2596
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002597 ReversePostOrderTraversal<Region *> RTraversal(R);
2598 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00002599
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002600 if (RN->isSubRegion()) {
2601 Region *SubRegion = RN->getNodeAs<Region>();
2602 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Michael Kruse9d080092015-09-11 21:41:48 +00002603 buildSchedule(SubRegion, LI, SD, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002604 continue;
2605 }
Tobias Grosser75805372011-04-29 06:27:02 +00002606 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002607
2608 Loop *L = getRegionNodeLoop(RN, LI);
2609 int LD = getRelativeLoopDepth(L);
2610 auto &LSchedulePair = LoopSchedules[L];
2611 LSchedulePair.second += getNumBlocksInRegionNode(RN);
2612
2613 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Michael Kruse9d080092015-09-11 21:41:48 +00002614 if (RN->isSubRegion() || !isTrivialBB(BB)) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002615
2616 ScopStmt *Stmt;
2617 if (RN->isSubRegion())
Michael Kruse9d080092015-09-11 21:41:48 +00002618 Stmt = addScopStmt(nullptr, RN->getNodeAs<Region>());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002619 else
Michael Kruse9d080092015-09-11 21:41:48 +00002620 Stmt = addScopStmt(BB, nullptr);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002621
2622 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
2623 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
2624 LSchedulePair.first =
2625 combineInSequence(LSchedulePair.first, StmtSchedule);
2626 }
2627
2628 unsigned NumVisited = LSchedulePair.second;
2629 while (L && NumVisited == L->getNumBlocks()) {
2630 auto *LDomain = isl_schedule_get_domain(LSchedulePair.first);
2631 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
2632 LSchedulePair.first =
2633 isl_schedule_insert_partial_schedule(LSchedulePair.first, MUPA);
2634
2635 auto *PL = L->getParentLoop();
2636 assert(LoopSchedules.count(PL));
2637 auto &PSchedulePair = LoopSchedules[PL];
2638 PSchedulePair.first =
2639 combineInSequence(PSchedulePair.first, LSchedulePair.first);
2640 PSchedulePair.second += NumVisited;
2641
2642 L = PL;
2643 NumVisited = PSchedulePair.second;
2644 }
Tobias Grosser808cd692015-07-14 09:33:13 +00002645 }
Tobias Grosser75805372011-04-29 06:27:02 +00002646}
2647
Johannes Doerfert7c494212014-10-31 23:13:39 +00002648ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00002649 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00002650 if (StmtMapIt == StmtMap.end())
2651 return nullptr;
2652 return StmtMapIt->second;
2653}
2654
Michael Kruse9d080092015-09-11 21:41:48 +00002655void Scop::printIRAccesses(raw_ostream &OS, ScalarEvolution *SE,
2656 LoopInfo *LI) const {
Michael Kruse7bf39442015-09-10 12:46:52 +00002657 OS << "Scop: " << R.getNameStr() << "\n";
2658
Michael Kruse9d080092015-09-11 21:41:48 +00002659 printIRAccessesDetail(OS, SE, LI, &R, 0);
Michael Kruse7bf39442015-09-10 12:46:52 +00002660}
2661
Michael Kruse9d080092015-09-11 21:41:48 +00002662void Scop::printIRAccessesDetail(raw_ostream &OS, ScalarEvolution *SE,
2663 LoopInfo *LI, const Region *CurR,
2664 unsigned ind) const {
Michael Kruse7bf39442015-09-10 12:46:52 +00002665 // FIXME: Print other details rather than memory accesses.
2666 for (const auto &CurBlock : CurR->blocks()) {
2667 AccFuncMapType::const_iterator AccSetIt = AccFuncMap.find(CurBlock);
2668
2669 // Ignore trivial blocks that do not contain any memory access.
2670 if (AccSetIt == AccFuncMap.end())
2671 continue;
2672
2673 OS.indent(ind) << "BB: " << CurBlock->getName() << '\n';
2674 typedef AccFuncSetType::const_iterator access_iterator;
2675 const AccFuncSetType &AccFuncs = AccSetIt->second;
2676
2677 for (access_iterator AI = AccFuncs.begin(), AE = AccFuncs.end(); AI != AE;
2678 ++AI)
2679 AI->first.print(OS.indent(ind + 2));
2680 }
2681}
2682
Johannes Doerfert96425c22015-08-30 21:13:53 +00002683int Scop::getRelativeLoopDepth(const Loop *L) const {
2684 Loop *OuterLoop =
2685 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
2686 if (!OuterLoop)
2687 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00002688 return L->getLoopDepth() - OuterLoop->getLoopDepth();
2689}
2690
Michael Krused868b5d2015-09-10 15:25:24 +00002691void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
2692 AccFuncSetType &Functions,
2693 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002694
2695 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
2696 // true, are not modeled as ordinary PHI nodes as they are not part of the
2697 // region. However, we model the operands in the predecessor blocks that are
2698 // part of the region as regular scalar accesses.
2699
2700 // If we can synthesize a PHI we can skip it, however only if it is in
2701 // the region. If it is not it can only be in the exit block of the region.
2702 // In this case we model the operands but not the PHI itself.
2703 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
2704 return;
2705
2706 // PHI nodes are modeled as if they had been demoted prior to the SCoP
2707 // detection. Hence, the PHI is a load of a new memory location in which the
2708 // incoming value was written at the end of the incoming basic block.
2709 bool OnlyNonAffineSubRegionOperands = true;
2710 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
2711 Value *Op = PHI->getIncomingValue(u);
2712 BasicBlock *OpBB = PHI->getIncomingBlock(u);
2713
2714 // Do not build scalar dependences inside a non-affine subregion.
2715 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
2716 continue;
2717
2718 OnlyNonAffineSubRegionOperands = false;
2719
2720 if (!R.contains(OpBB))
2721 continue;
2722
2723 Instruction *OpI = dyn_cast<Instruction>(Op);
2724 if (OpI) {
2725 BasicBlock *OpIBB = OpI->getParent();
2726 // As we pretend there is a use (or more precise a write) of OpI in OpBB
2727 // we have to insert a scalar dependence from the definition of OpI to
2728 // OpBB if the definition is not in OpBB.
2729 if (OpIBB != OpBB) {
2730 IRAccess ScalarRead(IRAccess::READ, OpI, ZeroOffset, 1, true, OpI);
2731 AccFuncMap[OpBB].push_back(std::make_pair(ScalarRead, PHI));
2732 IRAccess ScalarWrite(IRAccess::MUST_WRITE, OpI, ZeroOffset, 1, true,
2733 OpI);
2734 AccFuncMap[OpIBB].push_back(std::make_pair(ScalarWrite, OpI));
2735 }
2736 }
2737
2738 // Always use the terminator of the incoming basic block as the access
2739 // instruction.
2740 OpI = OpBB->getTerminator();
2741
2742 IRAccess ScalarAccess(IRAccess::MUST_WRITE, PHI, ZeroOffset, 1, true, Op,
2743 /* IsPHI */ !IsExitBlock);
2744 AccFuncMap[OpBB].push_back(std::make_pair(ScalarAccess, OpI));
2745 }
2746
2747 if (!OnlyNonAffineSubRegionOperands) {
2748 IRAccess ScalarAccess(IRAccess::READ, PHI, ZeroOffset, 1, true, PHI,
2749 /* IsPHI */ !IsExitBlock);
2750 Functions.push_back(std::make_pair(ScalarAccess, PHI));
2751 }
2752}
2753
Michael Krused868b5d2015-09-10 15:25:24 +00002754bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
2755 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002756 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
2757 if (isIgnoredIntrinsic(Inst))
2758 return false;
2759
2760 bool AnyCrossStmtUse = false;
2761 BasicBlock *ParentBB = Inst->getParent();
2762
2763 for (User *U : Inst->users()) {
2764 Instruction *UI = dyn_cast<Instruction>(U);
2765
2766 // Ignore the strange user
2767 if (UI == 0)
2768 continue;
2769
2770 BasicBlock *UseParent = UI->getParent();
2771
2772 // Ignore the users in the same BB (statement)
2773 if (UseParent == ParentBB)
2774 continue;
2775
2776 // Do not build scalar dependences inside a non-affine subregion.
2777 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
2778 continue;
2779
2780 // Check whether or not the use is in the SCoP.
2781 if (!R->contains(UseParent)) {
2782 AnyCrossStmtUse = true;
2783 continue;
2784 }
2785
2786 // If the instruction can be synthesized and the user is in the region
2787 // we do not need to add scalar dependences.
2788 if (canSynthesizeInst)
2789 continue;
2790
2791 // No need to translate these scalar dependences into polyhedral form,
2792 // because synthesizable scalars can be generated by the code generator.
2793 if (canSynthesize(UI, LI, SE, R))
2794 continue;
2795
2796 // Skip PHI nodes in the region as they handle their operands on their own.
2797 if (isa<PHINode>(UI))
2798 continue;
2799
2800 // Now U is used in another statement.
2801 AnyCrossStmtUse = true;
2802
2803 // Do not build a read access that is not in the current SCoP
2804 // Use the def instruction as base address of the IRAccess, so that it will
2805 // become the name of the scalar access in the polyhedral form.
2806 IRAccess ScalarAccess(IRAccess::READ, Inst, ZeroOffset, 1, true, Inst);
2807 AccFuncMap[UseParent].push_back(std::make_pair(ScalarAccess, UI));
2808 }
2809
2810 if (ModelReadOnlyScalars) {
2811 for (Value *Op : Inst->operands()) {
2812 if (canSynthesize(Op, LI, SE, R))
2813 continue;
2814
2815 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
2816 if (R->contains(OpInst))
2817 continue;
2818
2819 if (isa<Constant>(Op))
2820 continue;
2821
2822 IRAccess ScalarAccess(IRAccess::READ, Op, ZeroOffset, 1, true, Op);
2823 AccFuncMap[Inst->getParent()].push_back(
2824 std::make_pair(ScalarAccess, Inst));
2825 }
2826 }
2827
2828 return AnyCrossStmtUse;
2829}
2830
2831extern MapInsnToMemAcc InsnToMemAcc;
2832
2833IRAccess
Michael Krused868b5d2015-09-10 15:25:24 +00002834ScopInfo::buildIRAccess(Instruction *Inst, Loop *L, Region *R,
2835 const ScopDetection::BoxedLoopsSetTy *BoxedLoops) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002836 unsigned Size;
2837 Type *SizeType;
2838 Value *Val;
2839 enum IRAccess::TypeKind Type;
2840
2841 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
2842 SizeType = Load->getType();
2843 Size = TD->getTypeStoreSize(SizeType);
2844 Type = IRAccess::READ;
2845 Val = Load;
2846 } else {
2847 StoreInst *Store = cast<StoreInst>(Inst);
2848 SizeType = Store->getValueOperand()->getType();
2849 Size = TD->getTypeStoreSize(SizeType);
2850 Type = IRAccess::MUST_WRITE;
2851 Val = Store->getValueOperand();
2852 }
2853
2854 const SCEV *AccessFunction = SE->getSCEVAtScope(getPointerOperand(*Inst), L);
2855 const SCEVUnknown *BasePointer =
2856 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
2857
2858 assert(BasePointer && "Could not find base pointer");
2859 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
2860
2861 auto AccItr = InsnToMemAcc.find(Inst);
2862 if (PollyDelinearize && AccItr != InsnToMemAcc.end())
2863 return IRAccess(Type, BasePointer->getValue(), AccessFunction, Size, true,
2864 AccItr->second.DelinearizedSubscripts,
2865 AccItr->second.Shape->DelinearizedSizes, Val);
2866
2867 // Check if the access depends on a loop contained in a non-affine subregion.
2868 bool isVariantInNonAffineLoop = false;
2869 if (BoxedLoops) {
2870 SetVector<const Loop *> Loops;
2871 findLoops(AccessFunction, Loops);
2872 for (const Loop *L : Loops)
2873 if (BoxedLoops->count(L))
2874 isVariantInNonAffineLoop = true;
2875 }
2876
2877 bool IsAffine = !isVariantInNonAffineLoop &&
2878 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue());
2879
2880 SmallVector<const SCEV *, 4> Subscripts, Sizes;
2881 Subscripts.push_back(AccessFunction);
2882 Sizes.push_back(SE->getConstant(ZeroOffset->getType(), Size));
2883
2884 if (!IsAffine && Type == IRAccess::MUST_WRITE)
2885 Type = IRAccess::MAY_WRITE;
2886
2887 return IRAccess(Type, BasePointer->getValue(), AccessFunction, Size, IsAffine,
2888 Subscripts, Sizes, Val);
2889}
2890
Michael Krused868b5d2015-09-10 15:25:24 +00002891void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002892
2893 if (SD->isNonAffineSubRegion(&SR, &R)) {
2894 for (BasicBlock *BB : SR.blocks())
2895 buildAccessFunctions(R, *BB, &SR);
2896 return;
2897 }
2898
2899 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
2900 if (I->isSubRegion())
2901 buildAccessFunctions(R, *I->getNodeAs<Region>());
2902 else
2903 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
2904}
2905
Michael Krused868b5d2015-09-10 15:25:24 +00002906void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
2907 Region *NonAffineSubRegion,
2908 bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002909 AccFuncSetType Functions;
2910 Loop *L = LI->getLoopFor(&BB);
2911
2912 // The set of loops contained in non-affine subregions that are part of R.
2913 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
2914
2915 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
2916 Instruction *Inst = I;
2917
2918 PHINode *PHI = dyn_cast<PHINode>(Inst);
2919 if (PHI)
2920 buildPHIAccesses(PHI, R, Functions, NonAffineSubRegion, IsExitBlock);
2921
2922 // For the exit block we stop modeling after the last PHI node.
2923 if (!PHI && IsExitBlock)
2924 break;
2925
2926 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
2927 Functions.push_back(
2928 std::make_pair(buildIRAccess(Inst, L, &R, BoxedLoops), Inst));
2929
2930 if (isIgnoredIntrinsic(Inst))
2931 continue;
2932
2933 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
2934 // If the Instruction is used outside the statement, we need to build the
2935 // write access.
2936 if (!isa<StoreInst>(Inst)) {
2937 IRAccess ScalarAccess(IRAccess::MUST_WRITE, Inst, ZeroOffset, 1, true,
2938 Inst);
2939 Functions.push_back(std::make_pair(ScalarAccess, Inst));
2940 }
2941 }
2942 }
2943
2944 if (Functions.empty())
2945 return;
2946
2947 AccFuncSetType &Accs = AccFuncMap[&BB];
2948 Accs.insert(Accs.end(), Functions.begin(), Functions.end());
2949}
2950
Michael Kruse9d080092015-09-11 21:41:48 +00002951Scop *ScopInfo::buildScop(Region &R, DominatorTree &DT) {
2952 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
2953 Scop *S = new Scop(R, AccFuncMap, *SE, DT, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00002954
2955 buildAccessFunctions(R, R);
2956
2957 // In case the region does not have an exiting block we will later (during
2958 // code generation) split the exit block. This will move potential PHI nodes
2959 // from the current exit block into the new region exiting block. Hence, PHI
2960 // nodes that are at this point not part of the region will be.
2961 // To handle these PHI nodes later we will now model their operands as scalar
2962 // accesses. Note that we do not model anything in the exit block if we have
2963 // an exiting block in the region, as there will not be any splitting later.
2964 if (!R.getExitingBlock())
2965 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
2966
Michael Kruse9d080092015-09-11 21:41:48 +00002967 S->init(*LI, *SD, *AA);
2968 return S;
Michael Kruse7bf39442015-09-10 12:46:52 +00002969}
2970
Michael Krused868b5d2015-09-10 15:25:24 +00002971void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00002972 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00002973 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00002974 return;
2975 }
2976
2977 scop->printIRAccesses(OS, SE, LI);
2978 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00002979}
2980
Michael Krused868b5d2015-09-10 15:25:24 +00002981void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00002982 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00002983 if (scop) {
2984 delete scop;
2985 scop = 0;
2986 }
Michael Kruse7bf39442015-09-10 12:46:52 +00002987}
2988
2989//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00002990ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00002991 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00002992 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00002993}
2994
2995ScopInfo::~ScopInfo() {
2996 clear();
2997 isl_ctx_free(ctx);
2998}
2999
Tobias Grosser75805372011-04-29 06:27:02 +00003000void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Michael Krused868b5d2015-09-10 15:25:24 +00003001 AU.addRequiredID(IndependentBlocksID);
Chandler Carruthf5579872015-01-17 14:16:56 +00003002 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00003003 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00003004 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00003005 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
3006 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003007 AU.addRequired<AAResultsWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00003008 AU.setPreservesAll();
3009}
3010
3011bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00003012 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00003013
Michael Krused868b5d2015-09-10 15:25:24 +00003014 if (!SD->isMaxRegionInScop(*R))
3015 return false;
3016
3017 Function *F = R->getEntry()->getParent();
3018 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3019 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3020 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3021 TD = &F->getParent()->getDataLayout();
3022 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3023 ZeroOffset = SE->getConstant(TD->getIntPtrType(F->getContext()), 0);
3024
Michael Kruse9d080092015-09-11 21:41:48 +00003025 scop = buildScop(*R, DT);
Tobias Grosser75805372011-04-29 06:27:02 +00003026
Tobias Grosserd6a50b32015-05-30 06:26:21 +00003027 DEBUG(scop->print(dbgs()));
3028
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003029 if (!scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003030 delete scop;
3031 scop = nullptr;
3032 return false;
3033 }
3034
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003035 // Statistics.
3036 ++ScopFound;
3037 if (scop->getMaxLoopDepth() > 0)
3038 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00003039 return false;
3040}
3041
3042char ScopInfo::ID = 0;
3043
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003044Pass *polly::createScopInfoPass() { return new ScopInfo(); }
3045
Tobias Grosser73600b82011-10-08 00:30:40 +00003046INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
3047 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003048 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003049INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00003050INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00003051INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00003052INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003053INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003054INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00003055INITIALIZE_PASS_END(ScopInfo, "polly-scops",
3056 "Polly - Create polyhedral description of Scops", false,
3057 false)