blob: 9de53ff4a56a70ff352518624ffc393c6c72e270 [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,
Tobias Grosser92245222015-07-28 14:53:44 +0000163 const SmallVector<const SCEV *, 4> &DimensionSizes,
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000164 bool IsPHI, Scop *S)
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000165 : BasePtr(BasePtr), ElementType(ElementType),
Tobias Grosser92245222015-07-28 14:53:44 +0000166 DimensionSizes(DimensionSizes), IsPHI(IsPHI) {
167 std::string BasePtrName =
168 getIslCompatibleName("MemRef_", BasePtr, IsPHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000169 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000170 for (const SCEV *Expr : DimensionSizes) {
171 isl_pw_aff *Size = S->getPwAff(Expr);
172 DimensionSizesPw.push_back(Size);
173 }
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000174
175 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
176 if (BasePtrOriginSAI)
177 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000178}
179
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000180ScopArrayInfo::~ScopArrayInfo() {
181 isl_id_free(Id);
182 for (isl_pw_aff *Size : DimensionSizesPw)
183 isl_pw_aff_free(Size);
184}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000185
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000186std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
187
188int ScopArrayInfo::getElemSizeInBytes() const {
189 return ElementType->getPrimitiveSizeInBits() / 8;
190}
191
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000192isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
193
194void ScopArrayInfo::dump() const { print(errs()); }
195
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000196void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000197 OS.indent(8) << *getElementType() << " " << getName() << "[*]";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000198 for (unsigned u = 0; u < getNumberOfDimensions(); u++) {
199 OS << "[";
200
201 if (SizeAsPwAff)
202 OS << " " << DimensionSizesPw[u] << " ";
203 else
204 OS << *DimensionSizes[u];
205
206 OS << "]";
207 }
208
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000209 if (BasePtrOriginSAI)
210 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
211
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000212 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000213}
214
215const ScopArrayInfo *
216ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
217 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
218 assert(Id && "Output dimension didn't have an ID");
219 return getFromId(Id);
220}
221
222const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
223 void *User = isl_id_get_user(Id);
224 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
225 isl_id_free(Id);
226 return SAI;
227}
228
Michael Kruse7bf39442015-09-10 12:46:52 +0000229void IRAccess::print(raw_ostream &OS) const {
230 if (isRead())
231 OS << "Read ";
232 else {
233 if (isMayWrite())
234 OS << "May";
235 OS << "Write ";
236 }
237 OS << BaseAddress->getName() << '[' << *Offset << "]\n";
238}
239
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000240const std::string
241MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
242 switch (RT) {
243 case MemoryAccess::RT_NONE:
244 llvm_unreachable("Requested a reduction operator string for a memory "
245 "access which isn't a reduction");
246 case MemoryAccess::RT_ADD:
247 return "+";
248 case MemoryAccess::RT_MUL:
249 return "*";
250 case MemoryAccess::RT_BOR:
251 return "|";
252 case MemoryAccess::RT_BXOR:
253 return "^";
254 case MemoryAccess::RT_BAND:
255 return "&";
256 }
257 llvm_unreachable("Unknown reduction type");
258 return "";
259}
260
Johannes Doerfertf6183392014-07-01 20:52:51 +0000261/// @brief Return the reduction type for a given binary operator
262static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
263 const Instruction *Load) {
264 if (!BinOp)
265 return MemoryAccess::RT_NONE;
266 switch (BinOp->getOpcode()) {
267 case Instruction::FAdd:
268 if (!BinOp->hasUnsafeAlgebra())
269 return MemoryAccess::RT_NONE;
270 // Fall through
271 case Instruction::Add:
272 return MemoryAccess::RT_ADD;
273 case Instruction::Or:
274 return MemoryAccess::RT_BOR;
275 case Instruction::Xor:
276 return MemoryAccess::RT_BXOR;
277 case Instruction::And:
278 return MemoryAccess::RT_BAND;
279 case Instruction::FMul:
280 if (!BinOp->hasUnsafeAlgebra())
281 return MemoryAccess::RT_NONE;
282 // Fall through
283 case Instruction::Mul:
284 if (DisableMultiplicativeReductions)
285 return MemoryAccess::RT_NONE;
286 return MemoryAccess::RT_MUL;
287 default:
288 return MemoryAccess::RT_NONE;
289 }
290}
Tobias Grosser75805372011-04-29 06:27:02 +0000291//===----------------------------------------------------------------------===//
292
293MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000294 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000295 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000296 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000297}
298
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000299static MemoryAccess::AccessType getMemoryAccessType(const IRAccess &Access) {
300 switch (Access.getType()) {
301 case IRAccess::READ:
302 return MemoryAccess::READ;
303 case IRAccess::MUST_WRITE:
304 return MemoryAccess::MUST_WRITE;
305 case IRAccess::MAY_WRITE:
306 return MemoryAccess::MAY_WRITE;
307 }
308 llvm_unreachable("Unknown IRAccess type!");
309}
310
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000311const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
312 isl_id *ArrayId = getArrayId();
313 void *User = isl_id_get_user(ArrayId);
314 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
315 isl_id_free(ArrayId);
316 return SAI;
317}
318
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000319__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000320 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
321}
322
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000323__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
324 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000325 isl_map *Schedule, *ScheduledAccRel;
326 isl_union_set *UDomain;
327
328 UDomain = isl_union_set_from_set(getStatement()->getDomain());
329 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
330 Schedule = isl_map_from_union_map(USchedule);
331 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
332 return isl_pw_multi_aff_from_map(ScheduledAccRel);
333}
334
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000335__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000336 return isl_map_copy(AccessRelation);
337}
338
Johannes Doerferta99130f2014-10-13 12:58:03 +0000339std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000340 return stringFromIslObj(AccessRelation);
341}
342
Johannes Doerferta99130f2014-10-13 12:58:03 +0000343__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000344 return isl_map_get_space(AccessRelation);
345}
346
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000347__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000348 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000349}
350
Tobias Grosser6f730082015-09-05 07:46:47 +0000351std::string MemoryAccess::getNewAccessRelationStr() const {
352 return stringFromIslObj(NewAccessRelation);
353}
354
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000355__isl_give isl_basic_map *
356MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000357 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000358 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000359
Tobias Grosser084d8f72012-05-29 09:29:44 +0000360 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000361 isl_basic_set_universe(Statement->getDomainSpace()),
362 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000363}
364
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000365// Formalize no out-of-bound access assumption
366//
367// When delinearizing array accesses we optimistically assume that the
368// delinearized accesses do not access out of bound locations (the subscript
369// expression of each array evaluates for each statement instance that is
370// executed to a value that is larger than zero and strictly smaller than the
371// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000372// dimension for which we do not need to assume any upper bound. At this point
373// we formalize this assumption to ensure that at code generation time the
374// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000375//
376// To find the set of constraints necessary to avoid out of bound accesses, we
377// first build the set of data locations that are not within array bounds. We
378// then apply the reverse access relation to obtain the set of iterations that
379// may contain invalid accesses and reduce this set of iterations to the ones
380// that are actually executed by intersecting them with the domain of the
381// statement. If we now project out all loop dimensions, we obtain a set of
382// parameters that may cause statement instances to be executed that may
383// possibly yield out of bound memory accesses. The complement of these
384// constraints is the set of constraints that needs to be assumed to ensure such
385// statement instances are never executed.
386void MemoryAccess::assumeNoOutOfBound(const IRAccess &Access) {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000387 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000388 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000389 for (int i = 1, Size = Access.Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000390 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
391 isl_pw_aff *Var =
392 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
393 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
394
395 isl_set *DimOutside;
396
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000397 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfert574182d2015-08-12 10:19:50 +0000398 isl_pw_aff *SizeE = Statement->getPwAff(Access.Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000399
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000400 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
401 Statement->getNumIterators());
402 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
403 isl_space_dim(Space, isl_dim_set));
404 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
405 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000406
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000407 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000408
409 Outside = isl_set_union(Outside, DimOutside);
410 }
411
412 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
413 Outside = isl_set_intersect(Outside, Statement->getDomain());
414 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000415
416 // Remove divs to avoid the construction of overly complicated assumptions.
417 // Doing so increases the set of parameter combinations that are assumed to
418 // not appear. This is always save, but may make the resulting run-time check
419 // bail out more often than strictly necessary.
420 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000421 Outside = isl_set_complement(Outside);
422 Statement->getParent()->addAssumption(Outside);
423 isl_space_free(Space);
424}
425
Johannes Doerferte7044942015-02-24 11:58:30 +0000426void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
427 ScalarEvolution *SE = Statement->getParent()->getSE();
428
429 Value *Ptr = getPointerOperand(*getAccessInstruction());
430 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
431 return;
432
433 auto *PtrSCEV = SE->getSCEV(Ptr);
434 if (isa<SCEVCouldNotCompute>(PtrSCEV))
435 return;
436
437 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
438 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
439 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
440
441 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
442 if (Range.isFullSet())
443 return;
444
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000445 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000446 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000447 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
448 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
449
450 auto Min = LB.sdiv(APInt(BW, ElementSize));
451 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000452
453 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
454 AccessRange =
455 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
456 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
457}
458
Tobias Grosser619190d2015-03-30 17:22:28 +0000459__isl_give isl_map *MemoryAccess::foldAccess(const IRAccess &Access,
460 __isl_take isl_map *AccessRelation,
461 ScopStmt *Statement) {
462 int Size = Access.Subscripts.size();
463
464 for (int i = Size - 2; i >= 0; --i) {
465 isl_space *Space;
466 isl_map *MapOne, *MapTwo;
Johannes Doerfert574182d2015-08-12 10:19:50 +0000467 isl_pw_aff *DimSize = Statement->getPwAff(Access.Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000468
469 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
470 isl_pw_aff_free(DimSize);
471 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
472
473 Space = isl_map_get_space(AccessRelation);
474 Space = isl_space_map_from_set(isl_space_range(Space));
475 Space = isl_space_align_params(Space, SpaceSize);
476
477 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
478 isl_id_free(ParamId);
479
480 MapOne = isl_map_universe(isl_space_copy(Space));
481 for (int j = 0; j < Size; ++j)
482 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
483 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
484
485 MapTwo = isl_map_universe(isl_space_copy(Space));
486 for (int j = 0; j < Size; ++j)
487 if (j < i || j > i + 1)
488 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
489
490 isl_local_space *LS = isl_local_space_from_space(Space);
491 isl_constraint *C;
492 C = isl_equality_alloc(isl_local_space_copy(LS));
493 C = isl_constraint_set_constant_si(C, -1);
494 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
495 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
496 MapTwo = isl_map_add_constraint(MapTwo, C);
497 C = isl_equality_alloc(LS);
498 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
499 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
500 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
501 MapTwo = isl_map_add_constraint(MapTwo, C);
502 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
503
504 MapOne = isl_map_union(MapOne, MapTwo);
505 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
506 }
507 return AccessRelation;
508}
509
Johannes Doerfert13c8cf22014-08-10 08:09:38 +0000510MemoryAccess::MemoryAccess(const IRAccess &Access, Instruction *AccInst,
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000511 ScopStmt *Statement, const ScopArrayInfo *SAI,
512 int Identifier)
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000513 : AccType(getMemoryAccessType(Access)), Statement(Statement),
514 AccessInstruction(AccInst), AccessValue(Access.getAccessValue()),
Tobias Grosser166c4222015-09-05 07:46:40 +0000515 NewAccessRelation(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +0000516
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000517 isl_ctx *Ctx = Statement->getIslCtx();
Tobias Grosser9759f852011-11-10 12:44:55 +0000518 BaseAddr = Access.getBase();
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000519 BaseName = getIslCompatibleName("MemRef_", getBaseAddr(), "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000520
521 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000522
Tobias Grosserac3a95f2015-08-03 17:53:21 +0000523 auto IdName = "__polly_array_ref_" + std::to_string(Identifier);
Tobias Grossere29d31c2015-05-15 12:24:09 +0000524 Id = isl_id_alloc(Ctx, IdName.c_str(), nullptr);
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000525
Tobias Grossera1879642011-12-20 10:43:14 +0000526 if (!Access.isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000527 // We overapproximate non-affine accesses with a possible access to the
528 // whole array. For read accesses it does not make a difference, if an
529 // access must or may happen. However, for write accesses it is important to
530 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000531 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000532 AccessRelation =
533 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000534
535 computeBoundsOnAccessRelation(Access.getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000536 return;
537 }
538
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000539 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000540 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000541
Tobias Grosser79baa212014-04-10 08:38:02 +0000542 for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000543 isl_pw_aff *Affine = Statement->getPwAff(Access.Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000544
Sebastian Pop422e33f2014-06-03 18:16:31 +0000545 if (Size == 1) {
546 // For the non delinearized arrays, divide the access function of the last
547 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000548 //
549 // A stride one array access in C expressed as A[i] is expressed in
550 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
551 // two subsequent values of 'i' index two values that are stored next to
552 // each other in memory. By this division we make this characteristic
553 // obvious again.
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000554 isl_val *v = isl_val_int_from_si(Ctx, Access.getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000555 Affine = isl_pw_aff_scale_down_val(Affine, v);
556 }
557
558 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
559
Tobias Grosser79baa212014-04-10 08:38:02 +0000560 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000561 }
562
Tobias Grosser619190d2015-03-30 17:22:28 +0000563 AccessRelation = foldAccess(Access, AccessRelation, Statement);
564
Tobias Grosser79baa212014-04-10 08:38:02 +0000565 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000566 AccessRelation = isl_map_set_tuple_id(
567 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000568 AccessRelation =
569 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
570
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000571 assumeNoOutOfBound(Access);
Tobias Grosseraa660a92015-03-30 00:07:50 +0000572 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000573 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000574}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000575
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000576void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000577 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000578 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000579}
580
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000581const std::string MemoryAccess::getReductionOperatorStr() const {
582 return MemoryAccess::getReductionOperatorStr(getReductionType());
583}
584
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000585__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
586
Johannes Doerfertf6183392014-07-01 20:52:51 +0000587raw_ostream &polly::operator<<(raw_ostream &OS,
588 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000589 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000590 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000591 else
592 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000593 return OS;
594}
595
Tobias Grosser75805372011-04-29 06:27:02 +0000596void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000597 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000598 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000599 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000600 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000601 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000602 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000603 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000604 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000605 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000606 break;
607 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000608 OS << "[Reduction Type: " << getReductionType() << "] ";
609 OS << "[Scalar: " << isScalar() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000610 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000611 if (hasNewAccessRelation())
612 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000613}
614
Tobias Grosser74394f02013-01-14 22:40:23 +0000615void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000616
617// Create a map in the size of the provided set domain, that maps from the
618// one element of the provided set domain to another element of the provided
619// set domain.
620// The mapping is limited to all points that are equal in all but the last
621// dimension and for which the last dimension of the input is strict smaller
622// than the last dimension of the output.
623//
624// getEqualAndLarger(set[i0, i1, ..., iX]):
625//
626// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
627// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
628//
Tobias Grosserf5338802011-10-06 00:03:35 +0000629static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000630 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000631 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000632 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000633
634 // Set all but the last dimension to be equal for the input and output
635 //
636 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
637 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000638 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000639 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000640
641 // Set the last dimension of the input to be strict smaller than the
642 // last dimension of the output.
643 //
644 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000645 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
646 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000647 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000648}
649
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000650__isl_give isl_set *
651MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000652 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000653 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000654 isl_space *Space = isl_space_range(isl_map_get_space(S));
655 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000656
Sebastian Popa00a0292012-12-18 07:46:06 +0000657 S = isl_map_reverse(S);
658 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000659
Sebastian Popa00a0292012-12-18 07:46:06 +0000660 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
661 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
662 NextScatt = isl_map_apply_domain(NextScatt, S);
663 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000664
Sebastian Popa00a0292012-12-18 07:46:06 +0000665 isl_set *Deltas = isl_map_deltas(NextScatt);
666 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000667}
668
Sebastian Popa00a0292012-12-18 07:46:06 +0000669bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000670 int StrideWidth) const {
671 isl_set *Stride, *StrideX;
672 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000673
Sebastian Popa00a0292012-12-18 07:46:06 +0000674 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000675 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000676 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
677 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
678 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
679 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000680 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000681
Tobias Grosser28dd4862012-01-24 16:42:16 +0000682 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000683 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000684
Tobias Grosser28dd4862012-01-24 16:42:16 +0000685 return IsStrideX;
686}
687
Sebastian Popa00a0292012-12-18 07:46:06 +0000688bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
689 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000690}
691
Tobias Grosser79baa212014-04-10 08:38:02 +0000692bool MemoryAccess::isScalar() const {
693 return isl_map_n_out(AccessRelation) == 0;
694}
695
Sebastian Popa00a0292012-12-18 07:46:06 +0000696bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
697 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000698}
699
Tobias Grosser166c4222015-09-05 07:46:40 +0000700void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
701 isl_map_free(NewAccessRelation);
702 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000703}
Tobias Grosser75805372011-04-29 06:27:02 +0000704
705//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000706
Tobias Grosser808cd692015-07-14 09:33:13 +0000707isl_map *ScopStmt::getSchedule() const {
708 isl_set *Domain = getDomain();
709 if (isl_set_is_empty(Domain)) {
710 isl_set_free(Domain);
711 return isl_map_from_aff(
712 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
713 }
714 auto *Schedule = getParent()->getSchedule();
715 Schedule = isl_union_map_intersect_domain(
716 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
717 if (isl_union_map_is_empty(Schedule)) {
718 isl_set_free(Domain);
719 isl_union_map_free(Schedule);
720 return isl_map_from_aff(
721 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
722 }
723 auto *M = isl_map_from_union_map(Schedule);
724 M = isl_map_coalesce(M);
725 M = isl_map_gist_domain(M, Domain);
726 M = isl_map_coalesce(M);
727 return M;
728}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000729
Johannes Doerfert574182d2015-08-12 10:19:50 +0000730__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertb409fdc2015-08-28 09:24:35 +0000731 return getParent()->getPwAff(E, Domain);
Johannes Doerfert574182d2015-08-12 10:19:50 +0000732}
733
Tobias Grosser37eb4222014-02-20 21:43:54 +0000734void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
735 assert(isl_set_is_subset(NewDomain, Domain) &&
736 "New domain is not a subset of old domain!");
737 isl_set_free(Domain);
738 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000739}
740
Michael Kruse9d080092015-09-11 21:41:48 +0000741void ScopStmt::buildAccesses(BasicBlock *Block, bool isApproximated) {
742 AccFuncSetType *AFS = Parent.getAccessFunctions(Block);
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000743 if (!AFS)
744 return;
745
746 for (auto &AccessPair : *AFS) {
747 IRAccess &Access = AccessPair.first;
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000748 Instruction *AccessInst = AccessPair.second;
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000749 Type *ElementType = Access.getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000750
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000751 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Tobias Grosser92245222015-07-28 14:53:44 +0000752 Access.getBase(), ElementType, Access.Sizes, Access.isPHI());
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000753
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000754 if (isApproximated && Access.isWrite())
755 Access.setMayWrite();
756
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000757 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
758 if (!MAL)
759 MAL = new MemoryAccessList();
760 MAL->emplace_front(Access, AccessInst, this, SAI, MemAccs.size());
761 MemAccs.push_back(&MAL->front());
Tobias Grosser75805372011-04-29 06:27:02 +0000762 }
763}
764
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000765void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000766 for (MemoryAccess *MA : *this)
767 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000768
769 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000770}
771
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000772/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
773static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
774 void *User) {
775 isl_set **BoundedParts = static_cast<isl_set **>(User);
776 if (isl_basic_set_is_bounded(BSet))
777 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
778 else
779 isl_basic_set_free(BSet);
780 return isl_stat_ok;
781}
782
783/// @brief Return the bounded parts of @p S.
784static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
785 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
786 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
787 isl_set_free(S);
788 return BoundedParts;
789}
790
791/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
792///
793/// @returns A separation of @p S into first an unbounded then a bounded subset,
794/// both with regards to the dimension @p Dim.
795static std::pair<__isl_give isl_set *, __isl_give isl_set *>
796partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
797
798 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertca1e38f2015-09-14 11:12:52 +0000799 S = isl_set_lower_bound_si(S, isl_dim_set, u, u == Dim ? -1 : 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000800
801 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertca1e38f2015-09-14 11:12:52 +0000802 isl_set *OnlyDimS = S;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000803
804 // Remove dimensions that are greater than Dim as they are not interesting.
805 assert(NumDimsS >= Dim + 1);
806 OnlyDimS =
807 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
808
809 // Create artificial parametric upper bounds for dimensions smaller than Dim
810 // as we are not interested in them.
811 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
812 for (unsigned u = 0; u < Dim; u++) {
813 isl_constraint *C = isl_inequality_alloc(
814 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
815 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
816 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
817 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
818 }
819
820 // Collect all bounded parts of OnlyDimS.
821 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
822
823 // Create the dimensions greater than Dim again.
824 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
825 NumDimsS - Dim - 1);
826
827 // Remove the artificial upper bound parameters again.
828 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
829
Johannes Doerfertca1e38f2015-09-14 11:12:52 +0000830 isl_set *UnboundedParts = isl_set_complement(isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000831 return std::make_pair(UnboundedParts, BoundedParts);
832}
833
Johannes Doerfert96425c22015-08-30 21:13:53 +0000834static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
835 isl_pw_aff *L, isl_pw_aff *R) {
836 switch (Pred) {
837 case ICmpInst::ICMP_EQ:
838 return isl_pw_aff_eq_set(L, R);
839 case ICmpInst::ICMP_NE:
840 return isl_pw_aff_ne_set(L, R);
841 case ICmpInst::ICMP_SLT:
842 return isl_pw_aff_lt_set(L, R);
843 case ICmpInst::ICMP_SLE:
844 return isl_pw_aff_le_set(L, R);
845 case ICmpInst::ICMP_SGT:
846 return isl_pw_aff_gt_set(L, R);
847 case ICmpInst::ICMP_SGE:
848 return isl_pw_aff_ge_set(L, R);
849 case ICmpInst::ICMP_ULT:
850 return isl_pw_aff_lt_set(L, R);
851 case ICmpInst::ICMP_UGT:
852 return isl_pw_aff_gt_set(L, R);
853 case ICmpInst::ICMP_ULE:
854 return isl_pw_aff_le_set(L, R);
855 case ICmpInst::ICMP_UGE:
856 return isl_pw_aff_ge_set(L, R);
857 default:
858 llvm_unreachable("Non integer predicate not supported");
859 }
860}
861
862/// @brief Build the conditions sets for the branch @p BI in the @p Domain.
863///
864/// This will fill @p ConditionSets with the conditions under which control
865/// will be moved from @p BI to its successors. Hence, @p ConditionSets will
866/// have as many elements as @p BI has successors.
867static void
868buildConditionSets(Scop &S, BranchInst *BI, Loop *L, __isl_keep isl_set *Domain,
869 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
870
871 if (BI->isUnconditional()) {
872 ConditionSets.push_back(isl_set_copy(Domain));
873 return;
874 }
875
876 Value *Condition = BI->getCondition();
877
878 isl_set *ConsequenceCondSet = nullptr;
879 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
880 if (CCond->isZero())
881 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
882 else
883 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
884 } else {
885 auto *ICond = dyn_cast<ICmpInst>(Condition);
886 assert(ICond &&
887 "Condition of exiting branch was neither constant nor ICmp!");
888
889 ScalarEvolution &SE = *S.getSE();
890 isl_pw_aff *LHS, *RHS;
891 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), Domain);
892 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), Domain);
893 ConsequenceCondSet = buildConditionSet(ICond->getPredicate(), LHS, RHS);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000894
895 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
896 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
897 ConsequenceCondSet =
898 isl_set_set_dim_id(ConsequenceCondSet, isl_dim_set, u, DimId);
899 }
Johannes Doerfert96425c22015-08-30 21:13:53 +0000900 }
901
902 assert(ConsequenceCondSet);
903 isl_set *AlternativeCondSet =
904 isl_set_complement(isl_set_copy(ConsequenceCondSet));
905
906 ConditionSets.push_back(isl_set_coalesce(
907 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
908 ConditionSets.push_back(isl_set_coalesce(
909 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
910}
911
Johannes Doerfert32ae76e2015-09-10 13:12:02 +0000912void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000913 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000914
Tobias Grosser084d8f72012-05-29 09:29:44 +0000915 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
916
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000917 Domain = getParent()->getDomainConditions(this);
Johannes Doerfert96425c22015-08-30 21:13:53 +0000918 Domain = isl_set_coalesce(Domain);
Tobias Grosser084d8f72012-05-29 09:29:44 +0000919 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +0000920}
921
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000922void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
923 int Dimension = 0;
924 isl_ctx *Ctx = Parent.getIslCtx();
925 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
926 Type *Ty = GEP->getPointerOperandType();
927 ScalarEvolution &SE = *Parent.getSE();
928
929 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
930 Dimension = 1;
931 Ty = PtrTy->getElementType();
932 }
933
934 while (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
935 unsigned int Operand = 1 + Dimension;
936
937 if (GEP->getNumOperands() <= Operand)
938 break;
939
940 const SCEV *Expr = SE.getSCEV(GEP->getOperand(Operand));
941
942 if (isAffineExpr(&Parent.getRegion(), Expr, SE)) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000943 isl_pw_aff *AccessOffset = getPwAff(Expr);
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000944 AccessOffset =
945 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
946
947 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
948 isl_local_space_copy(LSpace),
949 isl_val_int_from_si(Ctx, ArrayTy->getNumElements())));
950
951 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
952 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
953 OutOfBound = isl_set_params(OutOfBound);
954 isl_set *InBound = isl_set_complement(OutOfBound);
955 isl_set *Executed = isl_set_params(getDomain());
956
957 // A => B == !A or B
958 isl_set *InBoundIfExecuted =
959 isl_set_union(isl_set_complement(Executed), InBound);
960
961 Parent.addAssumption(InBoundIfExecuted);
962 }
963
964 Dimension += 1;
965 Ty = ArrayTy->getElementType();
966 }
967
968 isl_local_space_free(LSpace);
969}
970
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000971void ScopStmt::deriveAssumptions(BasicBlock *Block) {
972 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000973 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
974 deriveAssumptionsFromGEP(GEP);
975}
976
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000977void ScopStmt::collectSurroundingLoops() {
978 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
979 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
980 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
981 isl_id_free(DimId);
982 }
983}
984
Michael Kruse9d080092015-09-11 21:41:48 +0000985ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000986 : Parent(parent), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000987
Tobias Grosser16c44032015-07-09 07:31:45 +0000988 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000989
Johannes Doerfert32ae76e2015-09-10 13:12:02 +0000990 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000991 collectSurroundingLoops();
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000992
993 BasicBlock *EntryBB = R.getEntry();
994 for (BasicBlock *Block : R.blocks()) {
Michael Kruse9d080092015-09-11 21:41:48 +0000995 buildAccesses(Block, Block != EntryBB);
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000996 deriveAssumptions(Block);
997 }
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000998 if (DetectReductions)
999 checkForReductions();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001000}
1001
Michael Kruse9d080092015-09-11 21:41:48 +00001002ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001003 : Parent(parent), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001004
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001005 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +00001006
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001007 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001008 collectSurroundingLoops();
Michael Kruse9d080092015-09-11 21:41:48 +00001009 buildAccesses(BB);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001010 deriveAssumptions(BB);
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001011 if (DetectReductions)
1012 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001013}
1014
Johannes Doerferte58a0122014-06-27 20:31:28 +00001015/// @brief Collect loads which might form a reduction chain with @p StoreMA
1016///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001017/// Check if the stored value for @p StoreMA is a binary operator with one or
1018/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001019/// used only once (by @p StoreMA) and its load operands are also used only
1020/// once, we have found a possible reduction chain. It starts at an operand
1021/// load and includes the binary operator and @p StoreMA.
1022///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001023/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001024/// escape this block or into any other store except @p StoreMA.
1025void ScopStmt::collectCandiateReductionLoads(
1026 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1027 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1028 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001029 return;
1030
1031 // Skip if there is not one binary operator between the load and the store
1032 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001033 if (!BinOp)
1034 return;
1035
1036 // Skip if the binary operators has multiple uses
1037 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001038 return;
1039
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001040 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001041 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1042 return;
1043
Johannes Doerfert9890a052014-07-01 00:32:29 +00001044 // Skip if the binary operator is outside the current SCoP
1045 if (BinOp->getParent() != Store->getParent())
1046 return;
1047
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001048 // Skip if it is a multiplicative reduction and we disabled them
1049 if (DisableMultiplicativeReductions &&
1050 (BinOp->getOpcode() == Instruction::Mul ||
1051 BinOp->getOpcode() == Instruction::FMul))
1052 return;
1053
Johannes Doerferte58a0122014-06-27 20:31:28 +00001054 // Check the binary operator operands for a candidate load
1055 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1056 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1057 if (!PossibleLoad0 && !PossibleLoad1)
1058 return;
1059
1060 // A load is only a candidate if it cannot escape (thus has only this use)
1061 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001062 if (PossibleLoad0->getParent() == Store->getParent())
1063 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001064 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001065 if (PossibleLoad1->getParent() == Store->getParent())
1066 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001067}
1068
1069/// @brief Check for reductions in this ScopStmt
1070///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001071/// Iterate over all store memory accesses and check for valid binary reduction
1072/// like chains. For all candidates we check if they have the same base address
1073/// and there are no other accesses which overlap with them. The base address
1074/// check rules out impossible reductions candidates early. The overlap check,
1075/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001076/// guarantees that none of the intermediate results will escape during
1077/// execution of the loop nest. We basically check here that no other memory
1078/// access can access the same memory as the potential reduction.
1079void ScopStmt::checkForReductions() {
1080 SmallVector<MemoryAccess *, 2> Loads;
1081 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1082
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001083 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001084 // stores and collecting possible reduction loads.
1085 for (MemoryAccess *StoreMA : MemAccs) {
1086 if (StoreMA->isRead())
1087 continue;
1088
1089 Loads.clear();
1090 collectCandiateReductionLoads(StoreMA, Loads);
1091 for (MemoryAccess *LoadMA : Loads)
1092 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1093 }
1094
1095 // Then check each possible candidate pair.
1096 for (const auto &CandidatePair : Candidates) {
1097 bool Valid = true;
1098 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1099 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1100
1101 // Skip those with obviously unequal base addresses.
1102 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1103 isl_map_free(LoadAccs);
1104 isl_map_free(StoreAccs);
1105 continue;
1106 }
1107
1108 // And check if the remaining for overlap with other memory accesses.
1109 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1110 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1111 isl_set *AllAccs = isl_map_range(AllAccsRel);
1112
1113 for (MemoryAccess *MA : MemAccs) {
1114 if (MA == CandidatePair.first || MA == CandidatePair.second)
1115 continue;
1116
1117 isl_map *AccRel =
1118 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1119 isl_set *Accs = isl_map_range(AccRel);
1120
1121 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1122 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1123 Valid = Valid && isl_set_is_empty(OverlapAccs);
1124 isl_set_free(OverlapAccs);
1125 }
1126 }
1127
1128 isl_set_free(AllAccs);
1129 if (!Valid)
1130 continue;
1131
Johannes Doerfertf6183392014-07-01 20:52:51 +00001132 const LoadInst *Load =
1133 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1134 MemoryAccess::ReductionType RT =
1135 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1136
Johannes Doerferte58a0122014-06-27 20:31:28 +00001137 // If no overlapping access was found we mark the load and store as
1138 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001139 CandidatePair.first->markAsReductionLike(RT);
1140 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001141 }
Tobias Grosser75805372011-04-29 06:27:02 +00001142}
1143
Tobias Grosser74394f02013-01-14 22:40:23 +00001144std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001145
Tobias Grosser54839312015-04-21 11:37:25 +00001146std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001147 auto *S = getSchedule();
1148 auto Str = stringFromIslObj(S);
1149 isl_map_free(S);
1150 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001151}
1152
Tobias Grosser74394f02013-01-14 22:40:23 +00001153unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001154
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001155unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001156
Tobias Grosser75805372011-04-29 06:27:02 +00001157const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1158
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001159const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001160 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001161}
1162
Tobias Grosser74394f02013-01-14 22:40:23 +00001163isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001164
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001165__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001166
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001167__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001168 return isl_set_get_space(Domain);
1169}
1170
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001171__isl_give isl_id *ScopStmt::getDomainId() const {
1172 return isl_set_get_tuple_id(Domain);
1173}
Tobias Grossercd95b772012-08-30 11:49:38 +00001174
Tobias Grosser75805372011-04-29 06:27:02 +00001175ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001176 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001177 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001178}
1179
1180void ScopStmt::print(raw_ostream &OS) const {
1181 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001182 OS.indent(12) << "Domain :=\n";
1183
1184 if (Domain) {
1185 OS.indent(16) << getDomainStr() << ";\n";
1186 } else
1187 OS.indent(16) << "n/a\n";
1188
Tobias Grosser54839312015-04-21 11:37:25 +00001189 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001190
1191 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001192 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001193 } else
1194 OS.indent(16) << "n/a\n";
1195
Tobias Grosser083d3d32014-06-28 08:59:45 +00001196 for (MemoryAccess *Access : MemAccs)
1197 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001198}
1199
1200void ScopStmt::dump() const { print(dbgs()); }
1201
1202//===----------------------------------------------------------------------===//
1203/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001204
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001205void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001206 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1207 isl_set_free(Context);
1208 Context = NewContext;
1209}
1210
Tobias Grosserabfbe632013-02-05 12:09:06 +00001211void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001212 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001213 Parameter = extractConstantFactor(Parameter, *SE).second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001214 if (ParameterIds.find(Parameter) != ParameterIds.end())
1215 continue;
1216
1217 int dimension = Parameters.size();
1218
1219 Parameters.push_back(Parameter);
1220 ParameterIds[Parameter] = dimension;
1221 }
1222}
1223
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001224__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1225 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001226
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001227 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001228 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001229
Tobias Grosser8f99c162011-11-15 11:38:55 +00001230 std::string ParameterName;
1231
1232 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1233 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001234 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001235 }
1236
1237 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001238 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001239
Tobias Grosser20532b82014-04-11 17:56:49 +00001240 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1241 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001242}
Tobias Grosser75805372011-04-29 06:27:02 +00001243
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001244isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1245 isl_set *DomainContext = isl_union_set_params(getDomains());
1246 return isl_set_intersect_params(C, DomainContext);
1247}
1248
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001249void Scop::addUserContext() {
1250 if (UserContextStr.empty())
1251 return;
1252
1253 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1254 isl_space *Space = getParamSpace();
1255 if (isl_space_dim(Space, isl_dim_param) !=
1256 isl_set_dim(UserContext, isl_dim_param)) {
1257 auto SpaceStr = isl_space_to_str(Space);
1258 errs() << "Error: the context provided in -polly-context has not the same "
1259 << "number of dimensions than the computed context. Due to this "
1260 << "mismatch, the -polly-context option is ignored. Please provide "
1261 << "the context in the parameter space: " << SpaceStr << ".\n";
1262 free(SpaceStr);
1263 isl_set_free(UserContext);
1264 isl_space_free(Space);
1265 return;
1266 }
1267
1268 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1269 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1270 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1271
1272 if (strcmp(NameContext, NameUserContext) != 0) {
1273 auto SpaceStr = isl_space_to_str(Space);
1274 errs() << "Error: the name of dimension " << i
1275 << " provided in -polly-context "
1276 << "is '" << NameUserContext << "', but the name in the computed "
1277 << "context is '" << NameContext
1278 << "'. Due to this name mismatch, "
1279 << "the -polly-context option is ignored. Please provide "
1280 << "the context in the parameter space: " << SpaceStr << ".\n";
1281 free(SpaceStr);
1282 isl_set_free(UserContext);
1283 isl_space_free(Space);
1284 return;
1285 }
1286
1287 UserContext =
1288 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1289 isl_space_get_dim_id(Space, isl_dim_param, i));
1290 }
1291
1292 Context = isl_set_intersect(Context, UserContext);
1293 isl_space_free(Space);
1294}
1295
Tobias Grosser6be480c2011-11-08 15:41:13 +00001296void Scop::buildContext() {
1297 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001298 Context = isl_set_universe(isl_space_copy(Space));
1299 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001300}
1301
Tobias Grosser18daaca2012-05-22 10:47:27 +00001302void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001303 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001304 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001305
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001306 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001307
Johannes Doerferte7044942015-02-24 11:58:30 +00001308 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001309 }
1310}
1311
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001312void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001313 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001314 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001315
Tobias Grosser083d3d32014-06-28 08:59:45 +00001316 for (const auto &ParamID : ParameterIds) {
1317 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001318 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001319 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001320 }
1321
1322 // Align the parameters of all data structures to the model.
1323 Context = isl_set_align_params(Context, Space);
1324
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001325 for (ScopStmt &Stmt : *this)
1326 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001327}
1328
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001329void Scop::simplifyAssumedContext() {
1330 // The parameter constraints of the iteration domains give us a set of
1331 // constraints that need to hold for all cases where at least a single
1332 // statement iteration is executed in the whole scop. We now simplify the
1333 // assumed context under the assumption that such constraints hold and at
1334 // least a single statement iteration is executed. For cases where no
1335 // statement instances are executed, the assumptions we have taken about
1336 // the executed code do not matter and can be changed.
1337 //
1338 // WARNING: This only holds if the assumptions we have taken do not reduce
1339 // the set of statement instances that are executed. Otherwise we
1340 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001341 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001342 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001343 // performed. In such a case, modifying the run-time conditions and
1344 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001345 // to not be executed.
1346 //
1347 // Example:
1348 //
1349 // When delinearizing the following code:
1350 //
1351 // for (long i = 0; i < 100; i++)
1352 // for (long j = 0; j < m; j++)
1353 // A[i+p][j] = 1.0;
1354 //
1355 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001356 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001357 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
1358 AssumedContext =
1359 isl_set_gist_params(AssumedContext, isl_union_set_params(getDomains()));
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001360 AssumedContext = isl_set_gist_params(AssumedContext, getContext());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001361}
1362
Johannes Doerfertb164c792014-09-18 11:17:17 +00001363/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001364static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001365 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1366 isl_pw_multi_aff *MinPMA, *MaxPMA;
1367 isl_pw_aff *LastDimAff;
1368 isl_aff *OneAff;
1369 unsigned Pos;
1370
Johannes Doerfert9143d672014-09-27 11:02:39 +00001371 // Restrict the number of parameters involved in the access as the lexmin/
1372 // lexmax computation will take too long if this number is high.
1373 //
1374 // Experiments with a simple test case using an i7 4800MQ:
1375 //
1376 // #Parameters involved | Time (in sec)
1377 // 6 | 0.01
1378 // 7 | 0.04
1379 // 8 | 0.12
1380 // 9 | 0.40
1381 // 10 | 1.54
1382 // 11 | 6.78
1383 // 12 | 30.38
1384 //
1385 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1386 unsigned InvolvedParams = 0;
1387 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1388 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1389 InvolvedParams++;
1390
1391 if (InvolvedParams > RunTimeChecksMaxParameters) {
1392 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001393 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001394 }
1395 }
1396
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001397 Set = isl_set_remove_divs(Set);
1398
Johannes Doerfertb164c792014-09-18 11:17:17 +00001399 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1400 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1401
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001402 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1403 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1404
Johannes Doerfertb164c792014-09-18 11:17:17 +00001405 // Adjust the last dimension of the maximal access by one as we want to
1406 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1407 // we test during code generation might now point after the end of the
1408 // allocated array but we will never dereference it anyway.
1409 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1410 "Assumed at least one output dimension");
1411 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1412 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1413 OneAff = isl_aff_zero_on_domain(
1414 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1415 OneAff = isl_aff_add_constant_si(OneAff, 1);
1416 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1417 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1418
1419 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1420
1421 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001422 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001423}
1424
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001425static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1426 isl_set *Domain = MA->getStatement()->getDomain();
1427 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1428 return isl_set_reset_tuple_id(Domain);
1429}
1430
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001431/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1432static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001433 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001434 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001435
1436 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1437 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001438 Locations = isl_union_set_coalesce(Locations);
1439 Locations = isl_union_set_detect_equalities(Locations);
1440 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001441 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001442 isl_union_set_free(Locations);
1443 return Valid;
1444}
1445
Johannes Doerfert96425c22015-08-30 21:13:53 +00001446/// @brief Helper to treat non-affine regions and basic blocks the same.
1447///
1448///{
1449
1450/// @brief Return the block that is the representing block for @p RN.
1451static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1452 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1453 : RN->getNodeAs<BasicBlock>();
1454}
1455
1456/// @brief Return the @p idx'th block that is executed after @p RN.
1457static inline BasicBlock *getRegionNodeSuccessor(RegionNode *RN, BranchInst *BI,
1458 unsigned idx) {
1459 if (RN->isSubRegion()) {
1460 assert(idx == 0);
1461 return RN->getNodeAs<Region>()->getExit();
1462 }
1463 return BI->getSuccessor(idx);
1464}
1465
1466/// @brief Return the smallest loop surrounding @p RN.
1467static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1468 if (!RN->isSubRegion())
1469 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1470
1471 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1472 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1473 while (L && NonAffineSubRegion->contains(L))
1474 L = L->getParentLoop();
1475 return L;
1476}
1477
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001478static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1479 if (!RN->isSubRegion())
1480 return 1;
1481
1482 unsigned NumBlocks = 0;
1483 Region *R = RN->getNodeAs<Region>();
1484 for (auto BB : R->blocks()) {
1485 (void)BB;
1486 NumBlocks++;
1487 }
1488 return NumBlocks;
1489}
1490
Johannes Doerfert96425c22015-08-30 21:13:53 +00001491///}
1492
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001493static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1494 unsigned Dim, Loop *L) {
1495 isl_id *DimId =
1496 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
1497 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
1498}
1499
Johannes Doerfert96425c22015-08-30 21:13:53 +00001500isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1501 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1502 : Stmt->getRegion()->getEntry();
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001503 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001504}
1505
1506void Scop::buildDomains(Region *R, LoopInfo &LI, ScopDetection &SD,
1507 DominatorTree &DT) {
1508
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001509 auto *EntryBB = R->getEntry();
1510 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
1511 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001512
1513 Loop *L = LI.getLoopFor(EntryBB);
1514 while (LD-- >= 0) {
1515 S = addDomainDimId(S, LD + 1, L);
1516 L = L->getParentLoop();
1517 }
1518
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001519 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001520
1521 buildDomainsWithBranchConstraints(R, LI, SD, DT);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001522 addLoopBoundsToHeaderDomains(LI, SD, DT);
1523 propagateDomainConstraints(R, LI, SD, DT);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001524}
1525
1526void Scop::buildDomainsWithBranchConstraints(Region *R, LoopInfo &LI,
1527 ScopDetection &SD,
1528 DominatorTree &DT) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001529 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00001530
1531 // To create the domain for each block in R we iterate over all blocks and
1532 // subregions in R and propagate the conditions under which the current region
1533 // element is executed. To this end we iterate in reverse post order over R as
1534 // it ensures that we first visit all predecessors of a region node (either a
1535 // basic block or a subregion) before we visit the region node itself.
1536 // Initially, only the domain for the SCoP region entry block is set and from
1537 // there we propagate the current domain to all successors, however we add the
1538 // condition that the successor is actually executed next.
1539 // As we are only interested in non-loop carried constraints here we can
1540 // simply skip loop back edges.
1541
1542 ReversePostOrderTraversal<Region *> RTraversal(R);
1543 for (auto *RN : RTraversal) {
1544
1545 // Recurse for affine subregions but go on for basic blocks and non-affine
1546 // subregions.
1547 if (RN->isSubRegion()) {
1548 Region *SubRegion = RN->getNodeAs<Region>();
1549 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
1550 buildDomainsWithBranchConstraints(SubRegion, LI, SD, DT);
1551 continue;
1552 }
1553 }
1554
1555 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001556 TerminatorInst *TI = BB->getTerminator();
1557
1558 // Unreachable instructions do not have successors so we can skip them.
1559 if (isa<UnreachableInst>(TI)) {
1560 // Assume unreachables only in error blocks.
1561 assert(isErrorBlock(*BB));
1562 continue;
1563 }
1564
Johannes Doerfert96425c22015-08-30 21:13:53 +00001565 isl_set *Domain = DomainMap[BB];
1566 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
1567 assert(Domain && "Due to reverse post order traversal of the region all "
1568 "predecessor of the current region node should have been "
1569 "visited and a domain for this region node should have "
1570 "been set.");
1571
1572 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1573 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1574
1575 // Build the condition sets for the successor nodes of the current region
1576 // node. If it is a non-affine subregion we will always execute the single
1577 // exit node, hence the single entry node domain is the condition set. For
1578 // basic blocks we use the helper function buildConditionSets.
1579 SmallVector<isl_set *, 2> ConditionSets;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001580 BranchInst *BI = cast<BranchInst>(TI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001581 if (RN->isSubRegion())
1582 ConditionSets.push_back(isl_set_copy(Domain));
1583 else
1584 buildConditionSets(*this, BI, BBLoop, Domain, ConditionSets);
1585
1586 // Now iterate over the successors and set their initial domain based on
1587 // their condition set. We skip back edges here and have to be careful when
1588 // we leave a loop not to keep constraints over a dimension that doesn't
1589 // exist anymore.
1590 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
1591 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, BI, u);
1592 isl_set *CondSet = ConditionSets[u];
1593
1594 // Skip back edges.
1595 if (DT.dominates(SuccBB, BB)) {
1596 isl_set_free(CondSet);
1597 continue;
1598 }
1599
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001600 // Do not adjust the number of dimensions if we enter a boxed loop or are
1601 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001602 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001603 Region *SuccRegion = RI.getRegionFor(SuccBB);
1604 if (BBLoop != SuccBBLoop && !RN->isSubRegion() &&
1605 !(SD.isNonAffineSubRegion(SuccRegion, &getRegion()) &&
1606 SuccRegion->contains(SuccBBLoop))) {
1607
1608 // Check if the edge to SuccBB is a loop entry or exit edge. If so
1609 // adjust the dimensionality accordingly. Lastly, if we leave a loop
1610 // and enter a new one we need to drop the old constraints.
1611 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001612 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001613 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001614 CondSet = isl_set_project_out(CondSet, isl_dim_set,
1615 isl_set_n_dim(CondSet) - LoopDepthDiff,
1616 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001617 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001618 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001619 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001620 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001621 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001622 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001623 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
1624 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001625 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001626 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00001627 }
1628
1629 // Set the domain for the successor or merge it with an existing domain in
1630 // case there are multiple paths (without loop back edges) to the
1631 // successor block.
1632 isl_set *&SuccDomain = DomainMap[SuccBB];
1633 if (!SuccDomain)
1634 SuccDomain = CondSet;
1635 else
1636 SuccDomain = isl_set_union(SuccDomain, CondSet);
1637
1638 SuccDomain = isl_set_coalesce(SuccDomain);
1639 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : " << Domain
1640 << "\n");
1641 }
1642 }
1643}
1644
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001645/// @brief Return the domain for @p BB wrt @p DomainMap.
1646///
1647/// This helper function will lookup @p BB in @p DomainMap but also handle the
1648/// case where @p BB is contained in a non-affine subregion using the region
1649/// tree obtained by @p RI.
1650static __isl_give isl_set *
1651getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
1652 RegionInfo &RI) {
1653 auto DIt = DomainMap.find(BB);
1654 if (DIt != DomainMap.end())
1655 return isl_set_copy(DIt->getSecond());
1656
1657 Region *R = RI.getRegionFor(BB);
1658 while (R->getEntry() == BB)
1659 R = R->getParent();
1660 return getDomainForBlock(R->getEntry(), DomainMap, RI);
1661}
1662
1663void Scop::propagateDomainConstraints(Region *R, LoopInfo &LI,
1664 ScopDetection &SD, DominatorTree &DT) {
1665 // Iterate over the region R and propagate the domain constrains from the
1666 // predecessors to the current node. In contrast to the
1667 // buildDomainsWithBranchConstraints function, this one will pull the domain
1668 // information from the predecessors instead of pushing it to the successors.
1669 // Additionally, we assume the domains to be already present in the domain
1670 // map here. However, we iterate again in reverse post order so we know all
1671 // predecessors have been visited before a block or non-affine subregion is
1672 // visited.
1673
1674 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
1675 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
1676
1677 ReversePostOrderTraversal<Region *> RTraversal(R);
1678 for (auto *RN : RTraversal) {
1679
1680 // Recurse for affine subregions but go on for basic blocks and non-affine
1681 // subregions.
1682 if (RN->isSubRegion()) {
1683 Region *SubRegion = RN->getNodeAs<Region>();
1684 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
1685 propagateDomainConstraints(SubRegion, LI, SD, DT);
1686 continue;
1687 }
1688 }
1689
1690 BasicBlock *BB = getRegionNodeBasicBlock(RN);
1691 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1692 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1693
1694 isl_set *&Domain = DomainMap[BB];
1695 assert(Domain && "Due to reverse post order traversal of the region all "
1696 "predecessor of the current region node should have been "
1697 "visited and a domain for this region node should have "
1698 "been set.");
1699
1700 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
1701 for (auto *PredBB : predecessors(BB)) {
1702
1703 // Skip backedges
1704 if (DT.dominates(BB, PredBB))
1705 continue;
1706
1707 isl_set *PredBBDom = nullptr;
1708
1709 // Handle the SCoP entry block with its outside predecessors.
1710 if (!getRegion().contains(PredBB))
1711 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
1712
1713 if (!PredBBDom) {
1714 // Determine the loop depth of the predecessor and adjust its domain to
1715 // the domain of the current block. This can mean we have to:
1716 // o) Drop a dimension if this block is the exit of a loop, not the
1717 // header of a new loop and the predecessor was part of the loop.
1718 // o) Add an unconstrainted new dimension if this block is the header
1719 // of a loop and the predecessor is not part of it.
1720 // o) Drop the information about the innermost loop dimension when the
1721 // predecessor and the current block are surrounded by different
1722 // loops in the same depth.
1723 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
1724 Loop *PredBBLoop = LI.getLoopFor(PredBB);
1725 while (BoxedLoops.count(PredBBLoop))
1726 PredBBLoop = PredBBLoop->getParentLoop();
1727
1728 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001729 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001730 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001731 PredBBDom = isl_set_project_out(
1732 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
1733 LoopDepthDiff);
1734 else if (PredBBLoopDepth < BBLoopDepth) {
1735 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001736 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001737 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
1738 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001739 PredBBDom = isl_set_drop_constraints_involving_dims(
1740 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001741 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001742 }
1743
1744 PredDom = isl_set_union(PredDom, PredBBDom);
1745 }
1746
1747 // Under the union of all predecessor conditions we can reach this block.
1748 Domain = isl_set_intersect(Domain, PredDom);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001749
1750 // Add assumptions for error blocks.
1751 if (isErrorBlock(*BB)) {
1752 IsOptimized = true;
1753 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
1754 addAssumption(isl_set_complement(DomPar));
1755 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001756 }
1757}
1758
1759/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
1760/// is incremented by one and all other dimensions are equal, e.g.,
1761/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
1762/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
1763static __isl_give isl_map *
1764createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
1765 auto *MapSpace = isl_space_map_from_set(SetSpace);
1766 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
1767 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
1768 if (u != Dim)
1769 NextIterationMap =
1770 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
1771 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
1772 C = isl_constraint_set_constant_si(C, 1);
1773 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
1774 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
1775 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
1776 return NextIterationMap;
1777}
1778
1779/// @brief Add @p L & all children to @p Loops if they are not in @p BoxedLoops.
1780static inline void
1781addLoopAndSubloops(Loop *L, SmallVectorImpl<Loop *> &Loops,
1782 const ScopDetection::BoxedLoopsSetTy &BoxedLoops) {
1783 if (BoxedLoops.count(L))
1784 return;
1785
1786 Loops.push_back(L);
1787 for (Loop *Subloop : *L)
1788 addLoopAndSubloops(Subloop, Loops, BoxedLoops);
1789}
1790
1791/// @brief Add loops in @p R to @p RegionLoops if they are not in @p BoxedLoops.
1792static inline void
1793collectLoopsInRegion(Region &R, LoopInfo &LI,
1794 SmallVector<Loop *, 8> &RegionLoops,
1795 const ScopDetection::BoxedLoopsSetTy &BoxedLoops) {
1796
1797 SmallVector<Loop *, 8> Loops(LI.begin(), LI.end());
1798 while (!Loops.empty()) {
1799 Loop *L = Loops.pop_back_val();
1800
1801 if (R.contains(L))
1802 addLoopAndSubloops(L, RegionLoops, BoxedLoops);
1803 else if (L->contains(R.getEntry()))
1804 Loops.append(L->begin(), L->end());
1805 }
1806}
1807
1808/// @brief Create a set from @p Space with @p Dim fixed to 0.
1809static __isl_give isl_set *
1810createFirstIterationDomain(__isl_take isl_space *Space, unsigned Dim) {
1811 auto *Domain = isl_set_universe(Space);
1812 Domain = isl_set_fix_si(Domain, isl_dim_set, Dim, 0);
1813 return Domain;
1814}
1815
1816void Scop::addLoopBoundsToHeaderDomains(LoopInfo &LI, ScopDetection &SD,
1817 DominatorTree &DT) {
1818 // We iterate over all loops in the SCoP, create the condition set under which
1819 // we will take the back edge, and then apply these restrictions to the
1820 // header.
1821
1822 Region &R = getRegion();
1823 SmallVector<Loop *, 8> RegionLoops;
1824 collectLoopsInRegion(R, LI, RegionLoops, *SD.getBoxedLoops(&R));
1825
1826 while (!RegionLoops.empty()) {
1827 Loop *L = RegionLoops.pop_back_val();
1828 int LoopDepth = getRelativeLoopDepth(L);
1829 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
1830
1831 BasicBlock *LatchBB = L->getLoopLatch();
1832 assert(LatchBB && "TODO implement multiple exit loop handling");
1833
1834 isl_set *LatchBBDom = DomainMap[LatchBB];
1835 isl_set *BackedgeCondition = nullptr;
1836
1837 BasicBlock *HeaderBB = L->getHeader();
1838
1839 BranchInst *BI = cast<BranchInst>(LatchBB->getTerminator());
1840 if (BI->isUnconditional())
1841 BackedgeCondition = isl_set_copy(LatchBBDom);
1842 else {
1843 SmallVector<isl_set *, 2> ConditionSets;
1844 int idx = BI->getSuccessor(0) != HeaderBB;
1845 buildConditionSets(*this, BI, L, LatchBBDom, ConditionSets);
1846
1847 // Free the non back edge condition set as we do not need it.
1848 isl_set_free(ConditionSets[1 - idx]);
1849
1850 BackedgeCondition = ConditionSets[idx];
1851 }
1852
1853 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
1854 isl_set *FirstIteration =
1855 createFirstIterationDomain(isl_set_get_space(HeaderBBDom), LoopDepth);
1856
1857 isl_map *NextIterationMap =
1858 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
1859
1860 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
1861 assert(LatchLoopDepth >= LoopDepth);
1862 BackedgeCondition =
1863 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
1864 LatchLoopDepth - LoopDepth);
1865
Johannes Doerfertca1e38f2015-09-14 11:12:52 +00001866 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
1867 for (int i = 0; i < LoopDepth; i++)
1868 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
1869
1870 isl_set *BackedgeConditionComplement =
1871 isl_set_complement(BackedgeCondition);
1872 BackedgeConditionComplement = isl_set_lower_bound_si(
1873 BackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
1874 BackedgeConditionComplement =
1875 isl_set_apply(BackedgeConditionComplement, ForwardMap);
1876 HeaderBBDom = isl_set_subtract(HeaderBBDom, BackedgeConditionComplement);
1877
1878 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001879
1880 // If a loop has an unbounded back edge condition part (here Parts.first)
1881 // we do not want to assume the header will even be executed for the first
1882 // iteration of an execution that will lead to an infinite loop. While it
1883 // would not be wrong to do so, it does not seem helpful.
Johannes Doerfertca1e38f2015-09-14 11:12:52 +00001884 // TODO: Use the unbounded part to build runtime assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001885 FirstIteration = isl_set_subtract(FirstIteration, Parts.first);
1886
Johannes Doerfertca1e38f2015-09-14 11:12:52 +00001887 HeaderBBDom = isl_set_apply(Parts.second, NextIterationMap);
1888 HeaderBBDom = isl_set_coalesce(isl_set_union(HeaderBBDom, FirstIteration));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001889
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001890 }
1891}
1892
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001893void Scop::buildAliasChecks(AliasAnalysis &AA) {
1894 if (!PollyUseRuntimeAliasChecks)
1895 return;
1896
1897 if (buildAliasGroups(AA))
1898 return;
1899
1900 // If a problem occurs while building the alias groups we need to delete
1901 // this SCoP and pretend it wasn't valid in the first place. To this end
1902 // we make the assumed context infeasible.
1903 addAssumption(isl_set_empty(getParamSpace()));
1904
1905 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
1906 << " could not be created as the number of parameters involved "
1907 "is too high. The SCoP will be "
1908 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
1909 "the maximal number of parameters but be advised that the "
1910 "compile time might increase exponentially.\n\n");
1911}
1912
Johannes Doerfert9143d672014-09-27 11:02:39 +00001913bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001914 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001915 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00001916 // for all memory accesses inside the SCoP.
1917 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001918 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00001919 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001920 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001921 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001922 // if their access domains intersect, otherwise they are in different
1923 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001924 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001925 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001926 // and maximal accesses to each array of a group in read only and non
1927 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00001928 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
1929
1930 AliasSetTracker AST(AA);
1931
1932 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00001933 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001934 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001935
1936 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001937 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001938 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
1939 isl_set_free(StmtDomain);
1940 if (StmtDomainEmpty)
1941 continue;
1942
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001943 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001944 if (MA->isScalar())
1945 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00001946 if (!MA->isRead())
1947 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001948 Instruction *Acc = MA->getAccessInstruction();
1949 PtrToAcc[getPointerOperand(*Acc)] = MA;
1950 AST.add(Acc);
1951 }
1952 }
1953
1954 SmallVector<AliasGroupTy, 4> AliasGroups;
1955 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00001956 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00001957 continue;
1958 AliasGroupTy AG;
1959 for (auto PR : AS)
1960 AG.push_back(PtrToAcc[PR.getValue()]);
1961 assert(AG.size() > 1 &&
1962 "Alias groups should contain at least two accesses");
1963 AliasGroups.push_back(std::move(AG));
1964 }
1965
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001966 // Split the alias groups based on their domain.
1967 for (unsigned u = 0; u < AliasGroups.size(); u++) {
1968 AliasGroupTy NewAG;
1969 AliasGroupTy &AG = AliasGroups[u];
1970 AliasGroupTy::iterator AGI = AG.begin();
1971 isl_set *AGDomain = getAccessDomain(*AGI);
1972 while (AGI != AG.end()) {
1973 MemoryAccess *MA = *AGI;
1974 isl_set *MADomain = getAccessDomain(MA);
1975 if (isl_set_is_disjoint(AGDomain, MADomain)) {
1976 NewAG.push_back(MA);
1977 AGI = AG.erase(AGI);
1978 isl_set_free(MADomain);
1979 } else {
1980 AGDomain = isl_set_union(AGDomain, MADomain);
1981 AGI++;
1982 }
1983 }
1984 if (NewAG.size() > 1)
1985 AliasGroups.push_back(std::move(NewAG));
1986 isl_set_free(AGDomain);
1987 }
1988
Tobias Grosserf4c24b22015-04-05 13:11:54 +00001989 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00001990 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
1991 for (AliasGroupTy &AG : AliasGroups) {
1992 NonReadOnlyBaseValues.clear();
1993 ReadOnlyPairs.clear();
1994
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001995 if (AG.size() < 2) {
1996 AG.clear();
1997 continue;
1998 }
1999
Johannes Doerfert13771732014-10-01 12:40:46 +00002000 for (auto II = AG.begin(); II != AG.end();) {
2001 Value *BaseAddr = (*II)->getBaseAddr();
2002 if (HasWriteAccess.count(BaseAddr)) {
2003 NonReadOnlyBaseValues.insert(BaseAddr);
2004 II++;
2005 } else {
2006 ReadOnlyPairs[BaseAddr].insert(*II);
2007 II = AG.erase(II);
2008 }
2009 }
2010
2011 // If we don't have read only pointers check if there are at least two
2012 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002013 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002014 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002015 continue;
2016 }
2017
2018 // If we don't have non read only pointers clear the alias group.
2019 if (NonReadOnlyBaseValues.empty()) {
2020 AG.clear();
2021 continue;
2022 }
2023
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002024 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002025 MinMaxAliasGroups.emplace_back();
2026 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2027 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2028 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2029 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002030
2031 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002032
2033 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002034 for (MemoryAccess *MA : AG)
2035 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002036
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002037 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2038 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002039
2040 // Bail out if the number of values we need to compare is too large.
2041 // This is important as the number of comparisions grows quadratically with
2042 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002043 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2044 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002045 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002046
2047 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002048 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002049 Accesses = isl_union_map_empty(getParamSpace());
2050
2051 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2052 for (MemoryAccess *MA : ReadOnlyPair.second)
2053 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2054
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002055 Valid =
2056 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002057
2058 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002059 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002060 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002061
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002062 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002063}
2064
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002065static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
2066 Loop *L = LI.getLoopFor(R.getEntry());
2067 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2068}
2069
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002070static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2071 ScopDetection &SD) {
2072
2073 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2074
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002075 unsigned MinLD = INT_MAX, MaxLD = 0;
2076 for (BasicBlock *BB : R.blocks()) {
2077 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002078 if (!R.contains(L))
2079 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002080 if (BoxedLoops && BoxedLoops->count(L))
2081 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002082 unsigned LD = L->getLoopDepth();
2083 MinLD = std::min(MinLD, LD);
2084 MaxLD = std::max(MaxLD, LD);
2085 }
2086 }
2087
2088 // Handle the case that there is no loop in the SCoP first.
2089 if (MaxLD == 0)
2090 return 1;
2091
2092 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2093 assert(MaxLD >= MinLD &&
2094 "Maximal loop depth was smaller than mininaml loop depth?");
2095 return MaxLD - MinLD + 1;
2096}
2097
Michael Kruse9d080092015-09-11 21:41:48 +00002098Scop::Scop(Region &R, AccFuncMapType &AccFuncMap,
2099 ScalarEvolution &ScalarEvolution, DominatorTree &DT,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002100 isl_ctx *Context, unsigned MaxLoopDepth)
Michael Kruse9d080092015-09-11 21:41:48 +00002101 : DT(DT), SE(&ScalarEvolution), R(R), AccFuncMap(AccFuncMap),
2102 IsOptimized(false), HasSingleExitEdge(R.getExitingBlock()),
2103 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Affinator(this) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002104
Michael Kruse9d080092015-09-11 21:41:48 +00002105void Scop::init(LoopInfo &LI, ScopDetection &SD, AliasAnalysis &AA) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002106 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00002107
Johannes Doerfert96425c22015-08-30 21:13:53 +00002108 buildDomains(&R, LI, SD, DT);
2109
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002110 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
Tobias Grosser75805372011-04-29 06:27:02 +00002111
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002112 Loop *L = getLoopSurroundingRegion(R, LI);
2113 LoopSchedules[L];
Michael Kruse9d080092015-09-11 21:41:48 +00002114 buildSchedule(&R, LI, SD, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002115 Schedule = LoopSchedules[L].first;
Tobias Grosser75805372011-04-29 06:27:02 +00002116
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002117 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002118 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002119 addUserContext();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002120 simplifyAssumedContext();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002121 buildAliasChecks(AA);
Tobias Grosser75805372011-04-29 06:27:02 +00002122}
2123
2124Scop::~Scop() {
2125 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002126 isl_set_free(AssumedContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002127 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002128
Johannes Doerfert96425c22015-08-30 21:13:53 +00002129 for (auto It : DomainMap)
2130 isl_set_free(It.second);
2131
Johannes Doerfertb164c792014-09-18 11:17:17 +00002132 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002133 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002134 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002135 isl_pw_multi_aff_free(MMA.first);
2136 isl_pw_multi_aff_free(MMA.second);
2137 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002138 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002139 isl_pw_multi_aff_free(MMA.first);
2140 isl_pw_multi_aff_free(MMA.second);
2141 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002142 }
Tobias Grosser75805372011-04-29 06:27:02 +00002143}
2144
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002145const ScopArrayInfo *
2146Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Tobias Grosser92245222015-07-28 14:53:44 +00002147 const SmallVector<const SCEV *, 4> &Sizes,
2148 bool IsPHI) {
2149 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)];
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002150 if (!SAI)
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002151 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, IsPHI,
2152 this));
Tobias Grosserab671442015-05-23 05:58:27 +00002153 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002154}
2155
Tobias Grosser92245222015-07-28 14:53:44 +00002156const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, bool IsPHI) {
2157 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002158 assert(SAI && "No ScopArrayInfo available for this base pointer");
2159 return SAI;
2160}
2161
Tobias Grosser74394f02013-01-14 22:40:23 +00002162std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002163std::string Scop::getAssumedContextStr() const {
2164 return stringFromIslObj(AssumedContext);
2165}
Tobias Grosser75805372011-04-29 06:27:02 +00002166
2167std::string Scop::getNameStr() const {
2168 std::string ExitName, EntryName;
2169 raw_string_ostream ExitStr(ExitName);
2170 raw_string_ostream EntryStr(EntryName);
2171
Tobias Grosserf240b482014-01-09 10:42:15 +00002172 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002173 EntryStr.str();
2174
2175 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00002176 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002177 ExitStr.str();
2178 } else
2179 ExitName = "FunctionExit";
2180
2181 return EntryName + "---" + ExitName;
2182}
2183
Tobias Grosser74394f02013-01-14 22:40:23 +00002184__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00002185__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002186 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00002187}
2188
Tobias Grossere86109f2013-10-29 21:05:49 +00002189__isl_give isl_set *Scop::getAssumedContext() const {
2190 return isl_set_copy(AssumedContext);
2191}
2192
Johannes Doerfert43788c52015-08-20 05:58:56 +00002193__isl_give isl_set *Scop::getRuntimeCheckContext() const {
2194 isl_set *RuntimeCheckContext = getAssumedContext();
2195 return RuntimeCheckContext;
2196}
2197
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002198bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002199 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002200 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002201 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
2202 isl_set_free(RuntimeCheckContext);
2203 return IsFeasible;
2204}
2205
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002206void Scop::addAssumption(__isl_take isl_set *Set) {
2207 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00002208 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002209}
2210
Tobias Grosser75805372011-04-29 06:27:02 +00002211void Scop::printContext(raw_ostream &OS) const {
2212 OS << "Context:\n";
2213
2214 if (!Context) {
2215 OS.indent(4) << "n/a\n\n";
2216 return;
2217 }
2218
2219 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00002220
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002221 OS.indent(4) << "Assumed Context:\n";
2222 if (!AssumedContext) {
2223 OS.indent(4) << "n/a\n\n";
2224 return;
2225 }
2226
2227 OS.indent(4) << getAssumedContextStr() << "\n";
2228
Tobias Grosser083d3d32014-06-28 08:59:45 +00002229 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00002230 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00002231 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
2232 }
Tobias Grosser75805372011-04-29 06:27:02 +00002233}
2234
Johannes Doerfertb164c792014-09-18 11:17:17 +00002235void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002236 int noOfGroups = 0;
2237 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002238 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002239 noOfGroups += 1;
2240 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002241 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002242 }
2243
Tobias Grosserbb853c22015-07-25 12:31:03 +00002244 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00002245 if (MinMaxAliasGroups.empty()) {
2246 OS.indent(8) << "n/a\n";
2247 return;
2248 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002249
Tobias Grosserbb853c22015-07-25 12:31:03 +00002250 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002251
2252 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002253 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002254 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002255 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002256 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2257 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002258 }
2259 OS << " ]]\n";
2260 }
2261
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002262 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002263 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00002264 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002265 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002266 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2267 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002268 }
2269 OS << " ]]\n";
2270 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002271 }
2272}
2273
Tobias Grosser75805372011-04-29 06:27:02 +00002274void Scop::printStatements(raw_ostream &OS) const {
2275 OS << "Statements {\n";
2276
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002277 for (const ScopStmt &Stmt : *this)
2278 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00002279
2280 OS.indent(4) << "}\n";
2281}
2282
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002283void Scop::printArrayInfo(raw_ostream &OS) const {
2284 OS << "Arrays {\n";
2285
Tobias Grosserab671442015-05-23 05:58:27 +00002286 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002287 Array.second->print(OS);
2288
2289 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002290
2291 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
2292
2293 for (auto &Array : arrays())
2294 Array.second->print(OS, /* SizeAsPwAff */ true);
2295
2296 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002297}
2298
Tobias Grosser75805372011-04-29 06:27:02 +00002299void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00002300 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
2301 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00002302 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00002303 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00002304 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002305 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002306 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00002307 printStatements(OS.indent(4));
2308}
2309
2310void Scop::dump() const { print(dbgs()); }
2311
Tobias Grosser9a38ab82011-11-08 15:41:03 +00002312isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00002313
Johannes Doerfertb409fdc2015-08-28 09:24:35 +00002314__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, isl_set *Domain) {
2315 return Affinator.getPwAff(E, Domain);
Johannes Doerfert574182d2015-08-12 10:19:50 +00002316}
2317
Tobias Grosser808cd692015-07-14 09:33:13 +00002318__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002319 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002320
Tobias Grosser808cd692015-07-14 09:33:13 +00002321 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002322 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002323
2324 return Domain;
2325}
2326
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002327__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002328 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002329
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002330 for (ScopStmt &Stmt : *this) {
2331 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002332 if (!MA->isMustWrite())
2333 continue;
2334
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002335 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002336 isl_map *AccessDomain = MA->getAccessRelation();
2337 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2338 Write = isl_union_map_add_map(Write, AccessDomain);
2339 }
2340 }
2341 return isl_union_map_coalesce(Write);
2342}
2343
2344__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002345 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002346
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002347 for (ScopStmt &Stmt : *this) {
2348 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002349 if (!MA->isMayWrite())
2350 continue;
2351
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002352 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002353 isl_map *AccessDomain = MA->getAccessRelation();
2354 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2355 Write = isl_union_map_add_map(Write, AccessDomain);
2356 }
2357 }
2358 return isl_union_map_coalesce(Write);
2359}
2360
Tobias Grosser37eb4222014-02-20 21:43:54 +00002361__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002362 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002363
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002364 for (ScopStmt &Stmt : *this) {
2365 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002366 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002367 continue;
2368
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002369 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002370 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002371 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2372 Write = isl_union_map_add_map(Write, AccessDomain);
2373 }
2374 }
2375 return isl_union_map_coalesce(Write);
2376}
2377
2378__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002379 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002380
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002381 for (ScopStmt &Stmt : *this) {
2382 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002383 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002384 continue;
2385
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002386 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002387 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002388
2389 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2390 Read = isl_union_map_add_map(Read, AccessDomain);
2391 }
2392 }
2393 return isl_union_map_coalesce(Read);
2394}
2395
Tobias Grosser808cd692015-07-14 09:33:13 +00002396__isl_give isl_union_map *Scop::getSchedule() const {
2397 auto Tree = getScheduleTree();
2398 auto S = isl_schedule_get_map(Tree);
2399 isl_schedule_free(Tree);
2400 return S;
2401}
Tobias Grosser37eb4222014-02-20 21:43:54 +00002402
Tobias Grosser808cd692015-07-14 09:33:13 +00002403__isl_give isl_schedule *Scop::getScheduleTree() const {
2404 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
2405 getDomains());
2406}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002407
Tobias Grosser808cd692015-07-14 09:33:13 +00002408void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
2409 auto *S = isl_schedule_from_domain(getDomains());
2410 S = isl_schedule_insert_partial_schedule(
2411 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
2412 isl_schedule_free(Schedule);
2413 Schedule = S;
2414}
2415
2416void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
2417 isl_schedule_free(Schedule);
2418 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00002419}
2420
2421bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
2422 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002423 for (ScopStmt &Stmt : *this) {
2424 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002425 isl_union_set *NewStmtDomain = isl_union_set_intersect(
2426 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
2427
2428 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
2429 isl_union_set_free(StmtDomain);
2430 isl_union_set_free(NewStmtDomain);
2431 continue;
2432 }
2433
2434 Changed = true;
2435
2436 isl_union_set_free(StmtDomain);
2437 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
2438
2439 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002440 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002441 isl_union_set_free(NewStmtDomain);
2442 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002443 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002444 }
2445 isl_union_set_free(Domain);
2446 return Changed;
2447}
2448
Tobias Grosser75805372011-04-29 06:27:02 +00002449ScalarEvolution *Scop::getSE() const { return SE; }
2450
Michael Kruse9d080092015-09-11 21:41:48 +00002451bool Scop::isTrivialBB(BasicBlock *BB) {
2452 if (getAccessFunctions(BB) && !isErrorBlock(*BB))
Tobias Grosser75805372011-04-29 06:27:02 +00002453 return false;
2454
2455 return true;
2456}
2457
Tobias Grosser808cd692015-07-14 09:33:13 +00002458struct MapToDimensionDataTy {
2459 int N;
2460 isl_union_pw_multi_aff *Res;
2461};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002462
Tobias Grosser808cd692015-07-14 09:33:13 +00002463// @brief Create a function that maps the elements of 'Set' to its N-th
2464// dimension.
2465//
2466// The result is added to 'User->Res'.
2467//
2468// @param Set The input set.
2469// @param N The dimension to map to.
2470//
2471// @returns Zero if no error occurred, non-zero otherwise.
2472static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
2473 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
2474 int Dim;
2475 isl_space *Space;
2476 isl_pw_multi_aff *PMA;
2477
2478 Dim = isl_set_dim(Set, isl_dim_set);
2479 Space = isl_set_get_space(Set);
2480 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
2481 Dim - Data->N);
2482 if (Data->N > 1)
2483 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
2484 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
2485
2486 isl_set_free(Set);
2487
2488 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002489}
2490
Tobias Grosser808cd692015-07-14 09:33:13 +00002491// @brief Create a function that maps the elements of Domain to their Nth
2492// dimension.
2493//
2494// @param Domain The set of elements to map.
2495// @param N The dimension to map to.
2496static __isl_give isl_multi_union_pw_aff *
2497mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002498 if (N <= 0 || isl_union_set_is_empty(Domain)) {
2499 isl_union_set_free(Domain);
2500 return nullptr;
2501 }
2502
Tobias Grosser808cd692015-07-14 09:33:13 +00002503 struct MapToDimensionDataTy Data;
2504 isl_space *Space;
2505
2506 Space = isl_union_set_get_space(Domain);
2507 Data.N = N;
2508 Data.Res = isl_union_pw_multi_aff_empty(Space);
2509 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
2510 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
2511
2512 isl_union_set_free(Domain);
2513 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
2514}
2515
Michael Kruse9d080092015-09-11 21:41:48 +00002516ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00002517 ScopStmt *Stmt;
2518 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00002519 Stmts.emplace_back(*this, *BB);
Tobias Grosser808cd692015-07-14 09:33:13 +00002520 Stmt = &Stmts.back();
2521 StmtMap[BB] = Stmt;
2522 } else {
2523 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00002524 Stmts.emplace_back(*this, *R);
Tobias Grosser808cd692015-07-14 09:33:13 +00002525 Stmt = &Stmts.back();
2526 for (BasicBlock *BB : R->blocks())
2527 StmtMap[BB] = Stmt;
2528 }
2529 return Stmt;
2530}
2531
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002532void Scop::buildSchedule(
Michael Kruse9d080092015-09-11 21:41:48 +00002533 Region *R, LoopInfo &LI, ScopDetection &SD,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002534 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00002535
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002536 ReversePostOrderTraversal<Region *> RTraversal(R);
2537 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00002538
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002539 if (RN->isSubRegion()) {
2540 Region *SubRegion = RN->getNodeAs<Region>();
2541 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Michael Kruse9d080092015-09-11 21:41:48 +00002542 buildSchedule(SubRegion, LI, SD, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002543 continue;
2544 }
Tobias Grosser75805372011-04-29 06:27:02 +00002545 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002546
2547 Loop *L = getRegionNodeLoop(RN, LI);
2548 int LD = getRelativeLoopDepth(L);
2549 auto &LSchedulePair = LoopSchedules[L];
2550 LSchedulePair.second += getNumBlocksInRegionNode(RN);
2551
2552 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Michael Kruse9d080092015-09-11 21:41:48 +00002553 if (RN->isSubRegion() || !isTrivialBB(BB)) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002554
2555 ScopStmt *Stmt;
2556 if (RN->isSubRegion())
Michael Kruse9d080092015-09-11 21:41:48 +00002557 Stmt = addScopStmt(nullptr, RN->getNodeAs<Region>());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002558 else
Michael Kruse9d080092015-09-11 21:41:48 +00002559 Stmt = addScopStmt(BB, nullptr);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002560
2561 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
2562 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
2563 LSchedulePair.first =
2564 combineInSequence(LSchedulePair.first, StmtSchedule);
2565 }
2566
2567 unsigned NumVisited = LSchedulePair.second;
2568 while (L && NumVisited == L->getNumBlocks()) {
2569 auto *LDomain = isl_schedule_get_domain(LSchedulePair.first);
2570 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
2571 LSchedulePair.first =
2572 isl_schedule_insert_partial_schedule(LSchedulePair.first, MUPA);
2573
2574 auto *PL = L->getParentLoop();
2575 assert(LoopSchedules.count(PL));
2576 auto &PSchedulePair = LoopSchedules[PL];
2577 PSchedulePair.first =
2578 combineInSequence(PSchedulePair.first, LSchedulePair.first);
2579 PSchedulePair.second += NumVisited;
2580
2581 L = PL;
2582 NumVisited = PSchedulePair.second;
2583 }
Tobias Grosser808cd692015-07-14 09:33:13 +00002584 }
Tobias Grosser75805372011-04-29 06:27:02 +00002585}
2586
Johannes Doerfert7c494212014-10-31 23:13:39 +00002587ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00002588 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00002589 if (StmtMapIt == StmtMap.end())
2590 return nullptr;
2591 return StmtMapIt->second;
2592}
2593
Michael Kruse9d080092015-09-11 21:41:48 +00002594void Scop::printIRAccesses(raw_ostream &OS, ScalarEvolution *SE,
2595 LoopInfo *LI) const {
Michael Kruse7bf39442015-09-10 12:46:52 +00002596 OS << "Scop: " << R.getNameStr() << "\n";
2597
Michael Kruse9d080092015-09-11 21:41:48 +00002598 printIRAccessesDetail(OS, SE, LI, &R, 0);
Michael Kruse7bf39442015-09-10 12:46:52 +00002599}
2600
Michael Kruse9d080092015-09-11 21:41:48 +00002601void Scop::printIRAccessesDetail(raw_ostream &OS, ScalarEvolution *SE,
2602 LoopInfo *LI, const Region *CurR,
2603 unsigned ind) const {
Michael Kruse7bf39442015-09-10 12:46:52 +00002604 // FIXME: Print other details rather than memory accesses.
2605 for (const auto &CurBlock : CurR->blocks()) {
2606 AccFuncMapType::const_iterator AccSetIt = AccFuncMap.find(CurBlock);
2607
2608 // Ignore trivial blocks that do not contain any memory access.
2609 if (AccSetIt == AccFuncMap.end())
2610 continue;
2611
2612 OS.indent(ind) << "BB: " << CurBlock->getName() << '\n';
2613 typedef AccFuncSetType::const_iterator access_iterator;
2614 const AccFuncSetType &AccFuncs = AccSetIt->second;
2615
2616 for (access_iterator AI = AccFuncs.begin(), AE = AccFuncs.end(); AI != AE;
2617 ++AI)
2618 AI->first.print(OS.indent(ind + 2));
2619 }
2620}
2621
Johannes Doerfert96425c22015-08-30 21:13:53 +00002622int Scop::getRelativeLoopDepth(const Loop *L) const {
2623 Loop *OuterLoop =
2624 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
2625 if (!OuterLoop)
2626 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00002627 return L->getLoopDepth() - OuterLoop->getLoopDepth();
2628}
2629
Michael Krused868b5d2015-09-10 15:25:24 +00002630void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
2631 AccFuncSetType &Functions,
2632 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002633
2634 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
2635 // true, are not modeled as ordinary PHI nodes as they are not part of the
2636 // region. However, we model the operands in the predecessor blocks that are
2637 // part of the region as regular scalar accesses.
2638
2639 // If we can synthesize a PHI we can skip it, however only if it is in
2640 // the region. If it is not it can only be in the exit block of the region.
2641 // In this case we model the operands but not the PHI itself.
2642 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
2643 return;
2644
2645 // PHI nodes are modeled as if they had been demoted prior to the SCoP
2646 // detection. Hence, the PHI is a load of a new memory location in which the
2647 // incoming value was written at the end of the incoming basic block.
2648 bool OnlyNonAffineSubRegionOperands = true;
2649 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
2650 Value *Op = PHI->getIncomingValue(u);
2651 BasicBlock *OpBB = PHI->getIncomingBlock(u);
2652
2653 // Do not build scalar dependences inside a non-affine subregion.
2654 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
2655 continue;
2656
2657 OnlyNonAffineSubRegionOperands = false;
2658
2659 if (!R.contains(OpBB))
2660 continue;
2661
2662 Instruction *OpI = dyn_cast<Instruction>(Op);
2663 if (OpI) {
2664 BasicBlock *OpIBB = OpI->getParent();
2665 // As we pretend there is a use (or more precise a write) of OpI in OpBB
2666 // we have to insert a scalar dependence from the definition of OpI to
2667 // OpBB if the definition is not in OpBB.
2668 if (OpIBB != OpBB) {
2669 IRAccess ScalarRead(IRAccess::READ, OpI, ZeroOffset, 1, true, OpI);
2670 AccFuncMap[OpBB].push_back(std::make_pair(ScalarRead, PHI));
2671 IRAccess ScalarWrite(IRAccess::MUST_WRITE, OpI, ZeroOffset, 1, true,
2672 OpI);
2673 AccFuncMap[OpIBB].push_back(std::make_pair(ScalarWrite, OpI));
2674 }
2675 }
2676
2677 // Always use the terminator of the incoming basic block as the access
2678 // instruction.
2679 OpI = OpBB->getTerminator();
2680
2681 IRAccess ScalarAccess(IRAccess::MUST_WRITE, PHI, ZeroOffset, 1, true, Op,
2682 /* IsPHI */ !IsExitBlock);
2683 AccFuncMap[OpBB].push_back(std::make_pair(ScalarAccess, OpI));
2684 }
2685
2686 if (!OnlyNonAffineSubRegionOperands) {
2687 IRAccess ScalarAccess(IRAccess::READ, PHI, ZeroOffset, 1, true, PHI,
2688 /* IsPHI */ !IsExitBlock);
2689 Functions.push_back(std::make_pair(ScalarAccess, PHI));
2690 }
2691}
2692
Michael Krused868b5d2015-09-10 15:25:24 +00002693bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
2694 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002695 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
2696 if (isIgnoredIntrinsic(Inst))
2697 return false;
2698
2699 bool AnyCrossStmtUse = false;
2700 BasicBlock *ParentBB = Inst->getParent();
2701
2702 for (User *U : Inst->users()) {
2703 Instruction *UI = dyn_cast<Instruction>(U);
2704
2705 // Ignore the strange user
2706 if (UI == 0)
2707 continue;
2708
2709 BasicBlock *UseParent = UI->getParent();
2710
2711 // Ignore the users in the same BB (statement)
2712 if (UseParent == ParentBB)
2713 continue;
2714
2715 // Do not build scalar dependences inside a non-affine subregion.
2716 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
2717 continue;
2718
2719 // Check whether or not the use is in the SCoP.
2720 if (!R->contains(UseParent)) {
2721 AnyCrossStmtUse = true;
2722 continue;
2723 }
2724
2725 // If the instruction can be synthesized and the user is in the region
2726 // we do not need to add scalar dependences.
2727 if (canSynthesizeInst)
2728 continue;
2729
2730 // No need to translate these scalar dependences into polyhedral form,
2731 // because synthesizable scalars can be generated by the code generator.
2732 if (canSynthesize(UI, LI, SE, R))
2733 continue;
2734
2735 // Skip PHI nodes in the region as they handle their operands on their own.
2736 if (isa<PHINode>(UI))
2737 continue;
2738
2739 // Now U is used in another statement.
2740 AnyCrossStmtUse = true;
2741
2742 // Do not build a read access that is not in the current SCoP
2743 // Use the def instruction as base address of the IRAccess, so that it will
2744 // become the name of the scalar access in the polyhedral form.
2745 IRAccess ScalarAccess(IRAccess::READ, Inst, ZeroOffset, 1, true, Inst);
2746 AccFuncMap[UseParent].push_back(std::make_pair(ScalarAccess, UI));
2747 }
2748
2749 if (ModelReadOnlyScalars) {
2750 for (Value *Op : Inst->operands()) {
2751 if (canSynthesize(Op, LI, SE, R))
2752 continue;
2753
2754 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
2755 if (R->contains(OpInst))
2756 continue;
2757
2758 if (isa<Constant>(Op))
2759 continue;
2760
2761 IRAccess ScalarAccess(IRAccess::READ, Op, ZeroOffset, 1, true, Op);
2762 AccFuncMap[Inst->getParent()].push_back(
2763 std::make_pair(ScalarAccess, Inst));
2764 }
2765 }
2766
2767 return AnyCrossStmtUse;
2768}
2769
2770extern MapInsnToMemAcc InsnToMemAcc;
2771
2772IRAccess
Michael Krused868b5d2015-09-10 15:25:24 +00002773ScopInfo::buildIRAccess(Instruction *Inst, Loop *L, Region *R,
2774 const ScopDetection::BoxedLoopsSetTy *BoxedLoops) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002775 unsigned Size;
2776 Type *SizeType;
2777 Value *Val;
2778 enum IRAccess::TypeKind Type;
2779
2780 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
2781 SizeType = Load->getType();
2782 Size = TD->getTypeStoreSize(SizeType);
2783 Type = IRAccess::READ;
2784 Val = Load;
2785 } else {
2786 StoreInst *Store = cast<StoreInst>(Inst);
2787 SizeType = Store->getValueOperand()->getType();
2788 Size = TD->getTypeStoreSize(SizeType);
2789 Type = IRAccess::MUST_WRITE;
2790 Val = Store->getValueOperand();
2791 }
2792
2793 const SCEV *AccessFunction = SE->getSCEVAtScope(getPointerOperand(*Inst), L);
2794 const SCEVUnknown *BasePointer =
2795 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
2796
2797 assert(BasePointer && "Could not find base pointer");
2798 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
2799
2800 auto AccItr = InsnToMemAcc.find(Inst);
2801 if (PollyDelinearize && AccItr != InsnToMemAcc.end())
2802 return IRAccess(Type, BasePointer->getValue(), AccessFunction, Size, true,
2803 AccItr->second.DelinearizedSubscripts,
2804 AccItr->second.Shape->DelinearizedSizes, Val);
2805
2806 // Check if the access depends on a loop contained in a non-affine subregion.
2807 bool isVariantInNonAffineLoop = false;
2808 if (BoxedLoops) {
2809 SetVector<const Loop *> Loops;
2810 findLoops(AccessFunction, Loops);
2811 for (const Loop *L : Loops)
2812 if (BoxedLoops->count(L))
2813 isVariantInNonAffineLoop = true;
2814 }
2815
2816 bool IsAffine = !isVariantInNonAffineLoop &&
2817 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue());
2818
2819 SmallVector<const SCEV *, 4> Subscripts, Sizes;
2820 Subscripts.push_back(AccessFunction);
2821 Sizes.push_back(SE->getConstant(ZeroOffset->getType(), Size));
2822
2823 if (!IsAffine && Type == IRAccess::MUST_WRITE)
2824 Type = IRAccess::MAY_WRITE;
2825
2826 return IRAccess(Type, BasePointer->getValue(), AccessFunction, Size, IsAffine,
2827 Subscripts, Sizes, Val);
2828}
2829
Michael Krused868b5d2015-09-10 15:25:24 +00002830void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002831
2832 if (SD->isNonAffineSubRegion(&SR, &R)) {
2833 for (BasicBlock *BB : SR.blocks())
2834 buildAccessFunctions(R, *BB, &SR);
2835 return;
2836 }
2837
2838 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
2839 if (I->isSubRegion())
2840 buildAccessFunctions(R, *I->getNodeAs<Region>());
2841 else
2842 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
2843}
2844
Michael Krused868b5d2015-09-10 15:25:24 +00002845void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
2846 Region *NonAffineSubRegion,
2847 bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002848 AccFuncSetType Functions;
2849 Loop *L = LI->getLoopFor(&BB);
2850
2851 // The set of loops contained in non-affine subregions that are part of R.
2852 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
2853
2854 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
2855 Instruction *Inst = I;
2856
2857 PHINode *PHI = dyn_cast<PHINode>(Inst);
2858 if (PHI)
2859 buildPHIAccesses(PHI, R, Functions, NonAffineSubRegion, IsExitBlock);
2860
2861 // For the exit block we stop modeling after the last PHI node.
2862 if (!PHI && IsExitBlock)
2863 break;
2864
2865 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
2866 Functions.push_back(
2867 std::make_pair(buildIRAccess(Inst, L, &R, BoxedLoops), Inst));
2868
2869 if (isIgnoredIntrinsic(Inst))
2870 continue;
2871
2872 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
2873 // If the Instruction is used outside the statement, we need to build the
2874 // write access.
2875 if (!isa<StoreInst>(Inst)) {
2876 IRAccess ScalarAccess(IRAccess::MUST_WRITE, Inst, ZeroOffset, 1, true,
2877 Inst);
2878 Functions.push_back(std::make_pair(ScalarAccess, Inst));
2879 }
2880 }
2881 }
2882
2883 if (Functions.empty())
2884 return;
2885
2886 AccFuncSetType &Accs = AccFuncMap[&BB];
2887 Accs.insert(Accs.end(), Functions.begin(), Functions.end());
2888}
2889
Michael Kruse9d080092015-09-11 21:41:48 +00002890Scop *ScopInfo::buildScop(Region &R, DominatorTree &DT) {
2891 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
2892 Scop *S = new Scop(R, AccFuncMap, *SE, DT, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00002893
2894 buildAccessFunctions(R, R);
2895
2896 // In case the region does not have an exiting block we will later (during
2897 // code generation) split the exit block. This will move potential PHI nodes
2898 // from the current exit block into the new region exiting block. Hence, PHI
2899 // nodes that are at this point not part of the region will be.
2900 // To handle these PHI nodes later we will now model their operands as scalar
2901 // accesses. Note that we do not model anything in the exit block if we have
2902 // an exiting block in the region, as there will not be any splitting later.
2903 if (!R.getExitingBlock())
2904 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
2905
Michael Kruse9d080092015-09-11 21:41:48 +00002906 S->init(*LI, *SD, *AA);
2907 return S;
Michael Kruse7bf39442015-09-10 12:46:52 +00002908}
2909
Michael Krused868b5d2015-09-10 15:25:24 +00002910void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00002911 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00002912 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00002913 return;
2914 }
2915
2916 scop->printIRAccesses(OS, SE, LI);
2917 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00002918}
2919
Michael Krused868b5d2015-09-10 15:25:24 +00002920void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00002921 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00002922 if (scop) {
2923 delete scop;
2924 scop = 0;
2925 }
Michael Kruse7bf39442015-09-10 12:46:52 +00002926}
2927
2928//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00002929ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00002930 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00002931 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00002932}
2933
2934ScopInfo::~ScopInfo() {
2935 clear();
2936 isl_ctx_free(ctx);
2937}
2938
Tobias Grosser75805372011-04-29 06:27:02 +00002939void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Michael Krused868b5d2015-09-10 15:25:24 +00002940 AU.addRequiredID(IndependentBlocksID);
Chandler Carruthf5579872015-01-17 14:16:56 +00002941 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00002942 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00002943 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00002944 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
2945 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00002946 AU.addRequired<AAResultsWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00002947 AU.setPreservesAll();
2948}
2949
2950bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00002951 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00002952
Michael Krused868b5d2015-09-10 15:25:24 +00002953 if (!SD->isMaxRegionInScop(*R))
2954 return false;
2955
2956 Function *F = R->getEntry()->getParent();
2957 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2958 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2959 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2960 TD = &F->getParent()->getDataLayout();
2961 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2962 ZeroOffset = SE->getConstant(TD->getIntPtrType(F->getContext()), 0);
2963
Michael Kruse9d080092015-09-11 21:41:48 +00002964 scop = buildScop(*R, DT);
Tobias Grosser75805372011-04-29 06:27:02 +00002965
Tobias Grosserd6a50b32015-05-30 06:26:21 +00002966 DEBUG(scop->print(dbgs()));
2967
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002968 if (!scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002969 delete scop;
2970 scop = nullptr;
2971 return false;
2972 }
2973
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002974 // Statistics.
2975 ++ScopFound;
2976 if (scop->getMaxLoopDepth() > 0)
2977 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00002978 return false;
2979}
2980
2981char ScopInfo::ID = 0;
2982
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002983Pass *polly::createScopInfoPass() { return new ScopInfo(); }
2984
Tobias Grosser73600b82011-10-08 00:30:40 +00002985INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
2986 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002987 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00002988INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00002989INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00002990INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00002991INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002992INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002993INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00002994INITIALIZE_PASS_END(ScopInfo, "polly-scops",
2995 "Polly - Create polyhedral description of Scops", false,
2996 false)