blob: 219627b287c670271580dd1134852bd78a8c5dbf [file] [log] [blame]
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001
Tobias Grosser75805372011-04-29 06:27:02 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Create a polyhedral description for a static control flow region.
11//
12// The pass creates a polyhedral description of the Scops detected by the Scop
13// detection derived from their LLVM-IR code.
14//
Tobias Grossera5605d32014-10-29 19:58:28 +000015// This representation is shared among several tools in the polyhedral
Tobias Grosser75805372011-04-29 06:27:02 +000016// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
Tobias Grosser75805372011-04-29 06:27:02 +000020#include "polly/LinkAllPasses.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000021#include "polly/CodeGen/BlockGenerators.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000022#include "polly/Options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000023#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000024#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000025#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000026#include "polly/Support/ScopHelper.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000027#include "llvm/ADT/MapVector.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000028#include "llvm/ADT/PostOrderIterator.h"
29#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000030#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000031#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000032#include "llvm/ADT/StringExtras.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 Grosserc2bb0cb2015-09-25 09:49:19 +000035#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000036#include "llvm/Analysis/RegionIterator.h"
37#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser75805372011-04-29 06:27:02 +000038#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000039#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000040#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000041#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000042#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000043#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000044#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000045#include "isl/schedule.h"
46#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000047#include "isl/set.h"
48#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000049#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000050#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000051#include <sstream>
52#include <string>
53#include <vector>
54
55using namespace llvm;
56using namespace polly;
57
Chandler Carruth95fef942014-04-22 03:30:19 +000058#define DEBUG_TYPE "polly-scops"
59
Tobias Grosser74394f02013-01-14 22:40:23 +000060STATISTIC(ScopFound, "Number of valid Scops");
61STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000062
Michael Kruse7bf39442015-09-10 12:46:52 +000063static cl::opt<bool> ModelReadOnlyScalars(
64 "polly-analyze-read-only-scalars",
65 cl::desc("Model read-only scalar values in the scop description"),
66 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
67
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000068// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000069// operations can overflow easily. Additive reductions and bit operations
70// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000071static cl::opt<bool> DisableMultiplicativeReductions(
72 "polly-disable-multiplicative-reductions",
73 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
74 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000075
Johannes Doerfert9143d672014-09-27 11:02:39 +000076static cl::opt<unsigned> RunTimeChecksMaxParameters(
77 "polly-rtc-max-parameters",
78 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
79 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
80
Tobias Grosser71500722015-03-28 15:11:14 +000081static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
82 "polly-rtc-max-arrays-per-group",
83 cl::desc("The maximal number of arrays to compare in each alias group."),
84 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000085static cl::opt<std::string> UserContextStr(
86 "polly-context", cl::value_desc("isl parameter set"),
87 cl::desc("Provide additional constraints on the context parameters"),
88 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000089
Tobias Grosserd83b8a82015-08-20 19:08:11 +000090static cl::opt<bool> DetectReductions("polly-detect-reductions",
91 cl::desc("Detect and exploit reductions"),
92 cl::Hidden, cl::ZeroOrMore,
93 cl::init(true), cl::cat(PollyCategory));
94
Michael Kruse7bf39442015-09-10 12:46:52 +000095//===----------------------------------------------------------------------===//
96/// Helper Classes
97
98void Comparison::print(raw_ostream &OS) const {
99 // Not yet implemented.
100}
101
Michael Kruse046dde42015-08-10 13:01:57 +0000102// Create a sequence of two schedules. Either argument may be null and is
103// interpreted as the empty schedule. Can also return null if both schedules are
104// empty.
105static __isl_give isl_schedule *
106combineInSequence(__isl_take isl_schedule *Prev,
107 __isl_take isl_schedule *Succ) {
108 if (!Prev)
109 return Succ;
110 if (!Succ)
111 return Prev;
112
113 return isl_schedule_sequence(Prev, Succ);
114}
115
Johannes Doerferte7044942015-02-24 11:58:30 +0000116static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
117 const ConstantRange &Range,
118 int dim,
119 enum isl_dim_type type) {
120 isl_val *V;
121 isl_ctx *ctx = isl_set_get_ctx(S);
122
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000123 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
124 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000125 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000126 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
127
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000128 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000129 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000130 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000131 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000132 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
133
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000134 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000135 return isl_set_union(SLB, SUB);
136 else
137 return isl_set_intersect(SLB, SUB);
138}
139
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000140static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
141 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
142 if (!BasePtrLI)
143 return nullptr;
144
145 if (!S->getRegion().contains(BasePtrLI))
146 return nullptr;
147
148 ScalarEvolution &SE = *S->getSE();
149
150 auto *OriginBaseSCEV =
151 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
152 if (!OriginBaseSCEV)
153 return nullptr;
154
155 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
156 if (!OriginBaseSCEVUnknown)
157 return nullptr;
158
159 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue());
160}
161
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000162ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Michael Kruse28468772015-09-14 15:45:33 +0000163 ArrayRef<const SCEV *> DimensionSizes, bool IsPHI,
164 Scop *S)
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000165 : BasePtr(BasePtr), ElementType(ElementType),
Michael Kruse28468772015-09-14 15:45:33 +0000166 DimensionSizes(DimensionSizes.begin(), DimensionSizes.end()),
167 IsPHI(IsPHI) {
Tobias Grosser92245222015-07-28 14:53:44 +0000168 std::string BasePtrName =
169 getIslCompatibleName("MemRef_", BasePtr, IsPHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000170 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000171 for (const SCEV *Expr : DimensionSizes) {
172 isl_pw_aff *Size = S->getPwAff(Expr);
173 DimensionSizesPw.push_back(Size);
174 }
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000175
176 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
177 if (BasePtrOriginSAI)
178 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000179}
180
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000181ScopArrayInfo::~ScopArrayInfo() {
182 isl_id_free(Id);
183 for (isl_pw_aff *Size : DimensionSizesPw)
184 isl_pw_aff_free(Size);
185}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000186
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000187std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
188
189int ScopArrayInfo::getElemSizeInBytes() const {
190 return ElementType->getPrimitiveSizeInBits() / 8;
191}
192
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000193isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
194
195void ScopArrayInfo::dump() const { print(errs()); }
196
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000197void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000198 OS.indent(8) << *getElementType() << " " << getName() << "[*]";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000199 for (unsigned u = 0; u < getNumberOfDimensions(); u++) {
200 OS << "[";
201
202 if (SizeAsPwAff)
203 OS << " " << DimensionSizesPw[u] << " ";
204 else
205 OS << *DimensionSizes[u];
206
207 OS << "]";
208 }
209
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000210 if (BasePtrOriginSAI)
211 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
212
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000213 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000214}
215
216const ScopArrayInfo *
217ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
218 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
219 assert(Id && "Output dimension didn't have an ID");
220 return getFromId(Id);
221}
222
223const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
224 void *User = isl_id_get_user(Id);
225 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
226 isl_id_free(Id);
227 return SAI;
228}
229
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000230const std::string
231MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
232 switch (RT) {
233 case MemoryAccess::RT_NONE:
234 llvm_unreachable("Requested a reduction operator string for a memory "
235 "access which isn't a reduction");
236 case MemoryAccess::RT_ADD:
237 return "+";
238 case MemoryAccess::RT_MUL:
239 return "*";
240 case MemoryAccess::RT_BOR:
241 return "|";
242 case MemoryAccess::RT_BXOR:
243 return "^";
244 case MemoryAccess::RT_BAND:
245 return "&";
246 }
247 llvm_unreachable("Unknown reduction type");
248 return "";
249}
250
Johannes Doerfertf6183392014-07-01 20:52:51 +0000251/// @brief Return the reduction type for a given binary operator
252static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
253 const Instruction *Load) {
254 if (!BinOp)
255 return MemoryAccess::RT_NONE;
256 switch (BinOp->getOpcode()) {
257 case Instruction::FAdd:
258 if (!BinOp->hasUnsafeAlgebra())
259 return MemoryAccess::RT_NONE;
260 // Fall through
261 case Instruction::Add:
262 return MemoryAccess::RT_ADD;
263 case Instruction::Or:
264 return MemoryAccess::RT_BOR;
265 case Instruction::Xor:
266 return MemoryAccess::RT_BXOR;
267 case Instruction::And:
268 return MemoryAccess::RT_BAND;
269 case Instruction::FMul:
270 if (!BinOp->hasUnsafeAlgebra())
271 return MemoryAccess::RT_NONE;
272 // Fall through
273 case Instruction::Mul:
274 if (DisableMultiplicativeReductions)
275 return MemoryAccess::RT_NONE;
276 return MemoryAccess::RT_MUL;
277 default:
278 return MemoryAccess::RT_NONE;
279 }
280}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000281
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000282/// @brief Derive the individual index expressions from a GEP instruction
283///
284/// This function optimistically assumes the GEP references into a fixed size
285/// array. If this is actually true, this function returns a list of array
286/// subscript expressions as SCEV as well as a list of integers describing
287/// the size of the individual array dimensions. Both lists have either equal
288/// length of the size list is one element shorter in case there is no known
289/// size available for the outermost array dimension.
290///
291/// @param GEP The GetElementPtr instruction to analyze.
292///
293/// @return A tuple with the subscript expressions and the dimension sizes.
294static std::tuple<std::vector<const SCEV *>, std::vector<int>>
295getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
296 std::vector<const SCEV *> Subscripts;
297 std::vector<int> Sizes;
298
299 Type *Ty = GEP->getPointerOperandType();
300
301 bool DroppedFirstDim = false;
302
Michael Kruse26ed65e2015-09-24 17:32:49 +0000303 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000304
305 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
306
307 if (i == 1) {
308 if (auto PtrTy = dyn_cast<PointerType>(Ty)) {
309 Ty = PtrTy->getElementType();
310 } else if (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
311 Ty = ArrayTy->getElementType();
312 } else {
313 Subscripts.clear();
314 Sizes.clear();
315 break;
316 }
317 if (auto Const = dyn_cast<SCEVConstant>(Expr))
318 if (Const->getValue()->isZero()) {
319 DroppedFirstDim = true;
320 continue;
321 }
322 Subscripts.push_back(Expr);
323 continue;
324 }
325
326 auto ArrayTy = dyn_cast<ArrayType>(Ty);
327 if (!ArrayTy) {
328 Subscripts.clear();
329 Sizes.clear();
330 break;
331 }
332
333 Subscripts.push_back(Expr);
334 if (!(DroppedFirstDim && i == 2))
335 Sizes.push_back(ArrayTy->getNumElements());
336
337 Ty = ArrayTy->getElementType();
338 }
339
340 return std::make_tuple(Subscripts, Sizes);
341}
342
Tobias Grosser75805372011-04-29 06:27:02 +0000343MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000344 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000345 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000346 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000347}
348
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000349const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
350 isl_id *ArrayId = getArrayId();
351 void *User = isl_id_get_user(ArrayId);
352 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
353 isl_id_free(ArrayId);
354 return SAI;
355}
356
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000357__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000358 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
359}
360
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000361__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
362 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000363 isl_map *Schedule, *ScheduledAccRel;
364 isl_union_set *UDomain;
365
366 UDomain = isl_union_set_from_set(getStatement()->getDomain());
367 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
368 Schedule = isl_map_from_union_map(USchedule);
369 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
370 return isl_pw_multi_aff_from_map(ScheduledAccRel);
371}
372
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000373__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000374 return isl_map_copy(AccessRelation);
375}
376
Johannes Doerferta99130f2014-10-13 12:58:03 +0000377std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000378 return stringFromIslObj(AccessRelation);
379}
380
Johannes Doerferta99130f2014-10-13 12:58:03 +0000381__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000382 return isl_map_get_space(AccessRelation);
383}
384
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000385__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000386 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000387}
388
Tobias Grosser6f730082015-09-05 07:46:47 +0000389std::string MemoryAccess::getNewAccessRelationStr() const {
390 return stringFromIslObj(NewAccessRelation);
391}
392
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000393__isl_give isl_basic_map *
394MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000395 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000396 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000397
Tobias Grosser084d8f72012-05-29 09:29:44 +0000398 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000399 isl_basic_set_universe(Statement->getDomainSpace()),
400 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000401}
402
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000403// Formalize no out-of-bound access assumption
404//
405// When delinearizing array accesses we optimistically assume that the
406// delinearized accesses do not access out of bound locations (the subscript
407// expression of each array evaluates for each statement instance that is
408// executed to a value that is larger than zero and strictly smaller than the
409// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000410// dimension for which we do not need to assume any upper bound. At this point
411// we formalize this assumption to ensure that at code generation time the
412// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000413//
414// To find the set of constraints necessary to avoid out of bound accesses, we
415// first build the set of data locations that are not within array bounds. We
416// then apply the reverse access relation to obtain the set of iterations that
417// may contain invalid accesses and reduce this set of iterations to the ones
418// that are actually executed by intersecting them with the domain of the
419// statement. If we now project out all loop dimensions, we obtain a set of
420// parameters that may cause statement instances to be executed that may
421// possibly yield out of bound memory accesses. The complement of these
422// constraints is the set of constraints that needs to be assumed to ensure such
423// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000424void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000425 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000426 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Michael Krusee2bccbb2015-09-18 19:59:43 +0000427 for (int i = 1, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000428 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
429 isl_pw_aff *Var =
430 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
431 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
432
433 isl_set *DimOutside;
434
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000435 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Michael Krusee2bccbb2015-09-18 19:59:43 +0000436 isl_pw_aff *SizeE = Statement->getPwAff(Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000437
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000438 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
439 Statement->getNumIterators());
440 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
441 isl_space_dim(Space, isl_dim_set));
442 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
443 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000444
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000445 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000446
447 Outside = isl_set_union(Outside, DimOutside);
448 }
449
450 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
451 Outside = isl_set_intersect(Outside, Statement->getDomain());
452 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000453
454 // Remove divs to avoid the construction of overly complicated assumptions.
455 // Doing so increases the set of parameter combinations that are assumed to
456 // not appear. This is always save, but may make the resulting run-time check
457 // bail out more often than strictly necessary.
458 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000459 Outside = isl_set_complement(Outside);
460 Statement->getParent()->addAssumption(Outside);
461 isl_space_free(Space);
462}
463
Johannes Doerferte7044942015-02-24 11:58:30 +0000464void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
465 ScalarEvolution *SE = Statement->getParent()->getSE();
466
467 Value *Ptr = getPointerOperand(*getAccessInstruction());
468 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
469 return;
470
471 auto *PtrSCEV = SE->getSCEV(Ptr);
472 if (isa<SCEVCouldNotCompute>(PtrSCEV))
473 return;
474
475 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
476 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
477 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
478
479 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
480 if (Range.isFullSet())
481 return;
482
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000483 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000484 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000485 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
486 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
487
488 auto Min = LB.sdiv(APInt(BW, ElementSize));
489 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000490
491 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
492 AccessRange =
493 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
494 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
495}
496
Michael Krusee2bccbb2015-09-18 19:59:43 +0000497__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000498 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000499 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000500
501 for (int i = Size - 2; i >= 0; --i) {
502 isl_space *Space;
503 isl_map *MapOne, *MapTwo;
Michael Krusee2bccbb2015-09-18 19:59:43 +0000504 isl_pw_aff *DimSize = Statement->getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000505
506 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
507 isl_pw_aff_free(DimSize);
508 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
509
510 Space = isl_map_get_space(AccessRelation);
511 Space = isl_space_map_from_set(isl_space_range(Space));
512 Space = isl_space_align_params(Space, SpaceSize);
513
514 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
515 isl_id_free(ParamId);
516
517 MapOne = isl_map_universe(isl_space_copy(Space));
518 for (int j = 0; j < Size; ++j)
519 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
520 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
521
522 MapTwo = isl_map_universe(isl_space_copy(Space));
523 for (int j = 0; j < Size; ++j)
524 if (j < i || j > i + 1)
525 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
526
527 isl_local_space *LS = isl_local_space_from_space(Space);
528 isl_constraint *C;
529 C = isl_equality_alloc(isl_local_space_copy(LS));
530 C = isl_constraint_set_constant_si(C, -1);
531 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
532 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
533 MapTwo = isl_map_add_constraint(MapTwo, C);
534 C = isl_equality_alloc(LS);
535 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
536 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
537 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
538 MapTwo = isl_map_add_constraint(MapTwo, C);
539 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
540
541 MapOne = isl_map_union(MapOne, MapTwo);
542 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
543 }
544 return AccessRelation;
545}
546
Michael Krusee2bccbb2015-09-18 19:59:43 +0000547void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
548 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000549
Michael Krusee2bccbb2015-09-18 19:59:43 +0000550 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000551 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000552
Michael Krusee2bccbb2015-09-18 19:59:43 +0000553 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000554 // We overapproximate non-affine accesses with a possible access to the
555 // whole array. For read accesses it does not make a difference, if an
556 // access must or may happen. However, for write accesses it is important to
557 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000558 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000559 AccessRelation =
560 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000561
Michael Krusee2bccbb2015-09-18 19:59:43 +0000562 computeBoundsOnAccessRelation(getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000563 return;
564 }
565
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000566 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000567 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000568
Michael Krusee2bccbb2015-09-18 19:59:43 +0000569 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
570 isl_pw_aff *Affine = Statement->getPwAff(Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000571
Sebastian Pop422e33f2014-06-03 18:16:31 +0000572 if (Size == 1) {
573 // For the non delinearized arrays, divide the access function of the last
574 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000575 //
576 // A stride one array access in C expressed as A[i] is expressed in
577 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
578 // two subsequent values of 'i' index two values that are stored next to
579 // each other in memory. By this division we make this characteristic
580 // obvious again.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000581 isl_val *v = isl_val_int_from_si(Ctx, getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000582 Affine = isl_pw_aff_scale_down_val(Affine, v);
583 }
584
585 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
586
Tobias Grosser79baa212014-04-10 08:38:02 +0000587 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000588 }
589
Michael Krusee2bccbb2015-09-18 19:59:43 +0000590 if (Sizes.size() > 1 && !isa<SCEVConstant>(Sizes[0]))
591 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000592
Tobias Grosser79baa212014-04-10 08:38:02 +0000593 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000594 AccessRelation = isl_map_set_tuple_id(
595 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000596 AccessRelation =
597 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
598
Michael Krusee2bccbb2015-09-18 19:59:43 +0000599 assumeNoOutOfBound();
Tobias Grosseraa660a92015-03-30 00:07:50 +0000600 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000601 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000602}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000603
Michael Krusee2bccbb2015-09-18 19:59:43 +0000604MemoryAccess::MemoryAccess(Instruction *AccessInst, __isl_take isl_id *Id,
605 AccessType Type, Value *BaseAddress,
Michael Kruse2d0ece92015-09-24 11:41:21 +0000606 unsigned ElemBytes, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000607 ArrayRef<const SCEV *> Subscripts,
608 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Michael Kruse8d0b7342015-09-25 21:21:00 +0000609 AccessOrigin Origin, StringRef BaseName)
610 : Id(Id), Origin(Origin), AccType(Type), RedType(RT_NONE),
611 Statement(nullptr), BaseAddr(BaseAddress), BaseName(BaseName),
612 ElemBytes(ElemBytes), Sizes(Sizes.begin(), Sizes.end()),
613 AccessInstruction(AccessInst), AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000614 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
615 NewAccessRelation(nullptr) {}
616
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000617void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000618 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000619 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000620}
621
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000622const std::string MemoryAccess::getReductionOperatorStr() const {
623 return MemoryAccess::getReductionOperatorStr(getReductionType());
624}
625
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000626__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
627
Johannes Doerfertf6183392014-07-01 20:52:51 +0000628raw_ostream &polly::operator<<(raw_ostream &OS,
629 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000630 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000631 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000632 else
633 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000634 return OS;
635}
636
Tobias Grosser75805372011-04-29 06:27:02 +0000637void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000638 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000639 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000640 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000641 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000642 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000643 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000644 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000645 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000646 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000647 break;
648 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000649 OS << "[Reduction Type: " << getReductionType() << "] ";
Michael Kruse8d0b7342015-09-25 21:21:00 +0000650 OS << "[Scalar: " << isImplicit() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000651 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000652 if (hasNewAccessRelation())
653 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000654}
655
Tobias Grosser74394f02013-01-14 22:40:23 +0000656void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000657
658// Create a map in the size of the provided set domain, that maps from the
659// one element of the provided set domain to another element of the provided
660// set domain.
661// The mapping is limited to all points that are equal in all but the last
662// dimension and for which the last dimension of the input is strict smaller
663// than the last dimension of the output.
664//
665// getEqualAndLarger(set[i0, i1, ..., iX]):
666//
667// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
668// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
669//
Tobias Grosserf5338802011-10-06 00:03:35 +0000670static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000671 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000672 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000673 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000674
675 // Set all but the last dimension to be equal for the input and output
676 //
677 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
678 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000679 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000680 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000681
682 // Set the last dimension of the input to be strict smaller than the
683 // last dimension of the output.
684 //
685 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000686 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
687 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000688 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000689}
690
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000691__isl_give isl_set *
692MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000693 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000694 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000695 isl_space *Space = isl_space_range(isl_map_get_space(S));
696 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000697
Sebastian Popa00a0292012-12-18 07:46:06 +0000698 S = isl_map_reverse(S);
699 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000700
Sebastian Popa00a0292012-12-18 07:46:06 +0000701 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
702 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
703 NextScatt = isl_map_apply_domain(NextScatt, S);
704 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000705
Sebastian Popa00a0292012-12-18 07:46:06 +0000706 isl_set *Deltas = isl_map_deltas(NextScatt);
707 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000708}
709
Sebastian Popa00a0292012-12-18 07:46:06 +0000710bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000711 int StrideWidth) const {
712 isl_set *Stride, *StrideX;
713 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000714
Sebastian Popa00a0292012-12-18 07:46:06 +0000715 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000716 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000717 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
718 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
719 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
720 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000721 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000722
Tobias Grosser28dd4862012-01-24 16:42:16 +0000723 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000724 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000725
Tobias Grosser28dd4862012-01-24 16:42:16 +0000726 return IsStrideX;
727}
728
Sebastian Popa00a0292012-12-18 07:46:06 +0000729bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
730 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000731}
732
Sebastian Popa00a0292012-12-18 07:46:06 +0000733bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
734 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000735}
736
Tobias Grosser166c4222015-09-05 07:46:40 +0000737void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
738 isl_map_free(NewAccessRelation);
739 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000740}
Tobias Grosser75805372011-04-29 06:27:02 +0000741
742//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000743
Tobias Grosser808cd692015-07-14 09:33:13 +0000744isl_map *ScopStmt::getSchedule() const {
745 isl_set *Domain = getDomain();
746 if (isl_set_is_empty(Domain)) {
747 isl_set_free(Domain);
748 return isl_map_from_aff(
749 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
750 }
751 auto *Schedule = getParent()->getSchedule();
752 Schedule = isl_union_map_intersect_domain(
753 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
754 if (isl_union_map_is_empty(Schedule)) {
755 isl_set_free(Domain);
756 isl_union_map_free(Schedule);
757 return isl_map_from_aff(
758 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
759 }
760 auto *M = isl_map_from_union_map(Schedule);
761 M = isl_map_coalesce(M);
762 M = isl_map_gist_domain(M, Domain);
763 M = isl_map_coalesce(M);
764 return M;
765}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000766
Johannes Doerfert574182d2015-08-12 10:19:50 +0000767__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000768 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
769 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000770}
771
Tobias Grosser37eb4222014-02-20 21:43:54 +0000772void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
773 assert(isl_set_is_subset(NewDomain, Domain) &&
774 "New domain is not a subset of old domain!");
775 isl_set_free(Domain);
776 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000777}
778
Michael Kruse9d080092015-09-11 21:41:48 +0000779void ScopStmt::buildAccesses(BasicBlock *Block, bool isApproximated) {
780 AccFuncSetType *AFS = Parent.getAccessFunctions(Block);
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000781 if (!AFS)
782 return;
783
Michael Krusee2bccbb2015-09-18 19:59:43 +0000784 for (auto &Access : *AFS) {
785 Instruction *AccessInst = Access.getAccessInstruction();
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000786 Type *ElementType = Access.getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000787
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000788 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Michael Krusee2bccbb2015-09-18 19:59:43 +0000789 Access.getBaseAddr(), ElementType, Access.Sizes, Access.isPHI());
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000790
Michael Krusee2bccbb2015-09-18 19:59:43 +0000791 if (isApproximated && Access.isMustWrite())
792 Access.AccType = MemoryAccess::MAY_WRITE;
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000793
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000794 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
795 if (!MAL)
796 MAL = new MemoryAccessList();
Michael Krusee2bccbb2015-09-18 19:59:43 +0000797 Access.setStatement(this);
798 Access.buildAccessRelation(SAI);
799 MAL->emplace_front(&Access);
800 MemAccs.push_back(MAL->front());
Tobias Grosser75805372011-04-29 06:27:02 +0000801 }
802}
803
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000804void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000805 for (MemoryAccess *MA : *this)
806 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000807
808 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000809}
810
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000811/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
812static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
813 void *User) {
814 isl_set **BoundedParts = static_cast<isl_set **>(User);
815 if (isl_basic_set_is_bounded(BSet))
816 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
817 else
818 isl_basic_set_free(BSet);
819 return isl_stat_ok;
820}
821
822/// @brief Return the bounded parts of @p S.
823static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
824 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
825 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
826 isl_set_free(S);
827 return BoundedParts;
828}
829
830/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
831///
832/// @returns A separation of @p S into first an unbounded then a bounded subset,
833/// both with regards to the dimension @p Dim.
834static std::pair<__isl_give isl_set *, __isl_give isl_set *>
835partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
836
837 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000838 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000839
840 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000841 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000842
843 // Remove dimensions that are greater than Dim as they are not interesting.
844 assert(NumDimsS >= Dim + 1);
845 OnlyDimS =
846 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
847
848 // Create artificial parametric upper bounds for dimensions smaller than Dim
849 // as we are not interested in them.
850 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
851 for (unsigned u = 0; u < Dim; u++) {
852 isl_constraint *C = isl_inequality_alloc(
853 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
854 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
855 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
856 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
857 }
858
859 // Collect all bounded parts of OnlyDimS.
860 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
861
862 // Create the dimensions greater than Dim again.
863 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
864 NumDimsS - Dim - 1);
865
866 // Remove the artificial upper bound parameters again.
867 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
868
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000869 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000870 return std::make_pair(UnboundedParts, BoundedParts);
871}
872
Johannes Doerfert96425c22015-08-30 21:13:53 +0000873static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
874 isl_pw_aff *L, isl_pw_aff *R) {
875 switch (Pred) {
876 case ICmpInst::ICMP_EQ:
877 return isl_pw_aff_eq_set(L, R);
878 case ICmpInst::ICMP_NE:
879 return isl_pw_aff_ne_set(L, R);
880 case ICmpInst::ICMP_SLT:
881 return isl_pw_aff_lt_set(L, R);
882 case ICmpInst::ICMP_SLE:
883 return isl_pw_aff_le_set(L, R);
884 case ICmpInst::ICMP_SGT:
885 return isl_pw_aff_gt_set(L, R);
886 case ICmpInst::ICMP_SGE:
887 return isl_pw_aff_ge_set(L, R);
888 case ICmpInst::ICMP_ULT:
889 return isl_pw_aff_lt_set(L, R);
890 case ICmpInst::ICMP_UGT:
891 return isl_pw_aff_gt_set(L, R);
892 case ICmpInst::ICMP_ULE:
893 return isl_pw_aff_le_set(L, R);
894 case ICmpInst::ICMP_UGE:
895 return isl_pw_aff_ge_set(L, R);
896 default:
897 llvm_unreachable("Non integer predicate not supported");
898 }
899}
900
901/// @brief Build the conditions sets for the branch @p BI in the @p Domain.
902///
903/// This will fill @p ConditionSets with the conditions under which control
904/// will be moved from @p BI to its successors. Hence, @p ConditionSets will
905/// have as many elements as @p BI has successors.
906static void
907buildConditionSets(Scop &S, BranchInst *BI, Loop *L, __isl_keep isl_set *Domain,
908 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
909
910 if (BI->isUnconditional()) {
911 ConditionSets.push_back(isl_set_copy(Domain));
912 return;
913 }
914
915 Value *Condition = BI->getCondition();
916
917 isl_set *ConsequenceCondSet = nullptr;
918 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
919 if (CCond->isZero())
920 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
921 else
922 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
923 } else {
924 auto *ICond = dyn_cast<ICmpInst>(Condition);
925 assert(ICond &&
926 "Condition of exiting branch was neither constant nor ICmp!");
927
928 ScalarEvolution &SE = *S.getSE();
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000929 BasicBlock *BB = BI->getParent();
Johannes Doerfert96425c22015-08-30 21:13:53 +0000930 isl_pw_aff *LHS, *RHS;
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000931 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
932 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
Johannes Doerfert96425c22015-08-30 21:13:53 +0000933 ConsequenceCondSet = buildConditionSet(ICond->getPredicate(), LHS, RHS);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000934
935 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
936 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
937 ConsequenceCondSet =
938 isl_set_set_dim_id(ConsequenceCondSet, isl_dim_set, u, DimId);
939 }
Johannes Doerfert96425c22015-08-30 21:13:53 +0000940 }
941
942 assert(ConsequenceCondSet);
943 isl_set *AlternativeCondSet =
944 isl_set_complement(isl_set_copy(ConsequenceCondSet));
945
946 ConditionSets.push_back(isl_set_coalesce(
947 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
948 ConditionSets.push_back(isl_set_coalesce(
949 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
950}
951
Johannes Doerfert32ae76e2015-09-10 13:12:02 +0000952void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000953 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000954
Tobias Grosser084d8f72012-05-29 09:29:44 +0000955 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
956
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000957 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +0000958 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +0000959}
960
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000961void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000962 isl_ctx *Ctx = Parent.getIslCtx();
963 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
964 Type *Ty = GEP->getPointerOperandType();
965 ScalarEvolution &SE = *Parent.getSE();
966
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000967 std::vector<const SCEV *> Subscripts;
968 std::vector<int> Sizes;
969
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000970 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000971
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000972 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000973 Ty = PtrTy->getElementType();
974 }
975
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000976 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000977
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000978 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000979
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000980 for (size_t i = 0; i < Sizes.size(); i++) {
981 auto Expr = Subscripts[i + IndexOffset];
982 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000983
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000984 if (!isAffineExpr(&Parent.getRegion(), Expr, SE))
985 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000986
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000987 isl_pw_aff *AccessOffset = getPwAff(Expr);
988 AccessOffset =
989 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000990
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000991 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
992 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000993
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000994 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
995 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
996 OutOfBound = isl_set_params(OutOfBound);
997 isl_set *InBound = isl_set_complement(OutOfBound);
998 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000999
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001000 // A => B == !A or B
1001 isl_set *InBoundIfExecuted =
1002 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001003
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001004 Parent.addAssumption(InBoundIfExecuted);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001005 }
1006
1007 isl_local_space_free(LSpace);
1008}
1009
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001010void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1011 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001012 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1013 deriveAssumptionsFromGEP(GEP);
1014}
1015
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001016void ScopStmt::collectSurroundingLoops() {
1017 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1018 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1019 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1020 isl_id_free(DimId);
1021 }
1022}
1023
Michael Kruse9d080092015-09-11 21:41:48 +00001024ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001025 : Parent(parent), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001026
Tobias Grosser16c44032015-07-09 07:31:45 +00001027 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001028
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001029 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001030 collectSurroundingLoops();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001031
1032 BasicBlock *EntryBB = R.getEntry();
1033 for (BasicBlock *Block : R.blocks()) {
Michael Kruse9d080092015-09-11 21:41:48 +00001034 buildAccesses(Block, Block != EntryBB);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001035 deriveAssumptions(Block);
1036 }
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001037 if (DetectReductions)
1038 checkForReductions();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001039}
1040
Michael Kruse9d080092015-09-11 21:41:48 +00001041ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001042 : Parent(parent), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001043
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001044 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +00001045
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001046 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001047 collectSurroundingLoops();
Michael Kruse9d080092015-09-11 21:41:48 +00001048 buildAccesses(BB);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001049 deriveAssumptions(BB);
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001050 if (DetectReductions)
1051 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001052}
1053
Johannes Doerferte58a0122014-06-27 20:31:28 +00001054/// @brief Collect loads which might form a reduction chain with @p StoreMA
1055///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001056/// Check if the stored value for @p StoreMA is a binary operator with one or
1057/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001058/// used only once (by @p StoreMA) and its load operands are also used only
1059/// once, we have found a possible reduction chain. It starts at an operand
1060/// load and includes the binary operator and @p StoreMA.
1061///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001062/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001063/// escape this block or into any other store except @p StoreMA.
1064void ScopStmt::collectCandiateReductionLoads(
1065 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1066 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1067 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001068 return;
1069
1070 // Skip if there is not one binary operator between the load and the store
1071 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001072 if (!BinOp)
1073 return;
1074
1075 // Skip if the binary operators has multiple uses
1076 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001077 return;
1078
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001079 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001080 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1081 return;
1082
Johannes Doerfert9890a052014-07-01 00:32:29 +00001083 // Skip if the binary operator is outside the current SCoP
1084 if (BinOp->getParent() != Store->getParent())
1085 return;
1086
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001087 // Skip if it is a multiplicative reduction and we disabled them
1088 if (DisableMultiplicativeReductions &&
1089 (BinOp->getOpcode() == Instruction::Mul ||
1090 BinOp->getOpcode() == Instruction::FMul))
1091 return;
1092
Johannes Doerferte58a0122014-06-27 20:31:28 +00001093 // Check the binary operator operands for a candidate load
1094 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1095 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1096 if (!PossibleLoad0 && !PossibleLoad1)
1097 return;
1098
1099 // A load is only a candidate if it cannot escape (thus has only this use)
1100 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001101 if (PossibleLoad0->getParent() == Store->getParent())
1102 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001103 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001104 if (PossibleLoad1->getParent() == Store->getParent())
1105 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001106}
1107
1108/// @brief Check for reductions in this ScopStmt
1109///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001110/// Iterate over all store memory accesses and check for valid binary reduction
1111/// like chains. For all candidates we check if they have the same base address
1112/// and there are no other accesses which overlap with them. The base address
1113/// check rules out impossible reductions candidates early. The overlap check,
1114/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001115/// guarantees that none of the intermediate results will escape during
1116/// execution of the loop nest. We basically check here that no other memory
1117/// access can access the same memory as the potential reduction.
1118void ScopStmt::checkForReductions() {
1119 SmallVector<MemoryAccess *, 2> Loads;
1120 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1121
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001122 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001123 // stores and collecting possible reduction loads.
1124 for (MemoryAccess *StoreMA : MemAccs) {
1125 if (StoreMA->isRead())
1126 continue;
1127
1128 Loads.clear();
1129 collectCandiateReductionLoads(StoreMA, Loads);
1130 for (MemoryAccess *LoadMA : Loads)
1131 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1132 }
1133
1134 // Then check each possible candidate pair.
1135 for (const auto &CandidatePair : Candidates) {
1136 bool Valid = true;
1137 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1138 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1139
1140 // Skip those with obviously unequal base addresses.
1141 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1142 isl_map_free(LoadAccs);
1143 isl_map_free(StoreAccs);
1144 continue;
1145 }
1146
1147 // And check if the remaining for overlap with other memory accesses.
1148 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1149 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1150 isl_set *AllAccs = isl_map_range(AllAccsRel);
1151
1152 for (MemoryAccess *MA : MemAccs) {
1153 if (MA == CandidatePair.first || MA == CandidatePair.second)
1154 continue;
1155
1156 isl_map *AccRel =
1157 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1158 isl_set *Accs = isl_map_range(AccRel);
1159
1160 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1161 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1162 Valid = Valid && isl_set_is_empty(OverlapAccs);
1163 isl_set_free(OverlapAccs);
1164 }
1165 }
1166
1167 isl_set_free(AllAccs);
1168 if (!Valid)
1169 continue;
1170
Johannes Doerfertf6183392014-07-01 20:52:51 +00001171 const LoadInst *Load =
1172 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1173 MemoryAccess::ReductionType RT =
1174 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1175
Johannes Doerferte58a0122014-06-27 20:31:28 +00001176 // If no overlapping access was found we mark the load and store as
1177 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001178 CandidatePair.first->markAsReductionLike(RT);
1179 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001180 }
Tobias Grosser75805372011-04-29 06:27:02 +00001181}
1182
Tobias Grosser74394f02013-01-14 22:40:23 +00001183std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001184
Tobias Grosser54839312015-04-21 11:37:25 +00001185std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001186 auto *S = getSchedule();
1187 auto Str = stringFromIslObj(S);
1188 isl_map_free(S);
1189 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001190}
1191
Tobias Grosser74394f02013-01-14 22:40:23 +00001192unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001193
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001194unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001195
Tobias Grosser75805372011-04-29 06:27:02 +00001196const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1197
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001198const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001199 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001200}
1201
Tobias Grosser74394f02013-01-14 22:40:23 +00001202isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001203
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001204__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001205
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001206__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001207 return isl_set_get_space(Domain);
1208}
1209
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001210__isl_give isl_id *ScopStmt::getDomainId() const {
1211 return isl_set_get_tuple_id(Domain);
1212}
Tobias Grossercd95b772012-08-30 11:49:38 +00001213
Tobias Grosser75805372011-04-29 06:27:02 +00001214ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001215 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001216 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001217}
1218
1219void ScopStmt::print(raw_ostream &OS) const {
1220 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001221 OS.indent(12) << "Domain :=\n";
1222
1223 if (Domain) {
1224 OS.indent(16) << getDomainStr() << ";\n";
1225 } else
1226 OS.indent(16) << "n/a\n";
1227
Tobias Grosser54839312015-04-21 11:37:25 +00001228 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001229
1230 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001231 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001232 } else
1233 OS.indent(16) << "n/a\n";
1234
Tobias Grosser083d3d32014-06-28 08:59:45 +00001235 for (MemoryAccess *Access : MemAccs)
1236 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001237}
1238
1239void ScopStmt::dump() const { print(dbgs()); }
1240
1241//===----------------------------------------------------------------------===//
1242/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001243
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001244void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001245 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1246 isl_set_free(Context);
1247 Context = NewContext;
1248}
1249
Tobias Grosserabfbe632013-02-05 12:09:06 +00001250void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001251 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001252 Parameter = extractConstantFactor(Parameter, *SE).second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001253 if (ParameterIds.find(Parameter) != ParameterIds.end())
1254 continue;
1255
1256 int dimension = Parameters.size();
1257
1258 Parameters.push_back(Parameter);
1259 ParameterIds[Parameter] = dimension;
1260 }
1261}
1262
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001263__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1264 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001265
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001266 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001267 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001268
Tobias Grosser8f99c162011-11-15 11:38:55 +00001269 std::string ParameterName;
1270
1271 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1272 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001273 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001274 }
1275
1276 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001277 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001278
Tobias Grosser20532b82014-04-11 17:56:49 +00001279 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1280 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001281}
Tobias Grosser75805372011-04-29 06:27:02 +00001282
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001283isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1284 isl_set *DomainContext = isl_union_set_params(getDomains());
1285 return isl_set_intersect_params(C, DomainContext);
1286}
1287
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001288void Scop::buildBoundaryContext() {
1289 BoundaryContext = Affinator.getWrappingContext();
1290 BoundaryContext = isl_set_complement(BoundaryContext);
1291 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
1292}
1293
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001294void Scop::addUserContext() {
1295 if (UserContextStr.empty())
1296 return;
1297
1298 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1299 isl_space *Space = getParamSpace();
1300 if (isl_space_dim(Space, isl_dim_param) !=
1301 isl_set_dim(UserContext, isl_dim_param)) {
1302 auto SpaceStr = isl_space_to_str(Space);
1303 errs() << "Error: the context provided in -polly-context has not the same "
1304 << "number of dimensions than the computed context. Due to this "
1305 << "mismatch, the -polly-context option is ignored. Please provide "
1306 << "the context in the parameter space: " << SpaceStr << ".\n";
1307 free(SpaceStr);
1308 isl_set_free(UserContext);
1309 isl_space_free(Space);
1310 return;
1311 }
1312
1313 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1314 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1315 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1316
1317 if (strcmp(NameContext, NameUserContext) != 0) {
1318 auto SpaceStr = isl_space_to_str(Space);
1319 errs() << "Error: the name of dimension " << i
1320 << " provided in -polly-context "
1321 << "is '" << NameUserContext << "', but the name in the computed "
1322 << "context is '" << NameContext
1323 << "'. Due to this name mismatch, "
1324 << "the -polly-context option is ignored. Please provide "
1325 << "the context in the parameter space: " << SpaceStr << ".\n";
1326 free(SpaceStr);
1327 isl_set_free(UserContext);
1328 isl_space_free(Space);
1329 return;
1330 }
1331
1332 UserContext =
1333 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1334 isl_space_get_dim_id(Space, isl_dim_param, i));
1335 }
1336
1337 Context = isl_set_intersect(Context, UserContext);
1338 isl_space_free(Space);
1339}
1340
Tobias Grosser6be480c2011-11-08 15:41:13 +00001341void Scop::buildContext() {
1342 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001343 Context = isl_set_universe(isl_space_copy(Space));
1344 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001345}
1346
Tobias Grosser18daaca2012-05-22 10:47:27 +00001347void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001348 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001349 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001350
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001351 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001352
Johannes Doerferte7044942015-02-24 11:58:30 +00001353 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001354 }
1355}
1356
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001357void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001358 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001359 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001360
Tobias Grosser083d3d32014-06-28 08:59:45 +00001361 for (const auto &ParamID : ParameterIds) {
1362 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001363 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001364 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001365 }
1366
1367 // Align the parameters of all data structures to the model.
1368 Context = isl_set_align_params(Context, Space);
1369
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001370 for (ScopStmt &Stmt : *this)
1371 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001372}
1373
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001374static __isl_give isl_set *
1375simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1376 const Scop &S) {
1377 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1378 AssumptionContext = isl_set_gist_params(AssumptionContext, DomainParameters);
1379 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1380 return AssumptionContext;
1381}
1382
1383void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001384 // The parameter constraints of the iteration domains give us a set of
1385 // constraints that need to hold for all cases where at least a single
1386 // statement iteration is executed in the whole scop. We now simplify the
1387 // assumed context under the assumption that such constraints hold and at
1388 // least a single statement iteration is executed. For cases where no
1389 // statement instances are executed, the assumptions we have taken about
1390 // the executed code do not matter and can be changed.
1391 //
1392 // WARNING: This only holds if the assumptions we have taken do not reduce
1393 // the set of statement instances that are executed. Otherwise we
1394 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001395 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001396 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001397 // performed. In such a case, modifying the run-time conditions and
1398 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001399 // to not be executed.
1400 //
1401 // Example:
1402 //
1403 // When delinearizing the following code:
1404 //
1405 // for (long i = 0; i < 100; i++)
1406 // for (long j = 0; j < m; j++)
1407 // A[i+p][j] = 1.0;
1408 //
1409 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001410 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001411 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001412 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1413 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001414}
1415
Johannes Doerfertb164c792014-09-18 11:17:17 +00001416/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001417static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001418 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1419 isl_pw_multi_aff *MinPMA, *MaxPMA;
1420 isl_pw_aff *LastDimAff;
1421 isl_aff *OneAff;
1422 unsigned Pos;
1423
Johannes Doerfert9143d672014-09-27 11:02:39 +00001424 // Restrict the number of parameters involved in the access as the lexmin/
1425 // lexmax computation will take too long if this number is high.
1426 //
1427 // Experiments with a simple test case using an i7 4800MQ:
1428 //
1429 // #Parameters involved | Time (in sec)
1430 // 6 | 0.01
1431 // 7 | 0.04
1432 // 8 | 0.12
1433 // 9 | 0.40
1434 // 10 | 1.54
1435 // 11 | 6.78
1436 // 12 | 30.38
1437 //
1438 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1439 unsigned InvolvedParams = 0;
1440 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1441 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1442 InvolvedParams++;
1443
1444 if (InvolvedParams > RunTimeChecksMaxParameters) {
1445 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001446 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001447 }
1448 }
1449
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001450 Set = isl_set_remove_divs(Set);
1451
Johannes Doerfertb164c792014-09-18 11:17:17 +00001452 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1453 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1454
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001455 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1456 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1457
Johannes Doerfertb164c792014-09-18 11:17:17 +00001458 // Adjust the last dimension of the maximal access by one as we want to
1459 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1460 // we test during code generation might now point after the end of the
1461 // allocated array but we will never dereference it anyway.
1462 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1463 "Assumed at least one output dimension");
1464 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1465 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1466 OneAff = isl_aff_zero_on_domain(
1467 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1468 OneAff = isl_aff_add_constant_si(OneAff, 1);
1469 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1470 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1471
1472 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1473
1474 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001475 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001476}
1477
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001478static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1479 isl_set *Domain = MA->getStatement()->getDomain();
1480 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1481 return isl_set_reset_tuple_id(Domain);
1482}
1483
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001484/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1485static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001486 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001487 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001488
1489 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1490 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001491 Locations = isl_union_set_coalesce(Locations);
1492 Locations = isl_union_set_detect_equalities(Locations);
1493 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001494 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001495 isl_union_set_free(Locations);
1496 return Valid;
1497}
1498
Johannes Doerfert96425c22015-08-30 21:13:53 +00001499/// @brief Helper to treat non-affine regions and basic blocks the same.
1500///
1501///{
1502
1503/// @brief Return the block that is the representing block for @p RN.
1504static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1505 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1506 : RN->getNodeAs<BasicBlock>();
1507}
1508
1509/// @brief Return the @p idx'th block that is executed after @p RN.
1510static inline BasicBlock *getRegionNodeSuccessor(RegionNode *RN, BranchInst *BI,
1511 unsigned idx) {
1512 if (RN->isSubRegion()) {
1513 assert(idx == 0);
1514 return RN->getNodeAs<Region>()->getExit();
1515 }
1516 return BI->getSuccessor(idx);
1517}
1518
1519/// @brief Return the smallest loop surrounding @p RN.
1520static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1521 if (!RN->isSubRegion())
1522 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1523
1524 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1525 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1526 while (L && NonAffineSubRegion->contains(L))
1527 L = L->getParentLoop();
1528 return L;
1529}
1530
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001531static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1532 if (!RN->isSubRegion())
1533 return 1;
1534
1535 unsigned NumBlocks = 0;
1536 Region *R = RN->getNodeAs<Region>();
1537 for (auto BB : R->blocks()) {
1538 (void)BB;
1539 NumBlocks++;
1540 }
1541 return NumBlocks;
1542}
1543
Johannes Doerfert96425c22015-08-30 21:13:53 +00001544///}
1545
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001546static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1547 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001548 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001549 isl_id *DimId =
1550 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
1551 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
1552}
1553
Johannes Doerfert96425c22015-08-30 21:13:53 +00001554isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1555 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1556 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00001557 return getDomainConditions(BB);
1558}
1559
1560isl_set *Scop::getDomainConditions(BasicBlock *BB) {
1561 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001562 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001563}
1564
1565void Scop::buildDomains(Region *R, LoopInfo &LI, ScopDetection &SD,
1566 DominatorTree &DT) {
1567
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001568 auto *EntryBB = R->getEntry();
1569 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
1570 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001571
1572 Loop *L = LI.getLoopFor(EntryBB);
1573 while (LD-- >= 0) {
1574 S = addDomainDimId(S, LD + 1, L);
1575 L = L->getParentLoop();
1576 }
1577
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001578 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001579
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00001580 if (SD.isNonAffineSubRegion(R, R))
1581 return;
1582
Johannes Doerfert96425c22015-08-30 21:13:53 +00001583 buildDomainsWithBranchConstraints(R, LI, SD, DT);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001584 propagateDomainConstraints(R, LI, SD, DT);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001585}
1586
1587void Scop::buildDomainsWithBranchConstraints(Region *R, LoopInfo &LI,
1588 ScopDetection &SD,
1589 DominatorTree &DT) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001590 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00001591
1592 // To create the domain for each block in R we iterate over all blocks and
1593 // subregions in R and propagate the conditions under which the current region
1594 // element is executed. To this end we iterate in reverse post order over R as
1595 // it ensures that we first visit all predecessors of a region node (either a
1596 // basic block or a subregion) before we visit the region node itself.
1597 // Initially, only the domain for the SCoP region entry block is set and from
1598 // there we propagate the current domain to all successors, however we add the
1599 // condition that the successor is actually executed next.
1600 // As we are only interested in non-loop carried constraints here we can
1601 // simply skip loop back edges.
1602
1603 ReversePostOrderTraversal<Region *> RTraversal(R);
1604 for (auto *RN : RTraversal) {
1605
1606 // Recurse for affine subregions but go on for basic blocks and non-affine
1607 // subregions.
1608 if (RN->isSubRegion()) {
1609 Region *SubRegion = RN->getNodeAs<Region>();
1610 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
1611 buildDomainsWithBranchConstraints(SubRegion, LI, SD, DT);
1612 continue;
1613 }
1614 }
1615
1616 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001617 TerminatorInst *TI = BB->getTerminator();
1618
1619 // Unreachable instructions do not have successors so we can skip them.
1620 if (isa<UnreachableInst>(TI)) {
1621 // Assume unreachables only in error blocks.
1622 assert(isErrorBlock(*BB));
1623 continue;
1624 }
1625
Johannes Doerfert96425c22015-08-30 21:13:53 +00001626 isl_set *Domain = DomainMap[BB];
1627 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
1628 assert(Domain && "Due to reverse post order traversal of the region all "
1629 "predecessor of the current region node should have been "
1630 "visited and a domain for this region node should have "
1631 "been set.");
1632
1633 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1634 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1635
1636 // Build the condition sets for the successor nodes of the current region
1637 // node. If it is a non-affine subregion we will always execute the single
1638 // exit node, hence the single entry node domain is the condition set. For
1639 // basic blocks we use the helper function buildConditionSets.
1640 SmallVector<isl_set *, 2> ConditionSets;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001641 BranchInst *BI = cast<BranchInst>(TI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001642 if (RN->isSubRegion())
1643 ConditionSets.push_back(isl_set_copy(Domain));
1644 else
1645 buildConditionSets(*this, BI, BBLoop, Domain, ConditionSets);
1646
1647 // Now iterate over the successors and set their initial domain based on
1648 // their condition set. We skip back edges here and have to be careful when
1649 // we leave a loop not to keep constraints over a dimension that doesn't
1650 // exist anymore.
1651 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
1652 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, BI, u);
1653 isl_set *CondSet = ConditionSets[u];
1654
1655 // Skip back edges.
1656 if (DT.dominates(SuccBB, BB)) {
1657 isl_set_free(CondSet);
1658 continue;
1659 }
1660
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001661 // Do not adjust the number of dimensions if we enter a boxed loop or are
1662 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001663 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001664 Region *SuccRegion = RI.getRegionFor(SuccBB);
1665 if (BBLoop != SuccBBLoop && !RN->isSubRegion() &&
1666 !(SD.isNonAffineSubRegion(SuccRegion, &getRegion()) &&
1667 SuccRegion->contains(SuccBBLoop))) {
1668
1669 // Check if the edge to SuccBB is a loop entry or exit edge. If so
1670 // adjust the dimensionality accordingly. Lastly, if we leave a loop
1671 // and enter a new one we need to drop the old constraints.
1672 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001673 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001674 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001675 CondSet = isl_set_project_out(CondSet, isl_dim_set,
1676 isl_set_n_dim(CondSet) - LoopDepthDiff,
1677 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001678 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001679 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001680 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001681 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001682 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001683 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001684 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
1685 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001686 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001687 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00001688 }
1689
1690 // Set the domain for the successor or merge it with an existing domain in
1691 // case there are multiple paths (without loop back edges) to the
1692 // successor block.
1693 isl_set *&SuccDomain = DomainMap[SuccBB];
1694 if (!SuccDomain)
1695 SuccDomain = CondSet;
1696 else
1697 SuccDomain = isl_set_union(SuccDomain, CondSet);
1698
1699 SuccDomain = isl_set_coalesce(SuccDomain);
1700 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : " << Domain
1701 << "\n");
1702 }
1703 }
1704}
1705
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001706/// @brief Return the domain for @p BB wrt @p DomainMap.
1707///
1708/// This helper function will lookup @p BB in @p DomainMap but also handle the
1709/// case where @p BB is contained in a non-affine subregion using the region
1710/// tree obtained by @p RI.
1711static __isl_give isl_set *
1712getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
1713 RegionInfo &RI) {
1714 auto DIt = DomainMap.find(BB);
1715 if (DIt != DomainMap.end())
1716 return isl_set_copy(DIt->getSecond());
1717
1718 Region *R = RI.getRegionFor(BB);
1719 while (R->getEntry() == BB)
1720 R = R->getParent();
1721 return getDomainForBlock(R->getEntry(), DomainMap, RI);
1722}
1723
Johannes Doerferte114dc02015-09-14 11:15:58 +00001724static bool containsErrorBlock(RegionNode *RN) {
1725 if (!RN->isSubRegion())
1726 return isErrorBlock(*RN->getNodeAs<BasicBlock>());
1727 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
1728 if (isErrorBlock(*BB))
1729 return true;
1730 return false;
1731}
1732
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001733void Scop::propagateDomainConstraints(Region *R, LoopInfo &LI,
1734 ScopDetection &SD, DominatorTree &DT) {
1735 // Iterate over the region R and propagate the domain constrains from the
1736 // predecessors to the current node. In contrast to the
1737 // buildDomainsWithBranchConstraints function, this one will pull the domain
1738 // information from the predecessors instead of pushing it to the successors.
1739 // Additionally, we assume the domains to be already present in the domain
1740 // map here. However, we iterate again in reverse post order so we know all
1741 // predecessors have been visited before a block or non-affine subregion is
1742 // visited.
1743
1744 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
1745 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
1746
1747 ReversePostOrderTraversal<Region *> RTraversal(R);
1748 for (auto *RN : RTraversal) {
1749
1750 // Recurse for affine subregions but go on for basic blocks and non-affine
1751 // subregions.
1752 if (RN->isSubRegion()) {
1753 Region *SubRegion = RN->getNodeAs<Region>();
1754 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
1755 propagateDomainConstraints(SubRegion, LI, SD, DT);
1756 continue;
1757 }
1758 }
1759
1760 BasicBlock *BB = getRegionNodeBasicBlock(RN);
1761 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1762 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1763
1764 isl_set *&Domain = DomainMap[BB];
1765 assert(Domain && "Due to reverse post order traversal of the region all "
1766 "predecessor of the current region node should have been "
1767 "visited and a domain for this region node should have "
1768 "been set.");
1769
1770 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
1771 for (auto *PredBB : predecessors(BB)) {
1772
1773 // Skip backedges
1774 if (DT.dominates(BB, PredBB))
1775 continue;
1776
1777 isl_set *PredBBDom = nullptr;
1778
1779 // Handle the SCoP entry block with its outside predecessors.
1780 if (!getRegion().contains(PredBB))
1781 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
1782
1783 if (!PredBBDom) {
1784 // Determine the loop depth of the predecessor and adjust its domain to
1785 // the domain of the current block. This can mean we have to:
1786 // o) Drop a dimension if this block is the exit of a loop, not the
1787 // header of a new loop and the predecessor was part of the loop.
1788 // o) Add an unconstrainted new dimension if this block is the header
1789 // of a loop and the predecessor is not part of it.
1790 // o) Drop the information about the innermost loop dimension when the
1791 // predecessor and the current block are surrounded by different
1792 // loops in the same depth.
1793 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
1794 Loop *PredBBLoop = LI.getLoopFor(PredBB);
1795 while (BoxedLoops.count(PredBBLoop))
1796 PredBBLoop = PredBBLoop->getParentLoop();
1797
1798 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001799 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001800 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001801 PredBBDom = isl_set_project_out(
1802 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
1803 LoopDepthDiff);
1804 else if (PredBBLoopDepth < BBLoopDepth) {
1805 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001806 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001807 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
1808 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001809 PredBBDom = isl_set_drop_constraints_involving_dims(
1810 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001811 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001812 }
1813
1814 PredDom = isl_set_union(PredDom, PredBBDom);
1815 }
1816
1817 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00001818 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001819
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001820 if (BBLoop && BBLoop->getHeader() == BB)
1821 addLoopBoundsToHeaderDomain(BBLoop, LI);
1822
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001823 // Add assumptions for error blocks.
Johannes Doerferte114dc02015-09-14 11:15:58 +00001824 if (containsErrorBlock(RN)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001825 IsOptimized = true;
1826 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
1827 addAssumption(isl_set_complement(DomPar));
1828 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001829 }
1830}
1831
1832/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
1833/// is incremented by one and all other dimensions are equal, e.g.,
1834/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
1835/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
1836static __isl_give isl_map *
1837createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
1838 auto *MapSpace = isl_space_map_from_set(SetSpace);
1839 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
1840 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
1841 if (u != Dim)
1842 NextIterationMap =
1843 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
1844 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
1845 C = isl_constraint_set_constant_si(C, 1);
1846 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
1847 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
1848 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
1849 return NextIterationMap;
1850}
1851
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001852void Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
1853 int LoopDepth = getRelativeLoopDepth(L);
1854 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001855
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001856 BasicBlock *HeaderBB = L->getHeader();
1857 assert(DomainMap.count(HeaderBB));
1858 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001859
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001860 isl_map *NextIterationMap =
1861 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001862
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001863 isl_set *UnionBackedgeCondition =
1864 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001865
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001866 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
1867 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001868
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001869 for (BasicBlock *LatchBB : LatchBlocks) {
1870 assert(DomainMap.count(LatchBB));
1871 isl_set *LatchBBDom = DomainMap[LatchBB];
1872 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001873
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001874 BranchInst *BI = cast<BranchInst>(LatchBB->getTerminator());
1875 if (BI->isUnconditional())
1876 BackedgeCondition = isl_set_copy(LatchBBDom);
1877 else {
1878 SmallVector<isl_set *, 2> ConditionSets;
1879 int idx = BI->getSuccessor(0) != HeaderBB;
1880 buildConditionSets(*this, BI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001881
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001882 // Free the non back edge condition set as we do not need it.
1883 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001884
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001885 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00001886 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001887
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001888 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
1889 assert(LatchLoopDepth >= LoopDepth);
1890 BackedgeCondition =
1891 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
1892 LatchLoopDepth - LoopDepth);
1893 UnionBackedgeCondition =
1894 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001895 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001896
1897 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
1898 for (int i = 0; i < LoopDepth; i++)
1899 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
1900
1901 isl_set *UnionBackedgeConditionComplement =
1902 isl_set_complement(UnionBackedgeCondition);
1903 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
1904 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
1905 UnionBackedgeConditionComplement =
1906 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
1907 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
1908 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
1909
1910 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
1911 HeaderBBDom = Parts.second;
1912
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00001913 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
1914 // the bounded assumptions to the context as they are already implied by the
1915 // <nsw> tag.
1916 if (Affinator.hasNSWAddRecForLoop(L)) {
1917 isl_set_free(Parts.first);
1918 return;
1919 }
1920
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001921 isl_set *UnboundedCtx = isl_set_params(Parts.first);
1922 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfert707a4062015-09-20 16:38:19 +00001923 addAssumption(BoundedCtx);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001924}
1925
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001926void Scop::buildAliasChecks(AliasAnalysis &AA) {
1927 if (!PollyUseRuntimeAliasChecks)
1928 return;
1929
1930 if (buildAliasGroups(AA))
1931 return;
1932
1933 // If a problem occurs while building the alias groups we need to delete
1934 // this SCoP and pretend it wasn't valid in the first place. To this end
1935 // we make the assumed context infeasible.
1936 addAssumption(isl_set_empty(getParamSpace()));
1937
1938 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
1939 << " could not be created as the number of parameters involved "
1940 "is too high. The SCoP will be "
1941 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
1942 "the maximal number of parameters but be advised that the "
1943 "compile time might increase exponentially.\n\n");
1944}
1945
Johannes Doerfert9143d672014-09-27 11:02:39 +00001946bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001947 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001948 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00001949 // for all memory accesses inside the SCoP.
1950 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001951 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00001952 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001953 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001954 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001955 // if their access domains intersect, otherwise they are in different
1956 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001957 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001958 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001959 // and maximal accesses to each array of a group in read only and non
1960 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00001961 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
1962
1963 AliasSetTracker AST(AA);
1964
1965 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00001966 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001967 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001968
1969 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001970 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001971 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
1972 isl_set_free(StmtDomain);
1973 if (StmtDomainEmpty)
1974 continue;
1975
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001976 for (MemoryAccess *MA : Stmt) {
Michael Kruse8d0b7342015-09-25 21:21:00 +00001977 if (MA->isImplicit())
Johannes Doerfertb164c792014-09-18 11:17:17 +00001978 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00001979 if (!MA->isRead())
1980 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001981 Instruction *Acc = MA->getAccessInstruction();
1982 PtrToAcc[getPointerOperand(*Acc)] = MA;
1983 AST.add(Acc);
1984 }
1985 }
1986
1987 SmallVector<AliasGroupTy, 4> AliasGroups;
1988 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00001989 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00001990 continue;
1991 AliasGroupTy AG;
1992 for (auto PR : AS)
1993 AG.push_back(PtrToAcc[PR.getValue()]);
1994 assert(AG.size() > 1 &&
1995 "Alias groups should contain at least two accesses");
1996 AliasGroups.push_back(std::move(AG));
1997 }
1998
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001999 // Split the alias groups based on their domain.
2000 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2001 AliasGroupTy NewAG;
2002 AliasGroupTy &AG = AliasGroups[u];
2003 AliasGroupTy::iterator AGI = AG.begin();
2004 isl_set *AGDomain = getAccessDomain(*AGI);
2005 while (AGI != AG.end()) {
2006 MemoryAccess *MA = *AGI;
2007 isl_set *MADomain = getAccessDomain(MA);
2008 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2009 NewAG.push_back(MA);
2010 AGI = AG.erase(AGI);
2011 isl_set_free(MADomain);
2012 } else {
2013 AGDomain = isl_set_union(AGDomain, MADomain);
2014 AGI++;
2015 }
2016 }
2017 if (NewAG.size() > 1)
2018 AliasGroups.push_back(std::move(NewAG));
2019 isl_set_free(AGDomain);
2020 }
2021
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002022 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002023 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2024 for (AliasGroupTy &AG : AliasGroups) {
2025 NonReadOnlyBaseValues.clear();
2026 ReadOnlyPairs.clear();
2027
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002028 if (AG.size() < 2) {
2029 AG.clear();
2030 continue;
2031 }
2032
Johannes Doerfert13771732014-10-01 12:40:46 +00002033 for (auto II = AG.begin(); II != AG.end();) {
2034 Value *BaseAddr = (*II)->getBaseAddr();
2035 if (HasWriteAccess.count(BaseAddr)) {
2036 NonReadOnlyBaseValues.insert(BaseAddr);
2037 II++;
2038 } else {
2039 ReadOnlyPairs[BaseAddr].insert(*II);
2040 II = AG.erase(II);
2041 }
2042 }
2043
2044 // If we don't have read only pointers check if there are at least two
2045 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002046 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002047 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002048 continue;
2049 }
2050
2051 // If we don't have non read only pointers clear the alias group.
2052 if (NonReadOnlyBaseValues.empty()) {
2053 AG.clear();
2054 continue;
2055 }
2056
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002057 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002058 MinMaxAliasGroups.emplace_back();
2059 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2060 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2061 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2062 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002063
2064 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002065
2066 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002067 for (MemoryAccess *MA : AG)
2068 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002069
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002070 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2071 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002072
2073 // Bail out if the number of values we need to compare is too large.
2074 // This is important as the number of comparisions grows quadratically with
2075 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002076 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2077 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002078 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002079
2080 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002081 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002082 Accesses = isl_union_map_empty(getParamSpace());
2083
2084 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2085 for (MemoryAccess *MA : ReadOnlyPair.second)
2086 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2087
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002088 Valid =
2089 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002090
2091 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002092 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002093 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002094
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002095 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002096}
2097
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002098static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
2099 Loop *L = LI.getLoopFor(R.getEntry());
2100 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2101}
2102
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002103static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2104 ScopDetection &SD) {
2105
2106 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2107
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002108 unsigned MinLD = INT_MAX, MaxLD = 0;
2109 for (BasicBlock *BB : R.blocks()) {
2110 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002111 if (!R.contains(L))
2112 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002113 if (BoxedLoops && BoxedLoops->count(L))
2114 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002115 unsigned LD = L->getLoopDepth();
2116 MinLD = std::min(MinLD, LD);
2117 MaxLD = std::max(MaxLD, LD);
2118 }
2119 }
2120
2121 // Handle the case that there is no loop in the SCoP first.
2122 if (MaxLD == 0)
2123 return 1;
2124
2125 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2126 assert(MaxLD >= MinLD &&
2127 "Maximal loop depth was smaller than mininaml loop depth?");
2128 return MaxLD - MinLD + 1;
2129}
2130
Michael Kruse9d080092015-09-11 21:41:48 +00002131Scop::Scop(Region &R, AccFuncMapType &AccFuncMap,
2132 ScalarEvolution &ScalarEvolution, DominatorTree &DT,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002133 isl_ctx *Context, unsigned MaxLoopDepth)
Michael Kruse9d080092015-09-11 21:41:48 +00002134 : DT(DT), SE(&ScalarEvolution), R(R), AccFuncMap(AccFuncMap),
2135 IsOptimized(false), HasSingleExitEdge(R.getExitingBlock()),
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002136 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Affinator(this),
2137 BoundaryContext(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002138
Michael Kruse9d080092015-09-11 21:41:48 +00002139void Scop::init(LoopInfo &LI, ScopDetection &SD, AliasAnalysis &AA) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002140 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00002141
Johannes Doerfert96425c22015-08-30 21:13:53 +00002142 buildDomains(&R, LI, SD, DT);
2143
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002144 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
Tobias Grosser75805372011-04-29 06:27:02 +00002145
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002146 Loop *L = getLoopSurroundingRegion(R, LI);
2147 LoopSchedules[L];
Michael Kruse9d080092015-09-11 21:41:48 +00002148 buildSchedule(&R, LI, SD, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002149 Schedule = LoopSchedules[L].first;
Tobias Grosser75805372011-04-29 06:27:02 +00002150
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002151 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002152 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002153 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002154 buildBoundaryContext();
2155 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002156 buildAliasChecks(AA);
Tobias Grosser75805372011-04-29 06:27:02 +00002157}
2158
2159Scop::~Scop() {
2160 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002161 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002162 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002163 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002164
Johannes Doerfert96425c22015-08-30 21:13:53 +00002165 for (auto It : DomainMap)
2166 isl_set_free(It.second);
2167
Johannes Doerfertb164c792014-09-18 11:17:17 +00002168 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002169 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002170 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002171 isl_pw_multi_aff_free(MMA.first);
2172 isl_pw_multi_aff_free(MMA.second);
2173 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002174 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002175 isl_pw_multi_aff_free(MMA.first);
2176 isl_pw_multi_aff_free(MMA.second);
2177 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002178 }
Tobias Grosser75805372011-04-29 06:27:02 +00002179}
2180
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002181const ScopArrayInfo *
2182Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Michael Kruse28468772015-09-14 15:45:33 +00002183 ArrayRef<const SCEV *> Sizes, bool IsPHI) {
Tobias Grosser92245222015-07-28 14:53:44 +00002184 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)];
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002185 if (!SAI)
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002186 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, IsPHI,
2187 this));
Tobias Grosserab671442015-05-23 05:58:27 +00002188 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002189}
2190
Tobias Grosser92245222015-07-28 14:53:44 +00002191const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, bool IsPHI) {
2192 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002193 assert(SAI && "No ScopArrayInfo available for this base pointer");
2194 return SAI;
2195}
2196
Tobias Grosser74394f02013-01-14 22:40:23 +00002197std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002198std::string Scop::getAssumedContextStr() const {
2199 return stringFromIslObj(AssumedContext);
2200}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002201std::string Scop::getBoundaryContextStr() const {
2202 return stringFromIslObj(BoundaryContext);
2203}
Tobias Grosser75805372011-04-29 06:27:02 +00002204
2205std::string Scop::getNameStr() const {
2206 std::string ExitName, EntryName;
2207 raw_string_ostream ExitStr(ExitName);
2208 raw_string_ostream EntryStr(EntryName);
2209
Tobias Grosserf240b482014-01-09 10:42:15 +00002210 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002211 EntryStr.str();
2212
2213 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00002214 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002215 ExitStr.str();
2216 } else
2217 ExitName = "FunctionExit";
2218
2219 return EntryName + "---" + ExitName;
2220}
2221
Tobias Grosser74394f02013-01-14 22:40:23 +00002222__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00002223__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002224 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00002225}
2226
Tobias Grossere86109f2013-10-29 21:05:49 +00002227__isl_give isl_set *Scop::getAssumedContext() const {
2228 return isl_set_copy(AssumedContext);
2229}
2230
Johannes Doerfert43788c52015-08-20 05:58:56 +00002231__isl_give isl_set *Scop::getRuntimeCheckContext() const {
2232 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002233 RuntimeCheckContext =
2234 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
2235 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002236 return RuntimeCheckContext;
2237}
2238
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002239bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002240 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002241 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002242 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
2243 isl_set_free(RuntimeCheckContext);
2244 return IsFeasible;
2245}
2246
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002247void Scop::addAssumption(__isl_take isl_set *Set) {
2248 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00002249 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002250}
2251
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002252__isl_give isl_set *Scop::getBoundaryContext() const {
2253 return isl_set_copy(BoundaryContext);
2254}
2255
Tobias Grosser75805372011-04-29 06:27:02 +00002256void Scop::printContext(raw_ostream &OS) const {
2257 OS << "Context:\n";
2258
2259 if (!Context) {
2260 OS.indent(4) << "n/a\n\n";
2261 return;
2262 }
2263
2264 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00002265
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002266 OS.indent(4) << "Assumed Context:\n";
2267 if (!AssumedContext) {
2268 OS.indent(4) << "n/a\n\n";
2269 return;
2270 }
2271
2272 OS.indent(4) << getAssumedContextStr() << "\n";
2273
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002274 OS.indent(4) << "Boundary Context:\n";
2275 if (!BoundaryContext) {
2276 OS.indent(4) << "n/a\n\n";
2277 return;
2278 }
2279
2280 OS.indent(4) << getBoundaryContextStr() << "\n";
2281
Tobias Grosser083d3d32014-06-28 08:59:45 +00002282 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00002283 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00002284 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
2285 }
Tobias Grosser75805372011-04-29 06:27:02 +00002286}
2287
Johannes Doerfertb164c792014-09-18 11:17:17 +00002288void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002289 int noOfGroups = 0;
2290 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002291 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002292 noOfGroups += 1;
2293 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002294 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002295 }
2296
Tobias Grosserbb853c22015-07-25 12:31:03 +00002297 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00002298 if (MinMaxAliasGroups.empty()) {
2299 OS.indent(8) << "n/a\n";
2300 return;
2301 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002302
Tobias Grosserbb853c22015-07-25 12:31:03 +00002303 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002304
2305 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002306 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002307 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002308 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002309 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2310 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002311 }
2312 OS << " ]]\n";
2313 }
2314
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002315 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002316 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00002317 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002318 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002319 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2320 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002321 }
2322 OS << " ]]\n";
2323 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002324 }
2325}
2326
Tobias Grosser75805372011-04-29 06:27:02 +00002327void Scop::printStatements(raw_ostream &OS) const {
2328 OS << "Statements {\n";
2329
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002330 for (const ScopStmt &Stmt : *this)
2331 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00002332
2333 OS.indent(4) << "}\n";
2334}
2335
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002336void Scop::printArrayInfo(raw_ostream &OS) const {
2337 OS << "Arrays {\n";
2338
Tobias Grosserab671442015-05-23 05:58:27 +00002339 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002340 Array.second->print(OS);
2341
2342 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002343
2344 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
2345
2346 for (auto &Array : arrays())
2347 Array.second->print(OS, /* SizeAsPwAff */ true);
2348
2349 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002350}
2351
Tobias Grosser75805372011-04-29 06:27:02 +00002352void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00002353 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
2354 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00002355 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00002356 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00002357 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002358 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002359 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00002360 printStatements(OS.indent(4));
2361}
2362
2363void Scop::dump() const { print(dbgs()); }
2364
Tobias Grosser9a38ab82011-11-08 15:41:03 +00002365isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00002366
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002367__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
2368 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00002369}
2370
Tobias Grosser808cd692015-07-14 09:33:13 +00002371__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002372 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002373
Tobias Grosser808cd692015-07-14 09:33:13 +00002374 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002375 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002376
2377 return Domain;
2378}
2379
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002380__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002381 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002382
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002383 for (ScopStmt &Stmt : *this) {
2384 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002385 if (!MA->isMustWrite())
2386 continue;
2387
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002388 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002389 isl_map *AccessDomain = MA->getAccessRelation();
2390 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2391 Write = isl_union_map_add_map(Write, AccessDomain);
2392 }
2393 }
2394 return isl_union_map_coalesce(Write);
2395}
2396
2397__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002398 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002399
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002400 for (ScopStmt &Stmt : *this) {
2401 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002402 if (!MA->isMayWrite())
2403 continue;
2404
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002405 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002406 isl_map *AccessDomain = MA->getAccessRelation();
2407 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2408 Write = isl_union_map_add_map(Write, AccessDomain);
2409 }
2410 }
2411 return isl_union_map_coalesce(Write);
2412}
2413
Tobias Grosser37eb4222014-02-20 21:43:54 +00002414__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002415 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002416
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002417 for (ScopStmt &Stmt : *this) {
2418 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002419 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002420 continue;
2421
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002422 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002423 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002424 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2425 Write = isl_union_map_add_map(Write, AccessDomain);
2426 }
2427 }
2428 return isl_union_map_coalesce(Write);
2429}
2430
2431__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002432 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002433
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002434 for (ScopStmt &Stmt : *this) {
2435 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002436 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002437 continue;
2438
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002439 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002440 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002441
2442 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2443 Read = isl_union_map_add_map(Read, AccessDomain);
2444 }
2445 }
2446 return isl_union_map_coalesce(Read);
2447}
2448
Tobias Grosser808cd692015-07-14 09:33:13 +00002449__isl_give isl_union_map *Scop::getSchedule() const {
2450 auto Tree = getScheduleTree();
2451 auto S = isl_schedule_get_map(Tree);
2452 isl_schedule_free(Tree);
2453 return S;
2454}
Tobias Grosser37eb4222014-02-20 21:43:54 +00002455
Tobias Grosser808cd692015-07-14 09:33:13 +00002456__isl_give isl_schedule *Scop::getScheduleTree() const {
2457 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
2458 getDomains());
2459}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002460
Tobias Grosser808cd692015-07-14 09:33:13 +00002461void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
2462 auto *S = isl_schedule_from_domain(getDomains());
2463 S = isl_schedule_insert_partial_schedule(
2464 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
2465 isl_schedule_free(Schedule);
2466 Schedule = S;
2467}
2468
2469void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
2470 isl_schedule_free(Schedule);
2471 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00002472}
2473
2474bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
2475 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002476 for (ScopStmt &Stmt : *this) {
2477 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002478 isl_union_set *NewStmtDomain = isl_union_set_intersect(
2479 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
2480
2481 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
2482 isl_union_set_free(StmtDomain);
2483 isl_union_set_free(NewStmtDomain);
2484 continue;
2485 }
2486
2487 Changed = true;
2488
2489 isl_union_set_free(StmtDomain);
2490 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
2491
2492 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002493 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002494 isl_union_set_free(NewStmtDomain);
2495 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002496 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002497 }
2498 isl_union_set_free(Domain);
2499 return Changed;
2500}
2501
Tobias Grosser75805372011-04-29 06:27:02 +00002502ScalarEvolution *Scop::getSE() const { return SE; }
2503
Michael Kruse9d080092015-09-11 21:41:48 +00002504bool Scop::isTrivialBB(BasicBlock *BB) {
2505 if (getAccessFunctions(BB) && !isErrorBlock(*BB))
Tobias Grosser75805372011-04-29 06:27:02 +00002506 return false;
2507
2508 return true;
2509}
2510
Tobias Grosser808cd692015-07-14 09:33:13 +00002511struct MapToDimensionDataTy {
2512 int N;
2513 isl_union_pw_multi_aff *Res;
2514};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002515
Tobias Grosser808cd692015-07-14 09:33:13 +00002516// @brief Create a function that maps the elements of 'Set' to its N-th
2517// dimension.
2518//
2519// The result is added to 'User->Res'.
2520//
2521// @param Set The input set.
2522// @param N The dimension to map to.
2523//
2524// @returns Zero if no error occurred, non-zero otherwise.
2525static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
2526 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
2527 int Dim;
2528 isl_space *Space;
2529 isl_pw_multi_aff *PMA;
2530
2531 Dim = isl_set_dim(Set, isl_dim_set);
2532 Space = isl_set_get_space(Set);
2533 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
2534 Dim - Data->N);
2535 if (Data->N > 1)
2536 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
2537 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
2538
2539 isl_set_free(Set);
2540
2541 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002542}
2543
Tobias Grosser808cd692015-07-14 09:33:13 +00002544// @brief Create a function that maps the elements of Domain to their Nth
2545// dimension.
2546//
2547// @param Domain The set of elements to map.
2548// @param N The dimension to map to.
2549static __isl_give isl_multi_union_pw_aff *
2550mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002551 if (N <= 0 || isl_union_set_is_empty(Domain)) {
2552 isl_union_set_free(Domain);
2553 return nullptr;
2554 }
2555
Tobias Grosser808cd692015-07-14 09:33:13 +00002556 struct MapToDimensionDataTy Data;
2557 isl_space *Space;
2558
2559 Space = isl_union_set_get_space(Domain);
2560 Data.N = N;
2561 Data.Res = isl_union_pw_multi_aff_empty(Space);
2562 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
2563 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
2564
2565 isl_union_set_free(Domain);
2566 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
2567}
2568
Michael Kruse9d080092015-09-11 21:41:48 +00002569ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00002570 ScopStmt *Stmt;
2571 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00002572 Stmts.emplace_back(*this, *BB);
Tobias Grosser808cd692015-07-14 09:33:13 +00002573 Stmt = &Stmts.back();
2574 StmtMap[BB] = Stmt;
2575 } else {
2576 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00002577 Stmts.emplace_back(*this, *R);
Tobias Grosser808cd692015-07-14 09:33:13 +00002578 Stmt = &Stmts.back();
2579 for (BasicBlock *BB : R->blocks())
2580 StmtMap[BB] = Stmt;
2581 }
2582 return Stmt;
2583}
2584
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002585void Scop::buildSchedule(
Michael Kruse9d080092015-09-11 21:41:48 +00002586 Region *R, LoopInfo &LI, ScopDetection &SD,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002587 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00002588
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002589 if (SD.isNonAffineSubRegion(R, &getRegion())) {
2590 auto *Stmt = addScopStmt(nullptr, R);
2591 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
2592 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
2593 auto &LSchedulePair = LoopSchedules[nullptr];
2594 LSchedulePair.first = StmtSchedule;
2595 return;
2596 }
2597
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002598 ReversePostOrderTraversal<Region *> RTraversal(R);
2599 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00002600
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002601 if (RN->isSubRegion()) {
2602 Region *SubRegion = RN->getNodeAs<Region>();
2603 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Michael Kruse9d080092015-09-11 21:41:48 +00002604 buildSchedule(SubRegion, LI, SD, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002605 continue;
2606 }
Tobias Grosser75805372011-04-29 06:27:02 +00002607 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002608
2609 Loop *L = getRegionNodeLoop(RN, LI);
2610 int LD = getRelativeLoopDepth(L);
2611 auto &LSchedulePair = LoopSchedules[L];
2612 LSchedulePair.second += getNumBlocksInRegionNode(RN);
2613
2614 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Michael Kruse9d080092015-09-11 21:41:48 +00002615 if (RN->isSubRegion() || !isTrivialBB(BB)) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002616
2617 ScopStmt *Stmt;
2618 if (RN->isSubRegion())
Michael Kruse9d080092015-09-11 21:41:48 +00002619 Stmt = addScopStmt(nullptr, RN->getNodeAs<Region>());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002620 else
Michael Kruse9d080092015-09-11 21:41:48 +00002621 Stmt = addScopStmt(BB, nullptr);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002622
2623 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
2624 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
2625 LSchedulePair.first =
2626 combineInSequence(LSchedulePair.first, StmtSchedule);
2627 }
2628
2629 unsigned NumVisited = LSchedulePair.second;
2630 while (L && NumVisited == L->getNumBlocks()) {
2631 auto *LDomain = isl_schedule_get_domain(LSchedulePair.first);
2632 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
2633 LSchedulePair.first =
2634 isl_schedule_insert_partial_schedule(LSchedulePair.first, MUPA);
2635
2636 auto *PL = L->getParentLoop();
2637 assert(LoopSchedules.count(PL));
2638 auto &PSchedulePair = LoopSchedules[PL];
2639 PSchedulePair.first =
2640 combineInSequence(PSchedulePair.first, LSchedulePair.first);
2641 PSchedulePair.second += NumVisited;
2642
2643 L = PL;
2644 NumVisited = PSchedulePair.second;
2645 }
Tobias Grosser808cd692015-07-14 09:33:13 +00002646 }
Tobias Grosser75805372011-04-29 06:27:02 +00002647}
2648
Johannes Doerfert7c494212014-10-31 23:13:39 +00002649ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00002650 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00002651 if (StmtMapIt == StmtMap.end())
2652 return nullptr;
2653 return StmtMapIt->second;
2654}
2655
Johannes Doerfert96425c22015-08-30 21:13:53 +00002656int Scop::getRelativeLoopDepth(const Loop *L) const {
2657 Loop *OuterLoop =
2658 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
2659 if (!OuterLoop)
2660 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00002661 return L->getLoopDepth() - OuterLoop->getLoopDepth();
2662}
2663
Michael Krused868b5d2015-09-10 15:25:24 +00002664void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00002665 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002666
2667 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
2668 // true, are not modeled as ordinary PHI nodes as they are not part of the
2669 // region. However, we model the operands in the predecessor blocks that are
2670 // part of the region as regular scalar accesses.
2671
2672 // If we can synthesize a PHI we can skip it, however only if it is in
2673 // the region. If it is not it can only be in the exit block of the region.
2674 // In this case we model the operands but not the PHI itself.
2675 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
2676 return;
2677
2678 // PHI nodes are modeled as if they had been demoted prior to the SCoP
2679 // detection. Hence, the PHI is a load of a new memory location in which the
2680 // incoming value was written at the end of the incoming basic block.
2681 bool OnlyNonAffineSubRegionOperands = true;
2682 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
2683 Value *Op = PHI->getIncomingValue(u);
2684 BasicBlock *OpBB = PHI->getIncomingBlock(u);
2685
2686 // Do not build scalar dependences inside a non-affine subregion.
2687 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
2688 continue;
2689
2690 OnlyNonAffineSubRegionOperands = false;
2691
2692 if (!R.contains(OpBB))
2693 continue;
2694
2695 Instruction *OpI = dyn_cast<Instruction>(Op);
2696 if (OpI) {
2697 BasicBlock *OpIBB = OpI->getParent();
2698 // As we pretend there is a use (or more precise a write) of OpI in OpBB
2699 // we have to insert a scalar dependence from the definition of OpI to
2700 // OpBB if the definition is not in OpBB.
2701 if (OpIBB != OpBB) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002702 addScalarReadAccess(OpI, PHI, OpBB);
2703 addScalarWriteAccess(OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00002704 }
Tobias Grosserda95a4a2015-09-24 20:59:59 +00002705 } else if (ModelReadOnlyScalars && !isa<Constant>(Op)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002706 addScalarReadAccess(Op, PHI, OpBB);
Michael Kruse7bf39442015-09-10 12:46:52 +00002707 }
2708
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002709 addPHIWriteAccess(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00002710 }
2711
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002712 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
2713 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00002714 }
2715}
2716
Michael Krused868b5d2015-09-10 15:25:24 +00002717bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
2718 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002719 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
2720 if (isIgnoredIntrinsic(Inst))
2721 return false;
2722
2723 bool AnyCrossStmtUse = false;
2724 BasicBlock *ParentBB = Inst->getParent();
2725
2726 for (User *U : Inst->users()) {
2727 Instruction *UI = dyn_cast<Instruction>(U);
2728
2729 // Ignore the strange user
2730 if (UI == 0)
2731 continue;
2732
2733 BasicBlock *UseParent = UI->getParent();
2734
2735 // Ignore the users in the same BB (statement)
2736 if (UseParent == ParentBB)
2737 continue;
2738
2739 // Do not build scalar dependences inside a non-affine subregion.
2740 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
2741 continue;
2742
2743 // Check whether or not the use is in the SCoP.
2744 if (!R->contains(UseParent)) {
2745 AnyCrossStmtUse = true;
2746 continue;
2747 }
2748
2749 // If the instruction can be synthesized and the user is in the region
2750 // we do not need to add scalar dependences.
2751 if (canSynthesizeInst)
2752 continue;
2753
2754 // No need to translate these scalar dependences into polyhedral form,
2755 // because synthesizable scalars can be generated by the code generator.
2756 if (canSynthesize(UI, LI, SE, R))
2757 continue;
2758
2759 // Skip PHI nodes in the region as they handle their operands on their own.
2760 if (isa<PHINode>(UI))
2761 continue;
2762
2763 // Now U is used in another statement.
2764 AnyCrossStmtUse = true;
2765
2766 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00002767 // Use the def instruction as base address of the MemoryAccess, so that it
2768 // will become the name of the scalar access in the polyhedral form.
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002769 addScalarReadAccess(Inst, UI);
Michael Kruse7bf39442015-09-10 12:46:52 +00002770 }
2771
Tobias Grosserda95a4a2015-09-24 20:59:59 +00002772 if (ModelReadOnlyScalars && !isa<PHINode>(Inst)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002773 for (Value *Op : Inst->operands()) {
2774 if (canSynthesize(Op, LI, SE, R))
2775 continue;
2776
2777 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
2778 if (R->contains(OpInst))
2779 continue;
2780
2781 if (isa<Constant>(Op))
2782 continue;
2783
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002784 addScalarReadAccess(Op, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00002785 }
2786 }
2787
2788 return AnyCrossStmtUse;
2789}
2790
2791extern MapInsnToMemAcc InsnToMemAcc;
2792
Michael Krusee2bccbb2015-09-18 19:59:43 +00002793void ScopInfo::buildMemoryAccess(
2794 Instruction *Inst, Loop *L, Region *R,
2795 const ScopDetection::BoxedLoopsSetTy *BoxedLoops) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002796 unsigned Size;
2797 Type *SizeType;
2798 Value *Val;
Michael Krusee2bccbb2015-09-18 19:59:43 +00002799 enum MemoryAccess::AccessType Type;
Michael Kruse7bf39442015-09-10 12:46:52 +00002800
2801 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
2802 SizeType = Load->getType();
2803 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00002804 Type = MemoryAccess::READ;
Michael Kruse7bf39442015-09-10 12:46:52 +00002805 Val = Load;
2806 } else {
2807 StoreInst *Store = cast<StoreInst>(Inst);
2808 SizeType = Store->getValueOperand()->getType();
2809 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00002810 Type = MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00002811 Val = Store->getValueOperand();
2812 }
2813
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002814 auto Address = getPointerOperand(*Inst);
2815
2816 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00002817 const SCEVUnknown *BasePointer =
2818 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
2819
2820 assert(BasePointer && "Could not find base pointer");
2821 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
2822
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002823 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
2824 auto NewAddress = Address;
2825 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
2826 auto Src = BitCast->getOperand(0);
2827 auto SrcTy = Src->getType();
2828 auto DstTy = BitCast->getType();
2829 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
2830 NewAddress = Src;
2831 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002832
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002833 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
2834 std::vector<const SCEV *> Subscripts;
2835 std::vector<int> Sizes;
2836 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
2837 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002838
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002839 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002840
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002841 bool AllAffineSubcripts = true;
2842 for (auto Subscript : Subscripts)
2843 if (!isAffineExpr(R, Subscript, *SE)) {
2844 AllAffineSubcripts = false;
2845 break;
2846 }
2847
2848 if (AllAffineSubcripts && Sizes.size() > 0) {
2849 for (auto V : Sizes)
2850 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
2851 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002852 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002853 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002854
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002855 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
2856 Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00002857 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002858 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002859 }
2860 }
2861
Michael Kruse7bf39442015-09-10 12:46:52 +00002862 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00002863 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002864 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
2865 AccItr->second.DelinearizedSubscripts,
2866 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00002867 return;
2868 }
Michael Kruse7bf39442015-09-10 12:46:52 +00002869
2870 // Check if the access depends on a loop contained in a non-affine subregion.
2871 bool isVariantInNonAffineLoop = false;
2872 if (BoxedLoops) {
2873 SetVector<const Loop *> Loops;
2874 findLoops(AccessFunction, Loops);
2875 for (const Loop *L : Loops)
2876 if (BoxedLoops->count(L))
2877 isVariantInNonAffineLoop = true;
2878 }
2879
2880 bool IsAffine = !isVariantInNonAffineLoop &&
2881 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue());
2882
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002883 // FIXME: Size if the number of bytes of an array element, not the number of
2884 // elements as probably intended here.
2885 const SCEV *SizeSCEV = SE->getConstant(ZeroOffset->getType(), Size);
Michael Kruse7bf39442015-09-10 12:46:52 +00002886
Michael Krusee2bccbb2015-09-18 19:59:43 +00002887 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
2888 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00002889
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002890 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, IsAffine,
2891 ArrayRef<const SCEV *>(AccessFunction),
2892 ArrayRef<const SCEV *>(SizeSCEV), Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00002893}
2894
Michael Krused868b5d2015-09-10 15:25:24 +00002895void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002896
2897 if (SD->isNonAffineSubRegion(&SR, &R)) {
2898 for (BasicBlock *BB : SR.blocks())
2899 buildAccessFunctions(R, *BB, &SR);
2900 return;
2901 }
2902
2903 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
2904 if (I->isSubRegion())
2905 buildAccessFunctions(R, *I->getNodeAs<Region>());
2906 else
2907 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
2908}
2909
Michael Krused868b5d2015-09-10 15:25:24 +00002910void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
2911 Region *NonAffineSubRegion,
2912 bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002913 Loop *L = LI->getLoopFor(&BB);
2914
2915 // The set of loops contained in non-affine subregions that are part of R.
2916 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
2917
2918 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
2919 Instruction *Inst = I;
2920
2921 PHINode *PHI = dyn_cast<PHINode>(Inst);
2922 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00002923 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00002924
2925 // For the exit block we stop modeling after the last PHI node.
2926 if (!PHI && IsExitBlock)
2927 break;
2928
2929 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
Michael Krusee2bccbb2015-09-18 19:59:43 +00002930 buildMemoryAccess(Inst, L, &R, BoxedLoops);
Michael Kruse7bf39442015-09-10 12:46:52 +00002931
2932 if (isIgnoredIntrinsic(Inst))
2933 continue;
2934
2935 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00002936 if (!isa<StoreInst>(Inst))
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002937 addScalarWriteAccess(Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00002938 }
2939 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00002940}
Michael Kruse7bf39442015-09-10 12:46:52 +00002941
Michael Kruse2d0ece92015-09-24 11:41:21 +00002942void ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
2943 MemoryAccess::AccessType Type,
2944 Value *BaseAddress, unsigned ElemBytes,
2945 bool Affine, Value *AccessValue,
2946 ArrayRef<const SCEV *> Subscripts,
Michael Kruse8d0b7342015-09-25 21:21:00 +00002947 ArrayRef<const SCEV *> Sizes,
2948 MemoryAccess::AccessOrigin Origin) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00002949 AccFuncSetType &AccList = AccFuncMap[BB];
2950 size_t Identifier = AccList.size();
Michael Kruse7bf39442015-09-10 12:46:52 +00002951
Michael Krusee2bccbb2015-09-18 19:59:43 +00002952 Value *BaseAddr = BaseAddress;
2953 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
2954
2955 std::string IdName = "__polly_array_ref_" + std::to_string(Identifier);
2956 isl_id *Id = isl_id_alloc(ctx, IdName.c_str(), nullptr);
2957
Michael Kruse2d0ece92015-09-24 11:41:21 +00002958 AccList.emplace_back(Inst, Id, Type, BaseAddress, ElemBytes, Affine,
Michael Kruse8d0b7342015-09-25 21:21:00 +00002959 Subscripts, Sizes, AccessValue, Origin, BaseName);
Michael Kruse7bf39442015-09-10 12:46:52 +00002960}
2961
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002962void ScopInfo::addExplicitAccess(
2963 Instruction *MemAccInst, MemoryAccess::AccessType Type, Value *BaseAddress,
2964 unsigned ElemBytes, bool IsAffine, ArrayRef<const SCEV *> Subscripts,
2965 ArrayRef<const SCEV *> Sizes, Value *AccessValue) {
2966 assert(isa<LoadInst>(MemAccInst) || isa<StoreInst>(MemAccInst));
2967 assert(isa<LoadInst>(MemAccInst) == (Type == MemoryAccess::READ));
2968 addMemoryAccess(MemAccInst->getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00002969 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
2970 MemoryAccess::EXPLICIT);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002971}
2972void ScopInfo::addScalarWriteAccess(Instruction *Value) {
2973 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
2974 true, Value, ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00002975 ArrayRef<const SCEV *>(), MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002976}
2977void ScopInfo::addScalarReadAccess(Value *Value, Instruction *User) {
2978 assert(!isa<PHINode>(User));
2979 addMemoryAccess(User->getParent(), User, MemoryAccess::READ, Value, 1, true,
2980 Value, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00002981 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002982}
2983void ScopInfo::addScalarReadAccess(Value *Value, PHINode *User,
2984 BasicBlock *UserBB) {
2985 addMemoryAccess(UserBB, User, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00002986 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
2987 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002988}
2989void ScopInfo::addPHIWriteAccess(PHINode *PHI, BasicBlock *IncomingBlock,
2990 Value *IncomingValue, bool IsExitBlock) {
2991 addMemoryAccess(IncomingBlock, IncomingBlock->getTerminator(),
2992 MemoryAccess::MUST_WRITE, PHI, 1, true, IncomingValue,
2993 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00002994 IsExitBlock ? MemoryAccess::SCALAR : MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00002995}
2996void ScopInfo::addPHIReadAccess(PHINode *PHI) {
2997 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00002998 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
2999 MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003000}
3001
Michael Kruse9d080092015-09-11 21:41:48 +00003002Scop *ScopInfo::buildScop(Region &R, DominatorTree &DT) {
3003 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
3004 Scop *S = new Scop(R, AccFuncMap, *SE, DT, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00003005
3006 buildAccessFunctions(R, R);
3007
3008 // In case the region does not have an exiting block we will later (during
3009 // code generation) split the exit block. This will move potential PHI nodes
3010 // from the current exit block into the new region exiting block. Hence, PHI
3011 // nodes that are at this point not part of the region will be.
3012 // To handle these PHI nodes later we will now model their operands as scalar
3013 // accesses. Note that we do not model anything in the exit block if we have
3014 // an exiting block in the region, as there will not be any splitting later.
3015 if (!R.getExitingBlock())
3016 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
3017
Michael Kruse9d080092015-09-11 21:41:48 +00003018 S->init(*LI, *SD, *AA);
3019 return S;
Michael Kruse7bf39442015-09-10 12:46:52 +00003020}
3021
Michael Krused868b5d2015-09-10 15:25:24 +00003022void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00003023 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00003024 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00003025 return;
3026 }
3027
Michael Kruse9d080092015-09-11 21:41:48 +00003028 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00003029}
3030
Michael Krused868b5d2015-09-10 15:25:24 +00003031void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00003032 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00003033 if (scop) {
3034 delete scop;
3035 scop = 0;
3036 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003037}
3038
3039//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00003040ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00003041 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00003042 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00003043}
3044
3045ScopInfo::~ScopInfo() {
3046 clear();
3047 isl_ctx_free(ctx);
3048}
3049
Tobias Grosser75805372011-04-29 06:27:02 +00003050void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Michael Krused868b5d2015-09-10 15:25:24 +00003051 AU.addRequiredID(IndependentBlocksID);
Chandler Carruthf5579872015-01-17 14:16:56 +00003052 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00003053 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00003054 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00003055 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
3056 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003057 AU.addRequired<AAResultsWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00003058 AU.setPreservesAll();
3059}
3060
3061bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00003062 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00003063
Michael Krused868b5d2015-09-10 15:25:24 +00003064 if (!SD->isMaxRegionInScop(*R))
3065 return false;
3066
3067 Function *F = R->getEntry()->getParent();
3068 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3069 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3070 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3071 TD = &F->getParent()->getDataLayout();
3072 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3073 ZeroOffset = SE->getConstant(TD->getIntPtrType(F->getContext()), 0);
3074
Michael Kruse9d080092015-09-11 21:41:48 +00003075 scop = buildScop(*R, DT);
Tobias Grosser75805372011-04-29 06:27:02 +00003076
Tobias Grosserd6a50b32015-05-30 06:26:21 +00003077 DEBUG(scop->print(dbgs()));
3078
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003079 if (!scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003080 delete scop;
3081 scop = nullptr;
3082 return false;
3083 }
3084
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003085 // Statistics.
3086 ++ScopFound;
3087 if (scop->getMaxLoopDepth() > 0)
3088 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00003089 return false;
3090}
3091
3092char ScopInfo::ID = 0;
3093
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003094Pass *polly::createScopInfoPass() { return new ScopInfo(); }
3095
Tobias Grosser73600b82011-10-08 00:30:40 +00003096INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
3097 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003098 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003099INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00003100INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00003101INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00003102INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003103INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003104INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00003105INITIALIZE_PASS_END(ScopInfo, "polly-scops",
3106 "Polly - Create polyhedral description of Scops", false,
3107 false)