blob: e27026fb18ebdc3757d1c2cfeaaf6fdaffe44a40 [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 Doerfertb164c792014-09-18 11:17:17 +000033#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000034#include "llvm/Analysis/LoopInfo.h"
Tobias Grosser83628182013-05-07 08:11:54 +000035#include "llvm/Analysis/RegionIterator.h"
36#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser75805372011-04-29 06:27:02 +000037#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000038#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000039#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000040#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000041#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000042#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000043#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000044#include "isl/schedule.h"
45#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000046#include "isl/set.h"
47#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000048#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000049#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000050#include <sstream>
51#include <string>
52#include <vector>
53
54using namespace llvm;
55using namespace polly;
56
Chandler Carruth95fef942014-04-22 03:30:19 +000057#define DEBUG_TYPE "polly-scops"
58
Tobias Grosser74394f02013-01-14 22:40:23 +000059STATISTIC(ScopFound, "Number of valid Scops");
60STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000061
Michael Kruse7bf39442015-09-10 12:46:52 +000062static cl::opt<bool> ModelReadOnlyScalars(
63 "polly-analyze-read-only-scalars",
64 cl::desc("Model read-only scalar values in the scop description"),
65 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
66
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000067// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000068// operations can overflow easily. Additive reductions and bit operations
69// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000070static cl::opt<bool> DisableMultiplicativeReductions(
71 "polly-disable-multiplicative-reductions",
72 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
73 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000074
Johannes Doerfert9143d672014-09-27 11:02:39 +000075static cl::opt<unsigned> RunTimeChecksMaxParameters(
76 "polly-rtc-max-parameters",
77 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
78 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
79
Tobias Grosser71500722015-03-28 15:11:14 +000080static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
81 "polly-rtc-max-arrays-per-group",
82 cl::desc("The maximal number of arrays to compare in each alias group."),
83 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000084static cl::opt<std::string> UserContextStr(
85 "polly-context", cl::value_desc("isl parameter set"),
86 cl::desc("Provide additional constraints on the context parameters"),
87 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000088
Tobias Grosserd83b8a82015-08-20 19:08:11 +000089static cl::opt<bool> DetectReductions("polly-detect-reductions",
90 cl::desc("Detect and exploit reductions"),
91 cl::Hidden, cl::ZeroOrMore,
92 cl::init(true), cl::cat(PollyCategory));
93
Michael Kruse7bf39442015-09-10 12:46:52 +000094//===----------------------------------------------------------------------===//
95/// Helper Classes
96
97void Comparison::print(raw_ostream &OS) const {
98 // Not yet implemented.
99}
100
Michael Kruse046dde42015-08-10 13:01:57 +0000101// Create a sequence of two schedules. Either argument may be null and is
102// interpreted as the empty schedule. Can also return null if both schedules are
103// empty.
104static __isl_give isl_schedule *
105combineInSequence(__isl_take isl_schedule *Prev,
106 __isl_take isl_schedule *Succ) {
107 if (!Prev)
108 return Succ;
109 if (!Succ)
110 return Prev;
111
112 return isl_schedule_sequence(Prev, Succ);
113}
114
Johannes Doerferte7044942015-02-24 11:58:30 +0000115static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
116 const ConstantRange &Range,
117 int dim,
118 enum isl_dim_type type) {
119 isl_val *V;
120 isl_ctx *ctx = isl_set_get_ctx(S);
121
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000122 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
123 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000124 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000125 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
126
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000127 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000128 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000129 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000130 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000131 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
132
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000133 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000134 return isl_set_union(SLB, SUB);
135 else
136 return isl_set_intersect(SLB, SUB);
137}
138
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000139static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
140 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
141 if (!BasePtrLI)
142 return nullptr;
143
144 if (!S->getRegion().contains(BasePtrLI))
145 return nullptr;
146
147 ScalarEvolution &SE = *S->getSE();
148
149 auto *OriginBaseSCEV =
150 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
151 if (!OriginBaseSCEV)
152 return nullptr;
153
154 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
155 if (!OriginBaseSCEVUnknown)
156 return nullptr;
157
158 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue());
159}
160
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000161ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grosser92245222015-07-28 14:53:44 +0000162 const SmallVector<const SCEV *, 4> &DimensionSizes,
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000163 bool IsPHI, Scop *S)
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000164 : BasePtr(BasePtr), ElementType(ElementType),
Tobias Grosser92245222015-07-28 14:53:44 +0000165 DimensionSizes(DimensionSizes), IsPHI(IsPHI) {
166 std::string BasePtrName =
167 getIslCompatibleName("MemRef_", BasePtr, IsPHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000168 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000169 for (const SCEV *Expr : DimensionSizes) {
170 isl_pw_aff *Size = S->getPwAff(Expr);
171 DimensionSizesPw.push_back(Size);
172 }
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000173
174 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
175 if (BasePtrOriginSAI)
176 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000177}
178
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000179ScopArrayInfo::~ScopArrayInfo() {
180 isl_id_free(Id);
181 for (isl_pw_aff *Size : DimensionSizesPw)
182 isl_pw_aff_free(Size);
183}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000184
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000185std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
186
187int ScopArrayInfo::getElemSizeInBytes() const {
188 return ElementType->getPrimitiveSizeInBits() / 8;
189}
190
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000191isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
192
193void ScopArrayInfo::dump() const { print(errs()); }
194
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000195void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000196 OS.indent(8) << *getElementType() << " " << getName() << "[*]";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000197 for (unsigned u = 0; u < getNumberOfDimensions(); u++) {
198 OS << "[";
199
200 if (SizeAsPwAff)
201 OS << " " << DimensionSizesPw[u] << " ";
202 else
203 OS << *DimensionSizes[u];
204
205 OS << "]";
206 }
207
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000208 if (BasePtrOriginSAI)
209 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
210
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000211 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000212}
213
214const ScopArrayInfo *
215ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
216 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
217 assert(Id && "Output dimension didn't have an ID");
218 return getFromId(Id);
219}
220
221const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
222 void *User = isl_id_get_user(Id);
223 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
224 isl_id_free(Id);
225 return SAI;
226}
227
Michael Kruse7bf39442015-09-10 12:46:52 +0000228void IRAccess::print(raw_ostream &OS) const {
229 if (isRead())
230 OS << "Read ";
231 else {
232 if (isMayWrite())
233 OS << "May";
234 OS << "Write ";
235 }
236 OS << BaseAddress->getName() << '[' << *Offset << "]\n";
237}
238
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000239const std::string
240MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
241 switch (RT) {
242 case MemoryAccess::RT_NONE:
243 llvm_unreachable("Requested a reduction operator string for a memory "
244 "access which isn't a reduction");
245 case MemoryAccess::RT_ADD:
246 return "+";
247 case MemoryAccess::RT_MUL:
248 return "*";
249 case MemoryAccess::RT_BOR:
250 return "|";
251 case MemoryAccess::RT_BXOR:
252 return "^";
253 case MemoryAccess::RT_BAND:
254 return "&";
255 }
256 llvm_unreachable("Unknown reduction type");
257 return "";
258}
259
Johannes Doerfertf6183392014-07-01 20:52:51 +0000260/// @brief Return the reduction type for a given binary operator
261static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
262 const Instruction *Load) {
263 if (!BinOp)
264 return MemoryAccess::RT_NONE;
265 switch (BinOp->getOpcode()) {
266 case Instruction::FAdd:
267 if (!BinOp->hasUnsafeAlgebra())
268 return MemoryAccess::RT_NONE;
269 // Fall through
270 case Instruction::Add:
271 return MemoryAccess::RT_ADD;
272 case Instruction::Or:
273 return MemoryAccess::RT_BOR;
274 case Instruction::Xor:
275 return MemoryAccess::RT_BXOR;
276 case Instruction::And:
277 return MemoryAccess::RT_BAND;
278 case Instruction::FMul:
279 if (!BinOp->hasUnsafeAlgebra())
280 return MemoryAccess::RT_NONE;
281 // Fall through
282 case Instruction::Mul:
283 if (DisableMultiplicativeReductions)
284 return MemoryAccess::RT_NONE;
285 return MemoryAccess::RT_MUL;
286 default:
287 return MemoryAccess::RT_NONE;
288 }
289}
Tobias Grosser75805372011-04-29 06:27:02 +0000290//===----------------------------------------------------------------------===//
291
292MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000293 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000294 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000295 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000296}
297
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000298static MemoryAccess::AccessType getMemoryAccessType(const IRAccess &Access) {
299 switch (Access.getType()) {
300 case IRAccess::READ:
301 return MemoryAccess::READ;
302 case IRAccess::MUST_WRITE:
303 return MemoryAccess::MUST_WRITE;
304 case IRAccess::MAY_WRITE:
305 return MemoryAccess::MAY_WRITE;
306 }
307 llvm_unreachable("Unknown IRAccess type!");
308}
309
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000310const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
311 isl_id *ArrayId = getArrayId();
312 void *User = isl_id_get_user(ArrayId);
313 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
314 isl_id_free(ArrayId);
315 return SAI;
316}
317
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000318__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000319 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
320}
321
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000322__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
323 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000324 isl_map *Schedule, *ScheduledAccRel;
325 isl_union_set *UDomain;
326
327 UDomain = isl_union_set_from_set(getStatement()->getDomain());
328 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
329 Schedule = isl_map_from_union_map(USchedule);
330 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
331 return isl_pw_multi_aff_from_map(ScheduledAccRel);
332}
333
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000334__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000335 return isl_map_copy(AccessRelation);
336}
337
Johannes Doerferta99130f2014-10-13 12:58:03 +0000338std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000339 return stringFromIslObj(AccessRelation);
340}
341
Johannes Doerferta99130f2014-10-13 12:58:03 +0000342__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000343 return isl_map_get_space(AccessRelation);
344}
345
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000346__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000347 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000348}
349
Tobias Grosser6f730082015-09-05 07:46:47 +0000350std::string MemoryAccess::getNewAccessRelationStr() const {
351 return stringFromIslObj(NewAccessRelation);
352}
353
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000354__isl_give isl_basic_map *
355MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000356 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000357 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000358
Tobias Grosser084d8f72012-05-29 09:29:44 +0000359 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000360 isl_basic_set_universe(Statement->getDomainSpace()),
361 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000362}
363
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000364// Formalize no out-of-bound access assumption
365//
366// When delinearizing array accesses we optimistically assume that the
367// delinearized accesses do not access out of bound locations (the subscript
368// expression of each array evaluates for each statement instance that is
369// executed to a value that is larger than zero and strictly smaller than the
370// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000371// dimension for which we do not need to assume any upper bound. At this point
372// we formalize this assumption to ensure that at code generation time the
373// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000374//
375// To find the set of constraints necessary to avoid out of bound accesses, we
376// first build the set of data locations that are not within array bounds. We
377// then apply the reverse access relation to obtain the set of iterations that
378// may contain invalid accesses and reduce this set of iterations to the ones
379// that are actually executed by intersecting them with the domain of the
380// statement. If we now project out all loop dimensions, we obtain a set of
381// parameters that may cause statement instances to be executed that may
382// possibly yield out of bound memory accesses. The complement of these
383// constraints is the set of constraints that needs to be assumed to ensure such
384// statement instances are never executed.
385void MemoryAccess::assumeNoOutOfBound(const IRAccess &Access) {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000386 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000387 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000388 for (int i = 1, Size = Access.Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000389 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
390 isl_pw_aff *Var =
391 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
392 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
393
394 isl_set *DimOutside;
395
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000396 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfert574182d2015-08-12 10:19:50 +0000397 isl_pw_aff *SizeE = Statement->getPwAff(Access.Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000398
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000399 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
400 Statement->getNumIterators());
401 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
402 isl_space_dim(Space, isl_dim_set));
403 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
404 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000405
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000406 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000407
408 Outside = isl_set_union(Outside, DimOutside);
409 }
410
411 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
412 Outside = isl_set_intersect(Outside, Statement->getDomain());
413 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000414
415 // Remove divs to avoid the construction of overly complicated assumptions.
416 // Doing so increases the set of parameter combinations that are assumed to
417 // not appear. This is always save, but may make the resulting run-time check
418 // bail out more often than strictly necessary.
419 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000420 Outside = isl_set_complement(Outside);
421 Statement->getParent()->addAssumption(Outside);
422 isl_space_free(Space);
423}
424
Johannes Doerferte7044942015-02-24 11:58:30 +0000425void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
426 ScalarEvolution *SE = Statement->getParent()->getSE();
427
428 Value *Ptr = getPointerOperand(*getAccessInstruction());
429 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
430 return;
431
432 auto *PtrSCEV = SE->getSCEV(Ptr);
433 if (isa<SCEVCouldNotCompute>(PtrSCEV))
434 return;
435
436 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
437 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
438 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
439
440 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
441 if (Range.isFullSet())
442 return;
443
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000444 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000445 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000446 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
447 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
448
449 auto Min = LB.sdiv(APInt(BW, ElementSize));
450 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000451
452 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
453 AccessRange =
454 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
455 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
456}
457
Tobias Grosser619190d2015-03-30 17:22:28 +0000458__isl_give isl_map *MemoryAccess::foldAccess(const IRAccess &Access,
459 __isl_take isl_map *AccessRelation,
460 ScopStmt *Statement) {
461 int Size = Access.Subscripts.size();
462
463 for (int i = Size - 2; i >= 0; --i) {
464 isl_space *Space;
465 isl_map *MapOne, *MapTwo;
Johannes Doerfert574182d2015-08-12 10:19:50 +0000466 isl_pw_aff *DimSize = Statement->getPwAff(Access.Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000467
468 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
469 isl_pw_aff_free(DimSize);
470 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
471
472 Space = isl_map_get_space(AccessRelation);
473 Space = isl_space_map_from_set(isl_space_range(Space));
474 Space = isl_space_align_params(Space, SpaceSize);
475
476 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
477 isl_id_free(ParamId);
478
479 MapOne = isl_map_universe(isl_space_copy(Space));
480 for (int j = 0; j < Size; ++j)
481 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
482 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
483
484 MapTwo = isl_map_universe(isl_space_copy(Space));
485 for (int j = 0; j < Size; ++j)
486 if (j < i || j > i + 1)
487 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
488
489 isl_local_space *LS = isl_local_space_from_space(Space);
490 isl_constraint *C;
491 C = isl_equality_alloc(isl_local_space_copy(LS));
492 C = isl_constraint_set_constant_si(C, -1);
493 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
494 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
495 MapTwo = isl_map_add_constraint(MapTwo, C);
496 C = isl_equality_alloc(LS);
497 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
498 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
499 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
500 MapTwo = isl_map_add_constraint(MapTwo, C);
501 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
502
503 MapOne = isl_map_union(MapOne, MapTwo);
504 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
505 }
506 return AccessRelation;
507}
508
Johannes Doerfert13c8cf22014-08-10 08:09:38 +0000509MemoryAccess::MemoryAccess(const IRAccess &Access, Instruction *AccInst,
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000510 ScopStmt *Statement, const ScopArrayInfo *SAI,
511 int Identifier)
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000512 : AccType(getMemoryAccessType(Access)), Statement(Statement),
513 AccessInstruction(AccInst), AccessValue(Access.getAccessValue()),
Tobias Grosser166c4222015-09-05 07:46:40 +0000514 NewAccessRelation(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +0000515
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000516 isl_ctx *Ctx = Statement->getIslCtx();
Tobias Grosser9759f852011-11-10 12:44:55 +0000517 BaseAddr = Access.getBase();
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000518 BaseName = getIslCompatibleName("MemRef_", getBaseAddr(), "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000519
520 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000521
Tobias Grosserac3a95f2015-08-03 17:53:21 +0000522 auto IdName = "__polly_array_ref_" + std::to_string(Identifier);
Tobias Grossere29d31c2015-05-15 12:24:09 +0000523 Id = isl_id_alloc(Ctx, IdName.c_str(), nullptr);
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000524
Tobias Grossera1879642011-12-20 10:43:14 +0000525 if (!Access.isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000526 // We overapproximate non-affine accesses with a possible access to the
527 // whole array. For read accesses it does not make a difference, if an
528 // access must or may happen. However, for write accesses it is important to
529 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000530 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000531 AccessRelation =
532 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000533
534 computeBoundsOnAccessRelation(Access.getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000535 return;
536 }
537
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000538 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000539 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000540
Tobias Grosser79baa212014-04-10 08:38:02 +0000541 for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000542 isl_pw_aff *Affine = Statement->getPwAff(Access.Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000543
Sebastian Pop422e33f2014-06-03 18:16:31 +0000544 if (Size == 1) {
545 // For the non delinearized arrays, divide the access function of the last
546 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000547 //
548 // A stride one array access in C expressed as A[i] is expressed in
549 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
550 // two subsequent values of 'i' index two values that are stored next to
551 // each other in memory. By this division we make this characteristic
552 // obvious again.
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000553 isl_val *v = isl_val_int_from_si(Ctx, Access.getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000554 Affine = isl_pw_aff_scale_down_val(Affine, v);
555 }
556
557 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
558
Tobias Grosser79baa212014-04-10 08:38:02 +0000559 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000560 }
561
Tobias Grosser619190d2015-03-30 17:22:28 +0000562 AccessRelation = foldAccess(Access, AccessRelation, Statement);
563
Tobias Grosser79baa212014-04-10 08:38:02 +0000564 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000565 AccessRelation = isl_map_set_tuple_id(
566 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000567 AccessRelation =
568 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
569
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000570 assumeNoOutOfBound(Access);
Tobias Grosseraa660a92015-03-30 00:07:50 +0000571 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000572 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000573}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000574
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000575void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000576 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000577 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000578}
579
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000580const std::string MemoryAccess::getReductionOperatorStr() const {
581 return MemoryAccess::getReductionOperatorStr(getReductionType());
582}
583
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000584__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
585
Johannes Doerfertf6183392014-07-01 20:52:51 +0000586raw_ostream &polly::operator<<(raw_ostream &OS,
587 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000588 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000589 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000590 else
591 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000592 return OS;
593}
594
Tobias Grosser75805372011-04-29 06:27:02 +0000595void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000596 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000597 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000598 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000599 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000600 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000601 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000602 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000603 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000604 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000605 break;
606 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000607 OS << "[Reduction Type: " << getReductionType() << "] ";
608 OS << "[Scalar: " << isScalar() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000609 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000610 if (hasNewAccessRelation())
611 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000612}
613
Tobias Grosser74394f02013-01-14 22:40:23 +0000614void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000615
616// Create a map in the size of the provided set domain, that maps from the
617// one element of the provided set domain to another element of the provided
618// set domain.
619// The mapping is limited to all points that are equal in all but the last
620// dimension and for which the last dimension of the input is strict smaller
621// than the last dimension of the output.
622//
623// getEqualAndLarger(set[i0, i1, ..., iX]):
624//
625// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
626// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
627//
Tobias Grosserf5338802011-10-06 00:03:35 +0000628static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000629 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000630 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000631 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000632
633 // Set all but the last dimension to be equal for the input and output
634 //
635 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
636 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000637 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000638 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000639
640 // Set the last dimension of the input to be strict smaller than the
641 // last dimension of the output.
642 //
643 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000644 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
645 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000646 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000647}
648
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000649__isl_give isl_set *
650MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000651 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000652 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000653 isl_space *Space = isl_space_range(isl_map_get_space(S));
654 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000655
Sebastian Popa00a0292012-12-18 07:46:06 +0000656 S = isl_map_reverse(S);
657 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000658
Sebastian Popa00a0292012-12-18 07:46:06 +0000659 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
660 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
661 NextScatt = isl_map_apply_domain(NextScatt, S);
662 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000663
Sebastian Popa00a0292012-12-18 07:46:06 +0000664 isl_set *Deltas = isl_map_deltas(NextScatt);
665 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000666}
667
Sebastian Popa00a0292012-12-18 07:46:06 +0000668bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000669 int StrideWidth) const {
670 isl_set *Stride, *StrideX;
671 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000672
Sebastian Popa00a0292012-12-18 07:46:06 +0000673 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000674 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000675 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
676 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
677 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
678 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000679 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000680
Tobias Grosser28dd4862012-01-24 16:42:16 +0000681 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000682 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000683
Tobias Grosser28dd4862012-01-24 16:42:16 +0000684 return IsStrideX;
685}
686
Sebastian Popa00a0292012-12-18 07:46:06 +0000687bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
688 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000689}
690
Tobias Grosser79baa212014-04-10 08:38:02 +0000691bool MemoryAccess::isScalar() const {
692 return isl_map_n_out(AccessRelation) == 0;
693}
694
Sebastian Popa00a0292012-12-18 07:46:06 +0000695bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
696 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000697}
698
Tobias Grosser166c4222015-09-05 07:46:40 +0000699void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
700 isl_map_free(NewAccessRelation);
701 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000702}
Tobias Grosser75805372011-04-29 06:27:02 +0000703
704//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000705
Tobias Grosser808cd692015-07-14 09:33:13 +0000706isl_map *ScopStmt::getSchedule() const {
707 isl_set *Domain = getDomain();
708 if (isl_set_is_empty(Domain)) {
709 isl_set_free(Domain);
710 return isl_map_from_aff(
711 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
712 }
713 auto *Schedule = getParent()->getSchedule();
714 Schedule = isl_union_map_intersect_domain(
715 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
716 if (isl_union_map_is_empty(Schedule)) {
717 isl_set_free(Domain);
718 isl_union_map_free(Schedule);
719 return isl_map_from_aff(
720 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
721 }
722 auto *M = isl_map_from_union_map(Schedule);
723 M = isl_map_coalesce(M);
724 M = isl_map_gist_domain(M, Domain);
725 M = isl_map_coalesce(M);
726 return M;
727}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000728
Johannes Doerfert574182d2015-08-12 10:19:50 +0000729__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertb409fdc2015-08-28 09:24:35 +0000730 return getParent()->getPwAff(E, Domain);
Johannes Doerfert574182d2015-08-12 10:19:50 +0000731}
732
Tobias Grosser37eb4222014-02-20 21:43:54 +0000733void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
734 assert(isl_set_is_subset(NewDomain, Domain) &&
735 "New domain is not a subset of old domain!");
736 isl_set_free(Domain);
737 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000738}
739
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000740void ScopStmt::buildAccesses(TempScop &tempScop, BasicBlock *Block,
741 bool isApproximated) {
742 AccFuncSetType *AFS = tempScop.getAccessFunctions(Block);
743 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++)
799 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
800
801 unsigned NumDimsS = isl_set_n_dim(S);
802 isl_set *OnlyDimS = isl_set_copy(S);
803
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
830 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
831 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);
894 }
895
896 assert(ConsequenceCondSet);
897 isl_set *AlternativeCondSet =
898 isl_set_complement(isl_set_copy(ConsequenceCondSet));
899
900 ConditionSets.push_back(isl_set_coalesce(
901 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
902 ConditionSets.push_back(isl_set_coalesce(
903 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
904}
905
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000906void ScopStmt::buildDomain(TempScop &tempScop, const Region &CurRegion) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000907 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000908
Tobias Grosser084d8f72012-05-29 09:29:44 +0000909 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
910
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000911 Domain = getParent()->getDomainConditions(this);
Johannes Doerfert96425c22015-08-30 21:13:53 +0000912 Domain = isl_set_coalesce(Domain);
Tobias Grosser084d8f72012-05-29 09:29:44 +0000913 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +0000914}
915
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000916void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
917 int Dimension = 0;
918 isl_ctx *Ctx = Parent.getIslCtx();
919 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
920 Type *Ty = GEP->getPointerOperandType();
921 ScalarEvolution &SE = *Parent.getSE();
922
923 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
924 Dimension = 1;
925 Ty = PtrTy->getElementType();
926 }
927
928 while (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
929 unsigned int Operand = 1 + Dimension;
930
931 if (GEP->getNumOperands() <= Operand)
932 break;
933
934 const SCEV *Expr = SE.getSCEV(GEP->getOperand(Operand));
935
936 if (isAffineExpr(&Parent.getRegion(), Expr, SE)) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000937 isl_pw_aff *AccessOffset = getPwAff(Expr);
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000938 AccessOffset =
939 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
940
941 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
942 isl_local_space_copy(LSpace),
943 isl_val_int_from_si(Ctx, ArrayTy->getNumElements())));
944
945 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
946 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
947 OutOfBound = isl_set_params(OutOfBound);
948 isl_set *InBound = isl_set_complement(OutOfBound);
949 isl_set *Executed = isl_set_params(getDomain());
950
951 // A => B == !A or B
952 isl_set *InBoundIfExecuted =
953 isl_set_union(isl_set_complement(Executed), InBound);
954
955 Parent.addAssumption(InBoundIfExecuted);
956 }
957
958 Dimension += 1;
959 Ty = ArrayTy->getElementType();
960 }
961
962 isl_local_space_free(LSpace);
963}
964
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000965void ScopStmt::deriveAssumptions(BasicBlock *Block) {
966 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000967 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
968 deriveAssumptionsFromGEP(GEP);
969}
970
Tobias Grosser74394f02013-01-14 22:40:23 +0000971ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Tobias Grosser808cd692015-07-14 09:33:13 +0000972 Region &R, SmallVectorImpl<Loop *> &Nest)
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000973 : Parent(parent), BB(nullptr), R(&R), Build(nullptr),
974 NestLoops(Nest.size()) {
975 // Setup the induction variables.
976 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
977 NestLoops[i] = Nest[i];
978
Tobias Grosser16c44032015-07-09 07:31:45 +0000979 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000980
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000981 buildDomain(tempScop, CurRegion);
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000982
983 BasicBlock *EntryBB = R.getEntry();
984 for (BasicBlock *Block : R.blocks()) {
985 buildAccesses(tempScop, Block, Block != EntryBB);
986 deriveAssumptions(Block);
987 }
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000988 if (DetectReductions)
989 checkForReductions();
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000990}
991
992ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Tobias Grosser808cd692015-07-14 09:33:13 +0000993 BasicBlock &bb, SmallVectorImpl<Loop *> &Nest)
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000994 : Parent(parent), BB(&bb), R(nullptr), Build(nullptr),
995 NestLoops(Nest.size()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000996 // Setup the induction variables.
Tobias Grosser683b8e42014-11-30 14:33:31 +0000997 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
Sebastian Pop860e0212013-02-15 21:26:44 +0000998 NestLoops[i] = Nest[i];
Tobias Grosser75805372011-04-29 06:27:02 +0000999
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001000 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +00001001
Johannes Doerfert45545ff2015-08-16 14:36:01 +00001002 buildDomain(tempScop, CurRegion);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001003 buildAccesses(tempScop, BB);
1004 deriveAssumptions(BB);
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001005 if (DetectReductions)
1006 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001007}
1008
Johannes Doerferte58a0122014-06-27 20:31:28 +00001009/// @brief Collect loads which might form a reduction chain with @p StoreMA
1010///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001011/// Check if the stored value for @p StoreMA is a binary operator with one or
1012/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001013/// used only once (by @p StoreMA) and its load operands are also used only
1014/// once, we have found a possible reduction chain. It starts at an operand
1015/// load and includes the binary operator and @p StoreMA.
1016///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001017/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001018/// escape this block or into any other store except @p StoreMA.
1019void ScopStmt::collectCandiateReductionLoads(
1020 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1021 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1022 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001023 return;
1024
1025 // Skip if there is not one binary operator between the load and the store
1026 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001027 if (!BinOp)
1028 return;
1029
1030 // Skip if the binary operators has multiple uses
1031 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001032 return;
1033
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001034 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001035 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1036 return;
1037
Johannes Doerfert9890a052014-07-01 00:32:29 +00001038 // Skip if the binary operator is outside the current SCoP
1039 if (BinOp->getParent() != Store->getParent())
1040 return;
1041
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001042 // Skip if it is a multiplicative reduction and we disabled them
1043 if (DisableMultiplicativeReductions &&
1044 (BinOp->getOpcode() == Instruction::Mul ||
1045 BinOp->getOpcode() == Instruction::FMul))
1046 return;
1047
Johannes Doerferte58a0122014-06-27 20:31:28 +00001048 // Check the binary operator operands for a candidate load
1049 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1050 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1051 if (!PossibleLoad0 && !PossibleLoad1)
1052 return;
1053
1054 // A load is only a candidate if it cannot escape (thus has only this use)
1055 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001056 if (PossibleLoad0->getParent() == Store->getParent())
1057 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001058 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001059 if (PossibleLoad1->getParent() == Store->getParent())
1060 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001061}
1062
1063/// @brief Check for reductions in this ScopStmt
1064///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001065/// Iterate over all store memory accesses and check for valid binary reduction
1066/// like chains. For all candidates we check if they have the same base address
1067/// and there are no other accesses which overlap with them. The base address
1068/// check rules out impossible reductions candidates early. The overlap check,
1069/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001070/// guarantees that none of the intermediate results will escape during
1071/// execution of the loop nest. We basically check here that no other memory
1072/// access can access the same memory as the potential reduction.
1073void ScopStmt::checkForReductions() {
1074 SmallVector<MemoryAccess *, 2> Loads;
1075 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1076
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001077 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001078 // stores and collecting possible reduction loads.
1079 for (MemoryAccess *StoreMA : MemAccs) {
1080 if (StoreMA->isRead())
1081 continue;
1082
1083 Loads.clear();
1084 collectCandiateReductionLoads(StoreMA, Loads);
1085 for (MemoryAccess *LoadMA : Loads)
1086 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1087 }
1088
1089 // Then check each possible candidate pair.
1090 for (const auto &CandidatePair : Candidates) {
1091 bool Valid = true;
1092 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1093 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1094
1095 // Skip those with obviously unequal base addresses.
1096 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1097 isl_map_free(LoadAccs);
1098 isl_map_free(StoreAccs);
1099 continue;
1100 }
1101
1102 // And check if the remaining for overlap with other memory accesses.
1103 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1104 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1105 isl_set *AllAccs = isl_map_range(AllAccsRel);
1106
1107 for (MemoryAccess *MA : MemAccs) {
1108 if (MA == CandidatePair.first || MA == CandidatePair.second)
1109 continue;
1110
1111 isl_map *AccRel =
1112 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1113 isl_set *Accs = isl_map_range(AccRel);
1114
1115 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1116 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1117 Valid = Valid && isl_set_is_empty(OverlapAccs);
1118 isl_set_free(OverlapAccs);
1119 }
1120 }
1121
1122 isl_set_free(AllAccs);
1123 if (!Valid)
1124 continue;
1125
Johannes Doerfertf6183392014-07-01 20:52:51 +00001126 const LoadInst *Load =
1127 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1128 MemoryAccess::ReductionType RT =
1129 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1130
Johannes Doerferte58a0122014-06-27 20:31:28 +00001131 // If no overlapping access was found we mark the load and store as
1132 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001133 CandidatePair.first->markAsReductionLike(RT);
1134 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001135 }
Tobias Grosser75805372011-04-29 06:27:02 +00001136}
1137
Tobias Grosser74394f02013-01-14 22:40:23 +00001138std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001139
Tobias Grosser54839312015-04-21 11:37:25 +00001140std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001141 auto *S = getSchedule();
1142 auto Str = stringFromIslObj(S);
1143 isl_map_free(S);
1144 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001145}
1146
Tobias Grosser74394f02013-01-14 22:40:23 +00001147unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001148
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001149unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001150
Tobias Grosser75805372011-04-29 06:27:02 +00001151const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1152
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001153const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001154 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001155}
1156
Tobias Grosser74394f02013-01-14 22:40:23 +00001157isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001158
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001159__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001160
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001161__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001162 return isl_set_get_space(Domain);
1163}
1164
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001165__isl_give isl_id *ScopStmt::getDomainId() const {
1166 return isl_set_get_tuple_id(Domain);
1167}
Tobias Grossercd95b772012-08-30 11:49:38 +00001168
Tobias Grosser75805372011-04-29 06:27:02 +00001169ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001170 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001171 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001172}
1173
1174void ScopStmt::print(raw_ostream &OS) const {
1175 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001176 OS.indent(12) << "Domain :=\n";
1177
1178 if (Domain) {
1179 OS.indent(16) << getDomainStr() << ";\n";
1180 } else
1181 OS.indent(16) << "n/a\n";
1182
Tobias Grosser54839312015-04-21 11:37:25 +00001183 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001184
1185 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001186 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001187 } else
1188 OS.indent(16) << "n/a\n";
1189
Tobias Grosser083d3d32014-06-28 08:59:45 +00001190 for (MemoryAccess *Access : MemAccs)
1191 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001192}
1193
1194void ScopStmt::dump() const { print(dbgs()); }
1195
1196//===----------------------------------------------------------------------===//
1197/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001198
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001199void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001200 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1201 isl_set_free(Context);
1202 Context = NewContext;
1203}
1204
Tobias Grosserabfbe632013-02-05 12:09:06 +00001205void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001206 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001207 Parameter = extractConstantFactor(Parameter, *SE).second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001208 if (ParameterIds.find(Parameter) != ParameterIds.end())
1209 continue;
1210
1211 int dimension = Parameters.size();
1212
1213 Parameters.push_back(Parameter);
1214 ParameterIds[Parameter] = dimension;
1215 }
1216}
1217
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001218__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1219 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001220
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001221 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001222 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001223
Tobias Grosser8f99c162011-11-15 11:38:55 +00001224 std::string ParameterName;
1225
1226 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1227 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001228 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001229 }
1230
1231 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001232 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001233
Tobias Grosser20532b82014-04-11 17:56:49 +00001234 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1235 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001236}
Tobias Grosser75805372011-04-29 06:27:02 +00001237
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001238isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1239 isl_set *DomainContext = isl_union_set_params(getDomains());
1240 return isl_set_intersect_params(C, DomainContext);
1241}
1242
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001243void Scop::addUserContext() {
1244 if (UserContextStr.empty())
1245 return;
1246
1247 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1248 isl_space *Space = getParamSpace();
1249 if (isl_space_dim(Space, isl_dim_param) !=
1250 isl_set_dim(UserContext, isl_dim_param)) {
1251 auto SpaceStr = isl_space_to_str(Space);
1252 errs() << "Error: the context provided in -polly-context has not the same "
1253 << "number of dimensions than the computed context. Due to this "
1254 << "mismatch, the -polly-context option is ignored. Please provide "
1255 << "the context in the parameter space: " << SpaceStr << ".\n";
1256 free(SpaceStr);
1257 isl_set_free(UserContext);
1258 isl_space_free(Space);
1259 return;
1260 }
1261
1262 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1263 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1264 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1265
1266 if (strcmp(NameContext, NameUserContext) != 0) {
1267 auto SpaceStr = isl_space_to_str(Space);
1268 errs() << "Error: the name of dimension " << i
1269 << " provided in -polly-context "
1270 << "is '" << NameUserContext << "', but the name in the computed "
1271 << "context is '" << NameContext
1272 << "'. Due to this name mismatch, "
1273 << "the -polly-context option is ignored. Please provide "
1274 << "the context in the parameter space: " << SpaceStr << ".\n";
1275 free(SpaceStr);
1276 isl_set_free(UserContext);
1277 isl_space_free(Space);
1278 return;
1279 }
1280
1281 UserContext =
1282 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1283 isl_space_get_dim_id(Space, isl_dim_param, i));
1284 }
1285
1286 Context = isl_set_intersect(Context, UserContext);
1287 isl_space_free(Space);
1288}
1289
Tobias Grosser6be480c2011-11-08 15:41:13 +00001290void Scop::buildContext() {
1291 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001292 Context = isl_set_universe(isl_space_copy(Space));
1293 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001294}
1295
Tobias Grosser18daaca2012-05-22 10:47:27 +00001296void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001297 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001298 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001299
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001300 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001301
Johannes Doerferte7044942015-02-24 11:58:30 +00001302 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001303 }
1304}
1305
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001306void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001307 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001308 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001309
Tobias Grosser083d3d32014-06-28 08:59:45 +00001310 for (const auto &ParamID : ParameterIds) {
1311 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001312 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001313 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001314 }
1315
1316 // Align the parameters of all data structures to the model.
1317 Context = isl_set_align_params(Context, Space);
1318
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001319 for (ScopStmt &Stmt : *this)
1320 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001321}
1322
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001323void Scop::simplifyAssumedContext() {
1324 // The parameter constraints of the iteration domains give us a set of
1325 // constraints that need to hold for all cases where at least a single
1326 // statement iteration is executed in the whole scop. We now simplify the
1327 // assumed context under the assumption that such constraints hold and at
1328 // least a single statement iteration is executed. For cases where no
1329 // statement instances are executed, the assumptions we have taken about
1330 // the executed code do not matter and can be changed.
1331 //
1332 // WARNING: This only holds if the assumptions we have taken do not reduce
1333 // the set of statement instances that are executed. Otherwise we
1334 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001335 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001336 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001337 // performed. In such a case, modifying the run-time conditions and
1338 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001339 // to not be executed.
1340 //
1341 // Example:
1342 //
1343 // When delinearizing the following code:
1344 //
1345 // for (long i = 0; i < 100; i++)
1346 // for (long j = 0; j < m; j++)
1347 // A[i+p][j] = 1.0;
1348 //
1349 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001350 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001351 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
1352 AssumedContext =
1353 isl_set_gist_params(AssumedContext, isl_union_set_params(getDomains()));
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001354 AssumedContext = isl_set_gist_params(AssumedContext, getContext());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001355}
1356
Johannes Doerfertb164c792014-09-18 11:17:17 +00001357/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001358static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001359 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1360 isl_pw_multi_aff *MinPMA, *MaxPMA;
1361 isl_pw_aff *LastDimAff;
1362 isl_aff *OneAff;
1363 unsigned Pos;
1364
Johannes Doerfert9143d672014-09-27 11:02:39 +00001365 // Restrict the number of parameters involved in the access as the lexmin/
1366 // lexmax computation will take too long if this number is high.
1367 //
1368 // Experiments with a simple test case using an i7 4800MQ:
1369 //
1370 // #Parameters involved | Time (in sec)
1371 // 6 | 0.01
1372 // 7 | 0.04
1373 // 8 | 0.12
1374 // 9 | 0.40
1375 // 10 | 1.54
1376 // 11 | 6.78
1377 // 12 | 30.38
1378 //
1379 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1380 unsigned InvolvedParams = 0;
1381 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1382 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1383 InvolvedParams++;
1384
1385 if (InvolvedParams > RunTimeChecksMaxParameters) {
1386 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001387 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001388 }
1389 }
1390
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001391 Set = isl_set_remove_divs(Set);
1392
Johannes Doerfertb164c792014-09-18 11:17:17 +00001393 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1394 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1395
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001396 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1397 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1398
Johannes Doerfertb164c792014-09-18 11:17:17 +00001399 // Adjust the last dimension of the maximal access by one as we want to
1400 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1401 // we test during code generation might now point after the end of the
1402 // allocated array but we will never dereference it anyway.
1403 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1404 "Assumed at least one output dimension");
1405 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1406 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1407 OneAff = isl_aff_zero_on_domain(
1408 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1409 OneAff = isl_aff_add_constant_si(OneAff, 1);
1410 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1411 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1412
1413 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1414
1415 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001416 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001417}
1418
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001419static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1420 isl_set *Domain = MA->getStatement()->getDomain();
1421 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1422 return isl_set_reset_tuple_id(Domain);
1423}
1424
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001425/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1426static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001427 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001428 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001429
1430 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1431 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001432 Locations = isl_union_set_coalesce(Locations);
1433 Locations = isl_union_set_detect_equalities(Locations);
1434 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001435 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001436 isl_union_set_free(Locations);
1437 return Valid;
1438}
1439
Johannes Doerfert96425c22015-08-30 21:13:53 +00001440/// @brief Helper to treat non-affine regions and basic blocks the same.
1441///
1442///{
1443
1444/// @brief Return the block that is the representing block for @p RN.
1445static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1446 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1447 : RN->getNodeAs<BasicBlock>();
1448}
1449
1450/// @brief Return the @p idx'th block that is executed after @p RN.
1451static inline BasicBlock *getRegionNodeSuccessor(RegionNode *RN, BranchInst *BI,
1452 unsigned idx) {
1453 if (RN->isSubRegion()) {
1454 assert(idx == 0);
1455 return RN->getNodeAs<Region>()->getExit();
1456 }
1457 return BI->getSuccessor(idx);
1458}
1459
1460/// @brief Return the smallest loop surrounding @p RN.
1461static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1462 if (!RN->isSubRegion())
1463 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1464
1465 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1466 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1467 while (L && NonAffineSubRegion->contains(L))
1468 L = L->getParentLoop();
1469 return L;
1470}
1471
1472///}
1473
1474isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1475 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1476 : Stmt->getRegion()->getEntry();
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001477 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001478}
1479
1480void Scop::buildDomains(Region *R, LoopInfo &LI, ScopDetection &SD,
1481 DominatorTree &DT) {
1482
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001483 auto *EntryBB = R->getEntry();
1484 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
1485 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
1486 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001487
1488 buildDomainsWithBranchConstraints(R, LI, SD, DT);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001489 addLoopBoundsToHeaderDomains(LI, SD, DT);
1490 propagateDomainConstraints(R, LI, SD, DT);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001491}
1492
1493void Scop::buildDomainsWithBranchConstraints(Region *R, LoopInfo &LI,
1494 ScopDetection &SD,
1495 DominatorTree &DT) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001496 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00001497
1498 // To create the domain for each block in R we iterate over all blocks and
1499 // subregions in R and propagate the conditions under which the current region
1500 // element is executed. To this end we iterate in reverse post order over R as
1501 // it ensures that we first visit all predecessors of a region node (either a
1502 // basic block or a subregion) before we visit the region node itself.
1503 // Initially, only the domain for the SCoP region entry block is set and from
1504 // there we propagate the current domain to all successors, however we add the
1505 // condition that the successor is actually executed next.
1506 // As we are only interested in non-loop carried constraints here we can
1507 // simply skip loop back edges.
1508
1509 ReversePostOrderTraversal<Region *> RTraversal(R);
1510 for (auto *RN : RTraversal) {
1511
1512 // Recurse for affine subregions but go on for basic blocks and non-affine
1513 // subregions.
1514 if (RN->isSubRegion()) {
1515 Region *SubRegion = RN->getNodeAs<Region>();
1516 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
1517 buildDomainsWithBranchConstraints(SubRegion, LI, SD, DT);
1518 continue;
1519 }
1520 }
1521
1522 BasicBlock *BB = getRegionNodeBasicBlock(RN);
1523 isl_set *Domain = DomainMap[BB];
1524 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
1525 assert(Domain && "Due to reverse post order traversal of the region all "
1526 "predecessor of the current region node should have been "
1527 "visited and a domain for this region node should have "
1528 "been set.");
1529
1530 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1531 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1532
1533 // Build the condition sets for the successor nodes of the current region
1534 // node. If it is a non-affine subregion we will always execute the single
1535 // exit node, hence the single entry node domain is the condition set. For
1536 // basic blocks we use the helper function buildConditionSets.
1537 SmallVector<isl_set *, 2> ConditionSets;
1538 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1539 if (RN->isSubRegion())
1540 ConditionSets.push_back(isl_set_copy(Domain));
1541 else
1542 buildConditionSets(*this, BI, BBLoop, Domain, ConditionSets);
1543
1544 // Now iterate over the successors and set their initial domain based on
1545 // their condition set. We skip back edges here and have to be careful when
1546 // we leave a loop not to keep constraints over a dimension that doesn't
1547 // exist anymore.
1548 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
1549 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, BI, u);
1550 isl_set *CondSet = ConditionSets[u];
1551
1552 // Skip back edges.
1553 if (DT.dominates(SuccBB, BB)) {
1554 isl_set_free(CondSet);
1555 continue;
1556 }
1557
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001558 // Do not adjust the number of dimensions if we enter a boxed loop or are
1559 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001560 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001561 Region *SuccRegion = RI.getRegionFor(SuccBB);
1562 if (BBLoop != SuccBBLoop && !RN->isSubRegion() &&
1563 !(SD.isNonAffineSubRegion(SuccRegion, &getRegion()) &&
1564 SuccRegion->contains(SuccBBLoop))) {
1565
1566 // Check if the edge to SuccBB is a loop entry or exit edge. If so
1567 // adjust the dimensionality accordingly. Lastly, if we leave a loop
1568 // and enter a new one we need to drop the old constraints.
1569 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
1570 assert(std::abs(BBLoopDepth - SuccBBLoopDepth) <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001571 if (BBLoopDepth > SuccBBLoopDepth) {
1572 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
1573 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001574 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001575 } else if (BBLoopDepth >= 0) {
1576 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
1577 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
1578 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00001579 }
1580
1581 // Set the domain for the successor or merge it with an existing domain in
1582 // case there are multiple paths (without loop back edges) to the
1583 // successor block.
1584 isl_set *&SuccDomain = DomainMap[SuccBB];
1585 if (!SuccDomain)
1586 SuccDomain = CondSet;
1587 else
1588 SuccDomain = isl_set_union(SuccDomain, CondSet);
1589
1590 SuccDomain = isl_set_coalesce(SuccDomain);
1591 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : " << Domain
1592 << "\n");
1593 }
1594 }
1595}
1596
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001597/// @brief Return the domain for @p BB wrt @p DomainMap.
1598///
1599/// This helper function will lookup @p BB in @p DomainMap but also handle the
1600/// case where @p BB is contained in a non-affine subregion using the region
1601/// tree obtained by @p RI.
1602static __isl_give isl_set *
1603getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
1604 RegionInfo &RI) {
1605 auto DIt = DomainMap.find(BB);
1606 if (DIt != DomainMap.end())
1607 return isl_set_copy(DIt->getSecond());
1608
1609 Region *R = RI.getRegionFor(BB);
1610 while (R->getEntry() == BB)
1611 R = R->getParent();
1612 return getDomainForBlock(R->getEntry(), DomainMap, RI);
1613}
1614
1615void Scop::propagateDomainConstraints(Region *R, LoopInfo &LI,
1616 ScopDetection &SD, DominatorTree &DT) {
1617 // Iterate over the region R and propagate the domain constrains from the
1618 // predecessors to the current node. In contrast to the
1619 // buildDomainsWithBranchConstraints function, this one will pull the domain
1620 // information from the predecessors instead of pushing it to the successors.
1621 // Additionally, we assume the domains to be already present in the domain
1622 // map here. However, we iterate again in reverse post order so we know all
1623 // predecessors have been visited before a block or non-affine subregion is
1624 // visited.
1625
1626 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
1627 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
1628
1629 ReversePostOrderTraversal<Region *> RTraversal(R);
1630 for (auto *RN : RTraversal) {
1631
1632 // Recurse for affine subregions but go on for basic blocks and non-affine
1633 // subregions.
1634 if (RN->isSubRegion()) {
1635 Region *SubRegion = RN->getNodeAs<Region>();
1636 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
1637 propagateDomainConstraints(SubRegion, LI, SD, DT);
1638 continue;
1639 }
1640 }
1641
1642 BasicBlock *BB = getRegionNodeBasicBlock(RN);
1643 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1644 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1645
1646 isl_set *&Domain = DomainMap[BB];
1647 assert(Domain && "Due to reverse post order traversal of the region all "
1648 "predecessor of the current region node should have been "
1649 "visited and a domain for this region node should have "
1650 "been set.");
1651
1652 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
1653 for (auto *PredBB : predecessors(BB)) {
1654
1655 // Skip backedges
1656 if (DT.dominates(BB, PredBB))
1657 continue;
1658
1659 isl_set *PredBBDom = nullptr;
1660
1661 // Handle the SCoP entry block with its outside predecessors.
1662 if (!getRegion().contains(PredBB))
1663 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
1664
1665 if (!PredBBDom) {
1666 // Determine the loop depth of the predecessor and adjust its domain to
1667 // the domain of the current block. This can mean we have to:
1668 // o) Drop a dimension if this block is the exit of a loop, not the
1669 // header of a new loop and the predecessor was part of the loop.
1670 // o) Add an unconstrainted new dimension if this block is the header
1671 // of a loop and the predecessor is not part of it.
1672 // o) Drop the information about the innermost loop dimension when the
1673 // predecessor and the current block are surrounded by different
1674 // loops in the same depth.
1675 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
1676 Loop *PredBBLoop = LI.getLoopFor(PredBB);
1677 while (BoxedLoops.count(PredBBLoop))
1678 PredBBLoop = PredBBLoop->getParentLoop();
1679
1680 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
1681 assert(std::abs(BBLoopDepth - PredBBLoopDepth) <= 1);
1682 if (BBLoopDepth < PredBBLoopDepth)
1683 PredBBDom =
1684 isl_set_project_out(PredBBDom, isl_dim_set, PredBBLoopDepth, 1);
1685 else if (PredBBLoopDepth < BBLoopDepth)
1686 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
1687 else if (BBLoop != PredBBLoop && BBLoopDepth >= 0)
1688 PredBBDom = isl_set_drop_constraints_involving_dims(
1689 PredBBDom, isl_dim_set, BBLoopDepth, 1);
1690 }
1691
1692 PredDom = isl_set_union(PredDom, PredBBDom);
1693 }
1694
1695 // Under the union of all predecessor conditions we can reach this block.
1696 Domain = isl_set_intersect(Domain, PredDom);
1697 }
1698}
1699
1700/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
1701/// is incremented by one and all other dimensions are equal, e.g.,
1702/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
1703/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
1704static __isl_give isl_map *
1705createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
1706 auto *MapSpace = isl_space_map_from_set(SetSpace);
1707 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
1708 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
1709 if (u != Dim)
1710 NextIterationMap =
1711 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
1712 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
1713 C = isl_constraint_set_constant_si(C, 1);
1714 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
1715 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
1716 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
1717 return NextIterationMap;
1718}
1719
1720/// @brief Add @p L & all children to @p Loops if they are not in @p BoxedLoops.
1721static inline void
1722addLoopAndSubloops(Loop *L, SmallVectorImpl<Loop *> &Loops,
1723 const ScopDetection::BoxedLoopsSetTy &BoxedLoops) {
1724 if (BoxedLoops.count(L))
1725 return;
1726
1727 Loops.push_back(L);
1728 for (Loop *Subloop : *L)
1729 addLoopAndSubloops(Subloop, Loops, BoxedLoops);
1730}
1731
1732/// @brief Add loops in @p R to @p RegionLoops if they are not in @p BoxedLoops.
1733static inline void
1734collectLoopsInRegion(Region &R, LoopInfo &LI,
1735 SmallVector<Loop *, 8> &RegionLoops,
1736 const ScopDetection::BoxedLoopsSetTy &BoxedLoops) {
1737
1738 SmallVector<Loop *, 8> Loops(LI.begin(), LI.end());
1739 while (!Loops.empty()) {
1740 Loop *L = Loops.pop_back_val();
1741
1742 if (R.contains(L))
1743 addLoopAndSubloops(L, RegionLoops, BoxedLoops);
1744 else if (L->contains(R.getEntry()))
1745 Loops.append(L->begin(), L->end());
1746 }
1747}
1748
1749/// @brief Create a set from @p Space with @p Dim fixed to 0.
1750static __isl_give isl_set *
1751createFirstIterationDomain(__isl_take isl_space *Space, unsigned Dim) {
1752 auto *Domain = isl_set_universe(Space);
1753 Domain = isl_set_fix_si(Domain, isl_dim_set, Dim, 0);
1754 return Domain;
1755}
1756
1757void Scop::addLoopBoundsToHeaderDomains(LoopInfo &LI, ScopDetection &SD,
1758 DominatorTree &DT) {
1759 // We iterate over all loops in the SCoP, create the condition set under which
1760 // we will take the back edge, and then apply these restrictions to the
1761 // header.
1762
1763 Region &R = getRegion();
1764 SmallVector<Loop *, 8> RegionLoops;
1765 collectLoopsInRegion(R, LI, RegionLoops, *SD.getBoxedLoops(&R));
1766
1767 while (!RegionLoops.empty()) {
1768 Loop *L = RegionLoops.pop_back_val();
1769 int LoopDepth = getRelativeLoopDepth(L);
1770 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
1771
1772 BasicBlock *LatchBB = L->getLoopLatch();
1773 assert(LatchBB && "TODO implement multiple exit loop handling");
1774
1775 isl_set *LatchBBDom = DomainMap[LatchBB];
1776 isl_set *BackedgeCondition = nullptr;
1777
1778 BasicBlock *HeaderBB = L->getHeader();
1779
1780 BranchInst *BI = cast<BranchInst>(LatchBB->getTerminator());
1781 if (BI->isUnconditional())
1782 BackedgeCondition = isl_set_copy(LatchBBDom);
1783 else {
1784 SmallVector<isl_set *, 2> ConditionSets;
1785 int idx = BI->getSuccessor(0) != HeaderBB;
1786 buildConditionSets(*this, BI, L, LatchBBDom, ConditionSets);
1787
1788 // Free the non back edge condition set as we do not need it.
1789 isl_set_free(ConditionSets[1 - idx]);
1790
1791 BackedgeCondition = ConditionSets[idx];
1792 }
1793
1794 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
1795 isl_set *FirstIteration =
1796 createFirstIterationDomain(isl_set_get_space(HeaderBBDom), LoopDepth);
1797
1798 isl_map *NextIterationMap =
1799 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
1800
1801 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
1802 assert(LatchLoopDepth >= LoopDepth);
1803 BackedgeCondition =
1804 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
1805 LatchLoopDepth - LoopDepth);
1806
1807 auto Parts = partitionSetParts(BackedgeCondition, LoopDepth);
1808
1809 // If a loop has an unbounded back edge condition part (here Parts.first)
1810 // we do not want to assume the header will even be executed for the first
1811 // iteration of an execution that will lead to an infinite loop. While it
1812 // would not be wrong to do so, it does not seem helpful.
1813 FirstIteration = isl_set_subtract(FirstIteration, Parts.first);
1814
1815 BackedgeCondition = isl_set_apply(Parts.second, NextIterationMap);
1816 BackedgeCondition = isl_set_union(BackedgeCondition, FirstIteration);
1817 BackedgeCondition = isl_set_coalesce(BackedgeCondition);
1818
1819 HeaderBBDom = isl_set_intersect(HeaderBBDom, BackedgeCondition);
1820 }
1821}
1822
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001823void Scop::buildAliasChecks(AliasAnalysis &AA) {
1824 if (!PollyUseRuntimeAliasChecks)
1825 return;
1826
1827 if (buildAliasGroups(AA))
1828 return;
1829
1830 // If a problem occurs while building the alias groups we need to delete
1831 // this SCoP and pretend it wasn't valid in the first place. To this end
1832 // we make the assumed context infeasible.
1833 addAssumption(isl_set_empty(getParamSpace()));
1834
1835 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
1836 << " could not be created as the number of parameters involved "
1837 "is too high. The SCoP will be "
1838 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
1839 "the maximal number of parameters but be advised that the "
1840 "compile time might increase exponentially.\n\n");
1841}
1842
Johannes Doerfert9143d672014-09-27 11:02:39 +00001843bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001844 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001845 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00001846 // for all memory accesses inside the SCoP.
1847 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001848 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00001849 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001850 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001851 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001852 // if their access domains intersect, otherwise they are in different
1853 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001854 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001855 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001856 // and maximal accesses to each array of a group in read only and non
1857 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00001858 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
1859
1860 AliasSetTracker AST(AA);
1861
1862 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00001863 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001864 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001865
1866 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001867 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001868 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
1869 isl_set_free(StmtDomain);
1870 if (StmtDomainEmpty)
1871 continue;
1872
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001873 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001874 if (MA->isScalar())
1875 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00001876 if (!MA->isRead())
1877 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001878 Instruction *Acc = MA->getAccessInstruction();
1879 PtrToAcc[getPointerOperand(*Acc)] = MA;
1880 AST.add(Acc);
1881 }
1882 }
1883
1884 SmallVector<AliasGroupTy, 4> AliasGroups;
1885 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00001886 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00001887 continue;
1888 AliasGroupTy AG;
1889 for (auto PR : AS)
1890 AG.push_back(PtrToAcc[PR.getValue()]);
1891 assert(AG.size() > 1 &&
1892 "Alias groups should contain at least two accesses");
1893 AliasGroups.push_back(std::move(AG));
1894 }
1895
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001896 // Split the alias groups based on their domain.
1897 for (unsigned u = 0; u < AliasGroups.size(); u++) {
1898 AliasGroupTy NewAG;
1899 AliasGroupTy &AG = AliasGroups[u];
1900 AliasGroupTy::iterator AGI = AG.begin();
1901 isl_set *AGDomain = getAccessDomain(*AGI);
1902 while (AGI != AG.end()) {
1903 MemoryAccess *MA = *AGI;
1904 isl_set *MADomain = getAccessDomain(MA);
1905 if (isl_set_is_disjoint(AGDomain, MADomain)) {
1906 NewAG.push_back(MA);
1907 AGI = AG.erase(AGI);
1908 isl_set_free(MADomain);
1909 } else {
1910 AGDomain = isl_set_union(AGDomain, MADomain);
1911 AGI++;
1912 }
1913 }
1914 if (NewAG.size() > 1)
1915 AliasGroups.push_back(std::move(NewAG));
1916 isl_set_free(AGDomain);
1917 }
1918
Tobias Grosserf4c24b22015-04-05 13:11:54 +00001919 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00001920 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
1921 for (AliasGroupTy &AG : AliasGroups) {
1922 NonReadOnlyBaseValues.clear();
1923 ReadOnlyPairs.clear();
1924
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001925 if (AG.size() < 2) {
1926 AG.clear();
1927 continue;
1928 }
1929
Johannes Doerfert13771732014-10-01 12:40:46 +00001930 for (auto II = AG.begin(); II != AG.end();) {
1931 Value *BaseAddr = (*II)->getBaseAddr();
1932 if (HasWriteAccess.count(BaseAddr)) {
1933 NonReadOnlyBaseValues.insert(BaseAddr);
1934 II++;
1935 } else {
1936 ReadOnlyPairs[BaseAddr].insert(*II);
1937 II = AG.erase(II);
1938 }
1939 }
1940
1941 // If we don't have read only pointers check if there are at least two
1942 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00001943 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001944 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00001945 continue;
1946 }
1947
1948 // If we don't have non read only pointers clear the alias group.
1949 if (NonReadOnlyBaseValues.empty()) {
1950 AG.clear();
1951 continue;
1952 }
1953
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001954 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001955 MinMaxAliasGroups.emplace_back();
1956 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
1957 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
1958 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
1959 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001960
1961 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001962
1963 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00001964 for (MemoryAccess *MA : AG)
1965 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001966
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00001967 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
1968 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001969
1970 // Bail out if the number of values we need to compare is too large.
1971 // This is important as the number of comparisions grows quadratically with
1972 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001973 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
1974 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001975 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001976
1977 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001978 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001979 Accesses = isl_union_map_empty(getParamSpace());
1980
1981 for (const auto &ReadOnlyPair : ReadOnlyPairs)
1982 for (MemoryAccess *MA : ReadOnlyPair.second)
1983 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
1984
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00001985 Valid =
1986 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00001987
1988 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001989 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001990 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00001991
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001992 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001993}
1994
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001995static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
1996 ScopDetection &SD) {
1997
1998 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
1999
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002000 unsigned MinLD = INT_MAX, MaxLD = 0;
2001 for (BasicBlock *BB : R.blocks()) {
2002 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002003 if (!R.contains(L))
2004 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002005 if (BoxedLoops && BoxedLoops->count(L))
2006 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002007 unsigned LD = L->getLoopDepth();
2008 MinLD = std::min(MinLD, LD);
2009 MaxLD = std::max(MaxLD, LD);
2010 }
2011 }
2012
2013 // Handle the case that there is no loop in the SCoP first.
2014 if (MaxLD == 0)
2015 return 1;
2016
2017 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2018 assert(MaxLD >= MinLD &&
2019 "Maximal loop depth was smaller than mininaml loop depth?");
2020 return MaxLD - MinLD + 1;
2021}
2022
Johannes Doerfert96425c22015-08-30 21:13:53 +00002023Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, DominatorTree &DT,
2024 isl_ctx *Context, unsigned MaxLoopDepth)
2025 : DT(DT), SE(&ScalarEvolution), R(R), IsOptimized(false),
Johannes Doerfert717b8662015-09-08 21:44:27 +00002026 HasSingleExitEdge(R.getExitingBlock()), MaxLoopDepth(MaxLoopDepth),
2027 IslCtx(Context), Affinator(this) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002028
Tobias Grosser40985012015-08-20 19:08:05 +00002029void Scop::initFromTempScop(TempScop &TempScop, LoopInfo &LI, ScopDetection &SD,
2030 AliasAnalysis &AA) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002031 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00002032
Johannes Doerfert96425c22015-08-30 21:13:53 +00002033 buildDomains(&R, LI, SD, DT);
2034
Tobias Grosserabfbe632013-02-05 12:09:06 +00002035 SmallVector<Loop *, 8> NestLoops;
Tobias Grosser75805372011-04-29 06:27:02 +00002036
Tobias Grosser54839312015-04-21 11:37:25 +00002037 // Build the iteration domain, access functions and schedule functions
Tobias Grosser75805372011-04-29 06:27:02 +00002038 // traversing the region tree.
Michael Kruse471a5e32015-07-30 19:27:04 +00002039 Schedule = buildScop(TempScop, getRegion(), NestLoops, LI, SD);
Tobias Grosser808cd692015-07-14 09:33:13 +00002040 if (!Schedule)
2041 Schedule = isl_schedule_empty(getParamSpace());
Tobias Grosser75805372011-04-29 06:27:02 +00002042
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002043 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002044 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002045 addUserContext();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002046 simplifyAssumedContext();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002047 buildAliasChecks(AA);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002048
Tobias Grosser75805372011-04-29 06:27:02 +00002049 assert(NestLoops.empty() && "NestLoops not empty at top level!");
2050}
2051
Michael Kruse471a5e32015-07-30 19:27:04 +00002052Scop *Scop::createFromTempScop(TempScop &TempScop, LoopInfo &LI,
2053 ScalarEvolution &SE, ScopDetection &SD,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002054 AliasAnalysis &AA, DominatorTree &DT,
2055 isl_ctx *ctx) {
Michael Kruse471a5e32015-07-30 19:27:04 +00002056 auto &R = TempScop.getMaxRegion();
2057 auto MaxLoopDepth = getMaxLoopDepthInRegion(R, LI, SD);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002058 auto S = new Scop(R, SE, DT, ctx, MaxLoopDepth);
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002059 S->initFromTempScop(TempScop, LI, SD, AA);
2060
Michael Kruse471a5e32015-07-30 19:27:04 +00002061 return S;
2062}
2063
Tobias Grosser75805372011-04-29 06:27:02 +00002064Scop::~Scop() {
2065 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002066 isl_set_free(AssumedContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002067 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002068
Johannes Doerfert96425c22015-08-30 21:13:53 +00002069 for (auto It : DomainMap)
2070 isl_set_free(It.second);
2071
Johannes Doerfertb164c792014-09-18 11:17:17 +00002072 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002073 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002074 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002075 isl_pw_multi_aff_free(MMA.first);
2076 isl_pw_multi_aff_free(MMA.second);
2077 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002078 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002079 isl_pw_multi_aff_free(MMA.first);
2080 isl_pw_multi_aff_free(MMA.second);
2081 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002082 }
Tobias Grosser75805372011-04-29 06:27:02 +00002083}
2084
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002085const ScopArrayInfo *
2086Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Tobias Grosser92245222015-07-28 14:53:44 +00002087 const SmallVector<const SCEV *, 4> &Sizes,
2088 bool IsPHI) {
2089 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)];
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002090 if (!SAI)
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002091 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, IsPHI,
2092 this));
Tobias Grosserab671442015-05-23 05:58:27 +00002093 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002094}
2095
Tobias Grosser92245222015-07-28 14:53:44 +00002096const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, bool IsPHI) {
2097 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002098 assert(SAI && "No ScopArrayInfo available for this base pointer");
2099 return SAI;
2100}
2101
Tobias Grosser74394f02013-01-14 22:40:23 +00002102std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002103std::string Scop::getAssumedContextStr() const {
2104 return stringFromIslObj(AssumedContext);
2105}
Tobias Grosser75805372011-04-29 06:27:02 +00002106
2107std::string Scop::getNameStr() const {
2108 std::string ExitName, EntryName;
2109 raw_string_ostream ExitStr(ExitName);
2110 raw_string_ostream EntryStr(EntryName);
2111
Tobias Grosserf240b482014-01-09 10:42:15 +00002112 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002113 EntryStr.str();
2114
2115 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00002116 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002117 ExitStr.str();
2118 } else
2119 ExitName = "FunctionExit";
2120
2121 return EntryName + "---" + ExitName;
2122}
2123
Tobias Grosser74394f02013-01-14 22:40:23 +00002124__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00002125__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002126 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00002127}
2128
Tobias Grossere86109f2013-10-29 21:05:49 +00002129__isl_give isl_set *Scop::getAssumedContext() const {
2130 return isl_set_copy(AssumedContext);
2131}
2132
Johannes Doerfert43788c52015-08-20 05:58:56 +00002133__isl_give isl_set *Scop::getRuntimeCheckContext() const {
2134 isl_set *RuntimeCheckContext = getAssumedContext();
2135 return RuntimeCheckContext;
2136}
2137
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002138bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002139 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002140 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002141 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
2142 isl_set_free(RuntimeCheckContext);
2143 return IsFeasible;
2144}
2145
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002146void Scop::addAssumption(__isl_take isl_set *Set) {
2147 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00002148 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002149}
2150
Tobias Grosser75805372011-04-29 06:27:02 +00002151void Scop::printContext(raw_ostream &OS) const {
2152 OS << "Context:\n";
2153
2154 if (!Context) {
2155 OS.indent(4) << "n/a\n\n";
2156 return;
2157 }
2158
2159 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00002160
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002161 OS.indent(4) << "Assumed Context:\n";
2162 if (!AssumedContext) {
2163 OS.indent(4) << "n/a\n\n";
2164 return;
2165 }
2166
2167 OS.indent(4) << getAssumedContextStr() << "\n";
2168
Tobias Grosser083d3d32014-06-28 08:59:45 +00002169 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00002170 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00002171 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
2172 }
Tobias Grosser75805372011-04-29 06:27:02 +00002173}
2174
Johannes Doerfertb164c792014-09-18 11:17:17 +00002175void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002176 int noOfGroups = 0;
2177 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002178 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002179 noOfGroups += 1;
2180 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002181 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002182 }
2183
Tobias Grosserbb853c22015-07-25 12:31:03 +00002184 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00002185 if (MinMaxAliasGroups.empty()) {
2186 OS.indent(8) << "n/a\n";
2187 return;
2188 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002189
Tobias Grosserbb853c22015-07-25 12:31:03 +00002190 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002191
2192 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002193 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002194 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002195 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002196 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2197 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002198 }
2199 OS << " ]]\n";
2200 }
2201
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002202 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002203 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00002204 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002205 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002206 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2207 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002208 }
2209 OS << " ]]\n";
2210 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002211 }
2212}
2213
Tobias Grosser75805372011-04-29 06:27:02 +00002214void Scop::printStatements(raw_ostream &OS) const {
2215 OS << "Statements {\n";
2216
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002217 for (const ScopStmt &Stmt : *this)
2218 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00002219
2220 OS.indent(4) << "}\n";
2221}
2222
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002223void Scop::printArrayInfo(raw_ostream &OS) const {
2224 OS << "Arrays {\n";
2225
Tobias Grosserab671442015-05-23 05:58:27 +00002226 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002227 Array.second->print(OS);
2228
2229 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002230
2231 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
2232
2233 for (auto &Array : arrays())
2234 Array.second->print(OS, /* SizeAsPwAff */ true);
2235
2236 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002237}
2238
Tobias Grosser75805372011-04-29 06:27:02 +00002239void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00002240 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
2241 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00002242 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00002243 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00002244 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002245 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002246 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00002247 printStatements(OS.indent(4));
2248}
2249
2250void Scop::dump() const { print(dbgs()); }
2251
Tobias Grosser9a38ab82011-11-08 15:41:03 +00002252isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00002253
Johannes Doerfertb409fdc2015-08-28 09:24:35 +00002254__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, isl_set *Domain) {
2255 return Affinator.getPwAff(E, Domain);
Johannes Doerfert574182d2015-08-12 10:19:50 +00002256}
2257
Tobias Grosser808cd692015-07-14 09:33:13 +00002258__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002259 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002260
Tobias Grosser808cd692015-07-14 09:33:13 +00002261 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002262 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002263
2264 return Domain;
2265}
2266
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002267__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002268 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002269
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002270 for (ScopStmt &Stmt : *this) {
2271 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002272 if (!MA->isMustWrite())
2273 continue;
2274
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002275 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002276 isl_map *AccessDomain = MA->getAccessRelation();
2277 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2278 Write = isl_union_map_add_map(Write, AccessDomain);
2279 }
2280 }
2281 return isl_union_map_coalesce(Write);
2282}
2283
2284__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002285 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002286
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002287 for (ScopStmt &Stmt : *this) {
2288 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002289 if (!MA->isMayWrite())
2290 continue;
2291
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002292 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002293 isl_map *AccessDomain = MA->getAccessRelation();
2294 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2295 Write = isl_union_map_add_map(Write, AccessDomain);
2296 }
2297 }
2298 return isl_union_map_coalesce(Write);
2299}
2300
Tobias Grosser37eb4222014-02-20 21:43:54 +00002301__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002302 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002303
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002304 for (ScopStmt &Stmt : *this) {
2305 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002306 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002307 continue;
2308
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002309 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002310 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002311 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2312 Write = isl_union_map_add_map(Write, AccessDomain);
2313 }
2314 }
2315 return isl_union_map_coalesce(Write);
2316}
2317
2318__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002319 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002320
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002321 for (ScopStmt &Stmt : *this) {
2322 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002323 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002324 continue;
2325
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002326 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002327 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002328
2329 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2330 Read = isl_union_map_add_map(Read, AccessDomain);
2331 }
2332 }
2333 return isl_union_map_coalesce(Read);
2334}
2335
Tobias Grosser808cd692015-07-14 09:33:13 +00002336__isl_give isl_union_map *Scop::getSchedule() const {
2337 auto Tree = getScheduleTree();
2338 auto S = isl_schedule_get_map(Tree);
2339 isl_schedule_free(Tree);
2340 return S;
2341}
Tobias Grosser37eb4222014-02-20 21:43:54 +00002342
Tobias Grosser808cd692015-07-14 09:33:13 +00002343__isl_give isl_schedule *Scop::getScheduleTree() const {
2344 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
2345 getDomains());
2346}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002347
Tobias Grosser808cd692015-07-14 09:33:13 +00002348void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
2349 auto *S = isl_schedule_from_domain(getDomains());
2350 S = isl_schedule_insert_partial_schedule(
2351 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
2352 isl_schedule_free(Schedule);
2353 Schedule = S;
2354}
2355
2356void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
2357 isl_schedule_free(Schedule);
2358 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00002359}
2360
2361bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
2362 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002363 for (ScopStmt &Stmt : *this) {
2364 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002365 isl_union_set *NewStmtDomain = isl_union_set_intersect(
2366 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
2367
2368 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
2369 isl_union_set_free(StmtDomain);
2370 isl_union_set_free(NewStmtDomain);
2371 continue;
2372 }
2373
2374 Changed = true;
2375
2376 isl_union_set_free(StmtDomain);
2377 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
2378
2379 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002380 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002381 isl_union_set_free(NewStmtDomain);
2382 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002383 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002384 }
2385 isl_union_set_free(Domain);
2386 return Changed;
2387}
2388
Tobias Grosser75805372011-04-29 06:27:02 +00002389ScalarEvolution *Scop::getSE() const { return SE; }
2390
2391bool Scop::isTrivialBB(BasicBlock *BB, TempScop &tempScop) {
2392 if (tempScop.getAccessFunctions(BB))
2393 return false;
2394
2395 return true;
2396}
2397
Tobias Grosser808cd692015-07-14 09:33:13 +00002398struct MapToDimensionDataTy {
2399 int N;
2400 isl_union_pw_multi_aff *Res;
2401};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002402
Tobias Grosser808cd692015-07-14 09:33:13 +00002403// @brief Create a function that maps the elements of 'Set' to its N-th
2404// dimension.
2405//
2406// The result is added to 'User->Res'.
2407//
2408// @param Set The input set.
2409// @param N The dimension to map to.
2410//
2411// @returns Zero if no error occurred, non-zero otherwise.
2412static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
2413 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
2414 int Dim;
2415 isl_space *Space;
2416 isl_pw_multi_aff *PMA;
2417
2418 Dim = isl_set_dim(Set, isl_dim_set);
2419 Space = isl_set_get_space(Set);
2420 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
2421 Dim - Data->N);
2422 if (Data->N > 1)
2423 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
2424 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
2425
2426 isl_set_free(Set);
2427
2428 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002429}
2430
Tobias Grosser808cd692015-07-14 09:33:13 +00002431// @brief Create a function that maps the elements of Domain to their Nth
2432// dimension.
2433//
2434// @param Domain The set of elements to map.
2435// @param N The dimension to map to.
2436static __isl_give isl_multi_union_pw_aff *
2437mapToDimension(__isl_take isl_union_set *Domain, int N) {
2438 struct MapToDimensionDataTy Data;
2439 isl_space *Space;
2440
2441 Space = isl_union_set_get_space(Domain);
2442 Data.N = N;
2443 Data.Res = isl_union_pw_multi_aff_empty(Space);
2444 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
2445 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
2446
2447 isl_union_set_free(Domain);
2448 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
2449}
2450
2451ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R, TempScop &tempScop,
2452 const Region &CurRegion,
2453 SmallVectorImpl<Loop *> &NestLoops) {
2454 ScopStmt *Stmt;
2455 if (BB) {
2456 Stmts.emplace_back(*this, tempScop, CurRegion, *BB, NestLoops);
2457 Stmt = &Stmts.back();
2458 StmtMap[BB] = Stmt;
2459 } else {
2460 assert(R && "Either basic block or a region expected.");
2461 Stmts.emplace_back(*this, tempScop, CurRegion, *R, NestLoops);
2462 Stmt = &Stmts.back();
2463 for (BasicBlock *BB : R->blocks())
2464 StmtMap[BB] = Stmt;
2465 }
2466 return Stmt;
2467}
2468
Michael Kruse046dde42015-08-10 13:01:57 +00002469__isl_give isl_schedule *
2470Scop::buildBBScopStmt(BasicBlock *BB, TempScop &tempScop,
2471 const Region &CurRegion,
2472 SmallVectorImpl<Loop *> &NestLoops) {
2473 if (isTrivialBB(BB, tempScop))
2474 return nullptr;
2475
2476 auto *Stmt = addScopStmt(BB, nullptr, tempScop, CurRegion, NestLoops);
2477 auto *Domain = Stmt->getDomain();
2478 return isl_schedule_from_domain(isl_union_set_from_set(Domain));
2479}
2480
Tobias Grosser808cd692015-07-14 09:33:13 +00002481__isl_give isl_schedule *Scop::buildScop(TempScop &tempScop,
2482 const Region &CurRegion,
2483 SmallVectorImpl<Loop *> &NestLoops,
2484 LoopInfo &LI, ScopDetection &SD) {
2485 if (SD.isNonAffineSubRegion(&CurRegion, &getRegion())) {
2486 auto *Stmt = addScopStmt(nullptr, const_cast<Region *>(&CurRegion),
2487 tempScop, CurRegion, NestLoops);
2488 auto *Domain = Stmt->getDomain();
2489 return isl_schedule_from_domain(isl_union_set_from_set(Domain));
2490 }
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002491
Tobias Grosser75805372011-04-29 06:27:02 +00002492 Loop *L = castToLoop(CurRegion, LI);
2493
2494 if (L)
2495 NestLoops.push_back(L);
2496
2497 unsigned loopDepth = NestLoops.size();
Tobias Grosser808cd692015-07-14 09:33:13 +00002498 isl_schedule *Schedule = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002499
2500 for (Region::const_element_iterator I = CurRegion.element_begin(),
Tobias Grosserabfbe632013-02-05 12:09:06 +00002501 E = CurRegion.element_end();
Tobias Grosser808cd692015-07-14 09:33:13 +00002502 I != E; ++I) {
2503 isl_schedule *StmtSchedule = nullptr;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002504 if (I->isSubRegion()) {
Tobias Grosser808cd692015-07-14 09:33:13 +00002505 StmtSchedule =
2506 buildScop(tempScop, *I->getNodeAs<Region>(), NestLoops, LI, SD);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002507 } else {
Michael Kruse046dde42015-08-10 13:01:57 +00002508 StmtSchedule = buildBBScopStmt(I->getNodeAs<BasicBlock>(), tempScop,
2509 CurRegion, NestLoops);
Tobias Grosser75805372011-04-29 06:27:02 +00002510 }
Michael Kruse046dde42015-08-10 13:01:57 +00002511 Schedule = combineInSequence(Schedule, StmtSchedule);
Tobias Grosser808cd692015-07-14 09:33:13 +00002512 }
Tobias Grosser75805372011-04-29 06:27:02 +00002513
Tobias Grosser808cd692015-07-14 09:33:13 +00002514 if (!L)
2515 return Schedule;
2516
2517 auto *Domain = isl_schedule_get_domain(Schedule);
2518 if (!isl_union_set_is_empty(Domain)) {
2519 auto *MUPA = mapToDimension(isl_union_set_copy(Domain), loopDepth);
2520 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
2521 }
2522 isl_union_set_free(Domain);
2523
Tobias Grosser75805372011-04-29 06:27:02 +00002524 NestLoops.pop_back();
Tobias Grosser808cd692015-07-14 09:33:13 +00002525 return Schedule;
Tobias Grosser75805372011-04-29 06:27:02 +00002526}
2527
Johannes Doerfert7c494212014-10-31 23:13:39 +00002528ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00002529 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00002530 if (StmtMapIt == StmtMap.end())
2531 return nullptr;
2532 return StmtMapIt->second;
2533}
2534
Michael Kruse7bf39442015-09-10 12:46:52 +00002535//===----------------------------------------------------------------------===//
2536// TempScop implementation
2537TempScop::~TempScop() {}
2538
2539void TempScop::print(raw_ostream &OS, ScalarEvolution *SE, LoopInfo *LI) const {
2540 OS << "Scop: " << R.getNameStr() << "\n";
2541
2542 printDetail(OS, SE, LI, &R, 0);
2543}
2544
2545void TempScop::printDetail(raw_ostream &OS, ScalarEvolution *SE, LoopInfo *LI,
2546 const Region *CurR, unsigned ind) const {
2547 // FIXME: Print other details rather than memory accesses.
2548 for (const auto &CurBlock : CurR->blocks()) {
2549 AccFuncMapType::const_iterator AccSetIt = AccFuncMap.find(CurBlock);
2550
2551 // Ignore trivial blocks that do not contain any memory access.
2552 if (AccSetIt == AccFuncMap.end())
2553 continue;
2554
2555 OS.indent(ind) << "BB: " << CurBlock->getName() << '\n';
2556 typedef AccFuncSetType::const_iterator access_iterator;
2557 const AccFuncSetType &AccFuncs = AccSetIt->second;
2558
2559 for (access_iterator AI = AccFuncs.begin(), AE = AccFuncs.end(); AI != AE;
2560 ++AI)
2561 AI->first.print(OS.indent(ind + 2));
2562 }
2563}
2564
Johannes Doerfert96425c22015-08-30 21:13:53 +00002565int Scop::getRelativeLoopDepth(const Loop *L) const {
2566 Loop *OuterLoop =
2567 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
2568 if (!OuterLoop)
2569 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00002570 return L->getLoopDepth() - OuterLoop->getLoopDepth();
2571}
2572
Michael Kruse7bf39442015-09-10 12:46:52 +00002573void TempScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
2574 AccFuncSetType &Functions,
2575 Region *NonAffineSubRegion,
2576 bool IsExitBlock) {
2577
2578 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
2579 // true, are not modeled as ordinary PHI nodes as they are not part of the
2580 // region. However, we model the operands in the predecessor blocks that are
2581 // part of the region as regular scalar accesses.
2582
2583 // If we can synthesize a PHI we can skip it, however only if it is in
2584 // the region. If it is not it can only be in the exit block of the region.
2585 // In this case we model the operands but not the PHI itself.
2586 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
2587 return;
2588
2589 // PHI nodes are modeled as if they had been demoted prior to the SCoP
2590 // detection. Hence, the PHI is a load of a new memory location in which the
2591 // incoming value was written at the end of the incoming basic block.
2592 bool OnlyNonAffineSubRegionOperands = true;
2593 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
2594 Value *Op = PHI->getIncomingValue(u);
2595 BasicBlock *OpBB = PHI->getIncomingBlock(u);
2596
2597 // Do not build scalar dependences inside a non-affine subregion.
2598 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
2599 continue;
2600
2601 OnlyNonAffineSubRegionOperands = false;
2602
2603 if (!R.contains(OpBB))
2604 continue;
2605
2606 Instruction *OpI = dyn_cast<Instruction>(Op);
2607 if (OpI) {
2608 BasicBlock *OpIBB = OpI->getParent();
2609 // As we pretend there is a use (or more precise a write) of OpI in OpBB
2610 // we have to insert a scalar dependence from the definition of OpI to
2611 // OpBB if the definition is not in OpBB.
2612 if (OpIBB != OpBB) {
2613 IRAccess ScalarRead(IRAccess::READ, OpI, ZeroOffset, 1, true, OpI);
2614 AccFuncMap[OpBB].push_back(std::make_pair(ScalarRead, PHI));
2615 IRAccess ScalarWrite(IRAccess::MUST_WRITE, OpI, ZeroOffset, 1, true,
2616 OpI);
2617 AccFuncMap[OpIBB].push_back(std::make_pair(ScalarWrite, OpI));
2618 }
2619 }
2620
2621 // Always use the terminator of the incoming basic block as the access
2622 // instruction.
2623 OpI = OpBB->getTerminator();
2624
2625 IRAccess ScalarAccess(IRAccess::MUST_WRITE, PHI, ZeroOffset, 1, true, Op,
2626 /* IsPHI */ !IsExitBlock);
2627 AccFuncMap[OpBB].push_back(std::make_pair(ScalarAccess, OpI));
2628 }
2629
2630 if (!OnlyNonAffineSubRegionOperands) {
2631 IRAccess ScalarAccess(IRAccess::READ, PHI, ZeroOffset, 1, true, PHI,
2632 /* IsPHI */ !IsExitBlock);
2633 Functions.push_back(std::make_pair(ScalarAccess, PHI));
2634 }
2635}
2636
2637bool TempScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
2638 Region *NonAffineSubRegion) {
2639 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
2640 if (isIgnoredIntrinsic(Inst))
2641 return false;
2642
2643 bool AnyCrossStmtUse = false;
2644 BasicBlock *ParentBB = Inst->getParent();
2645
2646 for (User *U : Inst->users()) {
2647 Instruction *UI = dyn_cast<Instruction>(U);
2648
2649 // Ignore the strange user
2650 if (UI == 0)
2651 continue;
2652
2653 BasicBlock *UseParent = UI->getParent();
2654
2655 // Ignore the users in the same BB (statement)
2656 if (UseParent == ParentBB)
2657 continue;
2658
2659 // Do not build scalar dependences inside a non-affine subregion.
2660 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
2661 continue;
2662
2663 // Check whether or not the use is in the SCoP.
2664 if (!R->contains(UseParent)) {
2665 AnyCrossStmtUse = true;
2666 continue;
2667 }
2668
2669 // If the instruction can be synthesized and the user is in the region
2670 // we do not need to add scalar dependences.
2671 if (canSynthesizeInst)
2672 continue;
2673
2674 // No need to translate these scalar dependences into polyhedral form,
2675 // because synthesizable scalars can be generated by the code generator.
2676 if (canSynthesize(UI, LI, SE, R))
2677 continue;
2678
2679 // Skip PHI nodes in the region as they handle their operands on their own.
2680 if (isa<PHINode>(UI))
2681 continue;
2682
2683 // Now U is used in another statement.
2684 AnyCrossStmtUse = true;
2685
2686 // Do not build a read access that is not in the current SCoP
2687 // Use the def instruction as base address of the IRAccess, so that it will
2688 // become the name of the scalar access in the polyhedral form.
2689 IRAccess ScalarAccess(IRAccess::READ, Inst, ZeroOffset, 1, true, Inst);
2690 AccFuncMap[UseParent].push_back(std::make_pair(ScalarAccess, UI));
2691 }
2692
2693 if (ModelReadOnlyScalars) {
2694 for (Value *Op : Inst->operands()) {
2695 if (canSynthesize(Op, LI, SE, R))
2696 continue;
2697
2698 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
2699 if (R->contains(OpInst))
2700 continue;
2701
2702 if (isa<Constant>(Op))
2703 continue;
2704
2705 IRAccess ScalarAccess(IRAccess::READ, Op, ZeroOffset, 1, true, Op);
2706 AccFuncMap[Inst->getParent()].push_back(
2707 std::make_pair(ScalarAccess, Inst));
2708 }
2709 }
2710
2711 return AnyCrossStmtUse;
2712}
2713
2714extern MapInsnToMemAcc InsnToMemAcc;
2715
2716IRAccess
2717TempScopInfo::buildIRAccess(Instruction *Inst, Loop *L, Region *R,
2718 const ScopDetection::BoxedLoopsSetTy *BoxedLoops) {
2719 unsigned Size;
2720 Type *SizeType;
2721 Value *Val;
2722 enum IRAccess::TypeKind Type;
2723
2724 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
2725 SizeType = Load->getType();
2726 Size = TD->getTypeStoreSize(SizeType);
2727 Type = IRAccess::READ;
2728 Val = Load;
2729 } else {
2730 StoreInst *Store = cast<StoreInst>(Inst);
2731 SizeType = Store->getValueOperand()->getType();
2732 Size = TD->getTypeStoreSize(SizeType);
2733 Type = IRAccess::MUST_WRITE;
2734 Val = Store->getValueOperand();
2735 }
2736
2737 const SCEV *AccessFunction = SE->getSCEVAtScope(getPointerOperand(*Inst), L);
2738 const SCEVUnknown *BasePointer =
2739 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
2740
2741 assert(BasePointer && "Could not find base pointer");
2742 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
2743
2744 auto AccItr = InsnToMemAcc.find(Inst);
2745 if (PollyDelinearize && AccItr != InsnToMemAcc.end())
2746 return IRAccess(Type, BasePointer->getValue(), AccessFunction, Size, true,
2747 AccItr->second.DelinearizedSubscripts,
2748 AccItr->second.Shape->DelinearizedSizes, Val);
2749
2750 // Check if the access depends on a loop contained in a non-affine subregion.
2751 bool isVariantInNonAffineLoop = false;
2752 if (BoxedLoops) {
2753 SetVector<const Loop *> Loops;
2754 findLoops(AccessFunction, Loops);
2755 for (const Loop *L : Loops)
2756 if (BoxedLoops->count(L))
2757 isVariantInNonAffineLoop = true;
2758 }
2759
2760 bool IsAffine = !isVariantInNonAffineLoop &&
2761 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue());
2762
2763 SmallVector<const SCEV *, 4> Subscripts, Sizes;
2764 Subscripts.push_back(AccessFunction);
2765 Sizes.push_back(SE->getConstant(ZeroOffset->getType(), Size));
2766
2767 if (!IsAffine && Type == IRAccess::MUST_WRITE)
2768 Type = IRAccess::MAY_WRITE;
2769
2770 return IRAccess(Type, BasePointer->getValue(), AccessFunction, Size, IsAffine,
2771 Subscripts, Sizes, Val);
2772}
2773
2774void TempScopInfo::buildAccessFunctions(Region &R, Region &SR) {
2775
2776 if (SD->isNonAffineSubRegion(&SR, &R)) {
2777 for (BasicBlock *BB : SR.blocks())
2778 buildAccessFunctions(R, *BB, &SR);
2779 return;
2780 }
2781
2782 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
2783 if (I->isSubRegion())
2784 buildAccessFunctions(R, *I->getNodeAs<Region>());
2785 else
2786 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
2787}
2788
2789void TempScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
2790 Region *NonAffineSubRegion,
2791 bool IsExitBlock) {
2792 AccFuncSetType Functions;
2793 Loop *L = LI->getLoopFor(&BB);
2794
2795 // The set of loops contained in non-affine subregions that are part of R.
2796 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
2797
2798 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
2799 Instruction *Inst = I;
2800
2801 PHINode *PHI = dyn_cast<PHINode>(Inst);
2802 if (PHI)
2803 buildPHIAccesses(PHI, R, Functions, NonAffineSubRegion, IsExitBlock);
2804
2805 // For the exit block we stop modeling after the last PHI node.
2806 if (!PHI && IsExitBlock)
2807 break;
2808
2809 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
2810 Functions.push_back(
2811 std::make_pair(buildIRAccess(Inst, L, &R, BoxedLoops), Inst));
2812
2813 if (isIgnoredIntrinsic(Inst))
2814 continue;
2815
2816 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
2817 // If the Instruction is used outside the statement, we need to build the
2818 // write access.
2819 if (!isa<StoreInst>(Inst)) {
2820 IRAccess ScalarAccess(IRAccess::MUST_WRITE, Inst, ZeroOffset, 1, true,
2821 Inst);
2822 Functions.push_back(std::make_pair(ScalarAccess, Inst));
2823 }
2824 }
2825 }
2826
2827 if (Functions.empty())
2828 return;
2829
2830 AccFuncSetType &Accs = AccFuncMap[&BB];
2831 Accs.insert(Accs.end(), Functions.begin(), Functions.end());
2832}
2833
2834TempScop *TempScopInfo::buildTempScop(Region &R) {
2835 TempScop *TScop = new TempScop(R, AccFuncMap);
2836
2837 buildAccessFunctions(R, R);
2838
2839 // In case the region does not have an exiting block we will later (during
2840 // code generation) split the exit block. This will move potential PHI nodes
2841 // from the current exit block into the new region exiting block. Hence, PHI
2842 // nodes that are at this point not part of the region will be.
2843 // To handle these PHI nodes later we will now model their operands as scalar
2844 // accesses. Note that we do not model anything in the exit block if we have
2845 // an exiting block in the region, as there will not be any splitting later.
2846 if (!R.getExitingBlock())
2847 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
2848
2849 return TScop;
2850}
2851
2852TempScop *TempScopInfo::getTempScop() const { return TempScopOfRegion; }
2853
2854void TempScopInfo::print(raw_ostream &OS, const Module *) const {
2855 if (TempScopOfRegion)
2856 TempScopOfRegion->print(OS, SE, LI);
2857}
2858
2859bool TempScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
2860 SD = &getAnalysis<ScopDetection>();
2861
2862 if (!SD->isMaxRegionInScop(*R))
2863 return false;
2864
2865 Function *F = R->getEntry()->getParent();
2866 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2867 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2868 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2869 TD = &F->getParent()->getDataLayout();
2870 ZeroOffset = SE->getConstant(TD->getIntPtrType(F->getContext()), 0);
2871
2872 assert(!TempScopOfRegion && "Build the TempScop only once");
2873 TempScopOfRegion = buildTempScop(*R);
2874
2875 return false;
2876}
2877
2878void TempScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
2879 AU.addRequiredTransitive<LoopInfoWrapperPass>();
2880 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
2881 AU.addRequiredTransitive<ScopDetection>();
2882 AU.addRequiredID(IndependentBlocksID);
2883 AU.addRequired<AAResultsWrapperPass>();
2884 AU.setPreservesAll();
2885}
2886
2887TempScopInfo::~TempScopInfo() { clear(); }
2888
2889void TempScopInfo::clear() {
2890 AccFuncMap.clear();
2891 if (TempScopOfRegion)
2892 delete TempScopOfRegion;
2893 TempScopOfRegion = nullptr;
2894}
2895
2896//===----------------------------------------------------------------------===//
2897// TempScop information extraction pass implement
2898char TempScopInfo::ID = 0;
2899
2900Pass *polly::createTempScopInfoPass() { return new TempScopInfo(); }
2901
2902INITIALIZE_PASS_BEGIN(TempScopInfo, "polly-analyze-ir",
2903 "Polly - Analyse the LLVM-IR in the detected regions",
2904 false, false);
2905INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
2906INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
2907INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
2908INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
2909INITIALIZE_PASS_END(TempScopInfo, "polly-analyze-ir",
2910 "Polly - Analyse the LLVM-IR in the detected regions",
2911 false, false)
2912
Tobias Grosser75805372011-04-29 06:27:02 +00002913//===----------------------------------------------------------------------===//
Tobias Grosserb76f38532011-08-20 11:11:25 +00002914ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
2915 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00002916 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00002917}
2918
2919ScopInfo::~ScopInfo() {
2920 clear();
2921 isl_ctx_free(ctx);
2922}
2923
Tobias Grosser75805372011-04-29 06:27:02 +00002924void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00002925 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00002926 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00002927 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00002928 AU.addRequired<ScalarEvolutionWrapperPass>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002929 AU.addRequired<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00002930 AU.addRequired<TempScopInfo>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00002931 AU.addRequired<AAResultsWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00002932 AU.setPreservesAll();
2933}
2934
2935bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Chandler Carruthf5579872015-01-17 14:16:56 +00002936 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00002937 AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002938 ScopDetection &SD = getAnalysis<ScopDetection>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00002939 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert96425c22015-08-30 21:13:53 +00002940 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00002941
Michael Kruse82a1c7d2015-08-14 20:10:27 +00002942 TempScop *tempScop = getAnalysis<TempScopInfo>().getTempScop();
Tobias Grosser75805372011-04-29 06:27:02 +00002943
2944 // This region is no Scop.
2945 if (!tempScop) {
Tobias Grosserc98a8fc2014-11-14 11:12:31 +00002946 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002947 return false;
2948 }
2949
Johannes Doerfert96425c22015-08-30 21:13:53 +00002950 scop = Scop::createFromTempScop(*tempScop, LI, SE, SD, AA, DT, ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00002951
Tobias Grosserd6a50b32015-05-30 06:26:21 +00002952 DEBUG(scop->print(dbgs()));
2953
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002954 if (!scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002955 delete scop;
2956 scop = nullptr;
2957 return false;
2958 }
2959
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002960 // Statistics.
2961 ++ScopFound;
2962 if (scop->getMaxLoopDepth() > 0)
2963 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00002964 return false;
2965}
2966
2967char ScopInfo::ID = 0;
2968
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002969Pass *polly::createScopInfoPass() { return new ScopInfo(); }
2970
Tobias Grosser73600b82011-10-08 00:30:40 +00002971INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
2972 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002973 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00002974INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00002975INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00002976INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00002977INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002978INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002979INITIALIZE_PASS_DEPENDENCY(TempScopInfo);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002980INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00002981INITIALIZE_PASS_END(ScopInfo, "polly-scops",
2982 "Polly - Create polyhedral description of Scops", false,
2983 false)