blob: fe23e5d770d17c13a12e936ede20e731980942c6 [file] [log] [blame]
Johannes Doerfert58a7c752015-09-28 09:48:53 +00001//===--------- ScopInfo.cpp - Create Scops from LLVM IR ------------------===//
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 Grosser5624d3c2015-12-21 12:38:56 +000020#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000021#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000022#include "polly/Options.h"
Tobias Grosser75805372011-04-29 06:27:02 +000023#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000024#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000025#include "polly/Support/ScopHelper.h"
Tobias Grosser9737c7b2015-11-22 11:06:51 +000026#include "llvm/ADT/DepthFirstIterator.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"
Johannes Doerfert2af10e22015-11-12 03:25:01 +000034#include "llvm/Analysis/AssumptionCache.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000035#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000036#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000037#include "llvm/Analysis/RegionIterator.h"
38#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Johannes Doerfert48fe86f2015-11-12 02:32:32 +000039#include "llvm/IR/DiagnosticInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000040#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000041#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000042#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000043#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000044#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000045#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000046#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000047#include "isl/schedule.h"
48#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000049#include "isl/set.h"
50#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000051#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000052#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000053#include <sstream>
54#include <string>
55#include <vector>
56
57using namespace llvm;
58using namespace polly;
59
Chandler Carruth95fef942014-04-22 03:30:19 +000060#define DEBUG_TYPE "polly-scops"
61
Tobias Grosser74394f02013-01-14 22:40:23 +000062STATISTIC(ScopFound, "Number of valid Scops");
63STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000064
Tobias Grosser75dc40c2015-12-20 13:31:48 +000065// The maximal number of basic sets we allow during domain construction to
66// be created. More complex scops will result in very high compile time and
67// are also unlikely to result in good code
68static int const MaxConjunctsInDomain = 20;
69
Michael Kruse7bf39442015-09-10 12:46:52 +000070static cl::opt<bool> ModelReadOnlyScalars(
71 "polly-analyze-read-only-scalars",
72 cl::desc("Model read-only scalar values in the scop description"),
73 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
74
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000075// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000076// operations can overflow easily. Additive reductions and bit operations
77// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000078static cl::opt<bool> DisableMultiplicativeReductions(
79 "polly-disable-multiplicative-reductions",
80 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
81 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000082
Johannes Doerfert9143d672014-09-27 11:02:39 +000083static cl::opt<unsigned> RunTimeChecksMaxParameters(
84 "polly-rtc-max-parameters",
85 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
86 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
87
Tobias Grosser71500722015-03-28 15:11:14 +000088static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
89 "polly-rtc-max-arrays-per-group",
90 cl::desc("The maximal number of arrays to compare in each alias group."),
91 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000092static cl::opt<std::string> UserContextStr(
93 "polly-context", cl::value_desc("isl parameter set"),
94 cl::desc("Provide additional constraints on the context parameters"),
95 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000096
Tobias Grosserd83b8a82015-08-20 19:08:11 +000097static cl::opt<bool> DetectReductions("polly-detect-reductions",
98 cl::desc("Detect and exploit reductions"),
99 cl::Hidden, cl::ZeroOrMore,
100 cl::init(true), cl::cat(PollyCategory));
101
Tobias Grosser4927c8e2015-11-24 12:50:02 +0000102static cl::opt<bool> IgnoreIntegerWrapping(
103 "polly-ignore-integer-wrapping",
104 cl::desc("Do not build run-time checks to proof absence of integer "
105 "wrapping"),
106 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
107
Michael Kruse7bf39442015-09-10 12:46:52 +0000108//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000109
Michael Kruse046dde42015-08-10 13:01:57 +0000110// Create a sequence of two schedules. Either argument may be null and is
111// interpreted as the empty schedule. Can also return null if both schedules are
112// empty.
113static __isl_give isl_schedule *
114combineInSequence(__isl_take isl_schedule *Prev,
115 __isl_take isl_schedule *Succ) {
116 if (!Prev)
117 return Succ;
118 if (!Succ)
119 return Prev;
120
121 return isl_schedule_sequence(Prev, Succ);
122}
123
Johannes Doerferte7044942015-02-24 11:58:30 +0000124static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
125 const ConstantRange &Range,
126 int dim,
127 enum isl_dim_type type) {
128 isl_val *V;
129 isl_ctx *ctx = isl_set_get_ctx(S);
130
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000131 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
132 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000133 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000134 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
135
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000136 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000137 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000138 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000139 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000140 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
141
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000142 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000143 return isl_set_union(SLB, SUB);
144 else
145 return isl_set_intersect(SLB, SUB);
146}
147
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000148static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
149 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
150 if (!BasePtrLI)
151 return nullptr;
152
153 if (!S->getRegion().contains(BasePtrLI))
154 return nullptr;
155
156 ScalarEvolution &SE = *S->getSE();
157
158 auto *OriginBaseSCEV =
159 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
160 if (!OriginBaseSCEV)
161 return nullptr;
162
163 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
164 if (!OriginBaseSCEVUnknown)
165 return nullptr;
166
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000167 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grossera535dff2015-12-13 19:59:01 +0000168 ScopArrayInfo::MK_Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000169}
170
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000171ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grossera535dff2015-12-13 19:59:01 +0000172 ArrayRef<const SCEV *> Sizes, enum MemoryKind Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000173 const DataLayout &DL, Scop *S)
174 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000175 std::string BasePtrName =
Tobias Grossera535dff2015-12-13 19:59:01 +0000176 getIslCompatibleName("MemRef_", BasePtr, Kind == MK_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000177 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000178
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000179 updateSizes(Sizes);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000180 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
181 if (BasePtrOriginSAI)
182 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000183}
184
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000185__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000186 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000187 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
188 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
189 return Space;
190}
191
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000192void ScopArrayInfo::updateElementType(Type *NewElementType) {
193 if (NewElementType == ElementType)
194 return;
195
Tobias Grosserd840fc72016-02-04 13:18:42 +0000196 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
197 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
198
Johannes Doerferta7920982016-02-25 14:08:48 +0000199 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000200 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000201
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000202 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
203 ElementType = NewElementType;
204 } else {
205 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
206 ElementType = IntegerType::get(ElementType->getContext(), GCD);
207 }
208}
209
210bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000211 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
212 int ExtraDimsNew = NewSizes.size() - SharedDims;
213 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Tobias Grosser8286b832015-11-02 11:29:32 +0000214 for (int i = 0; i < SharedDims; i++)
215 if (NewSizes[i + ExtraDimsNew] != DimensionSizes[i + ExtraDimsOld])
216 return false;
217
218 if (DimensionSizes.size() >= NewSizes.size())
219 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000220
221 DimensionSizes.clear();
222 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
223 NewSizes.end());
224 for (isl_pw_aff *Size : DimensionSizesPw)
225 isl_pw_aff_free(Size);
226 DimensionSizesPw.clear();
227 for (const SCEV *Expr : DimensionSizes) {
228 isl_pw_aff *Size = S.getPwAff(Expr);
229 DimensionSizesPw.push_back(Size);
230 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000231 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000232}
233
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000234ScopArrayInfo::~ScopArrayInfo() {
235 isl_id_free(Id);
236 for (isl_pw_aff *Size : DimensionSizesPw)
237 isl_pw_aff_free(Size);
238}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000239
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000240std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
241
242int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000243 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000244}
245
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000246isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
247
248void ScopArrayInfo::dump() const { print(errs()); }
249
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000250void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000251 OS.indent(8) << *getElementType() << " " << getName();
252 if (getNumberOfDimensions() > 0)
253 OS << "[*]";
Tobias Grosser26253842015-11-10 14:24:21 +0000254 for (unsigned u = 1; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000255 OS << "[";
256
Tobias Grosser26253842015-11-10 14:24:21 +0000257 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000258 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000259 OS << " " << Size << " ";
260 isl_pw_aff_free(Size);
261 } else {
262 OS << *getDimensionSize(u);
263 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000264
265 OS << "]";
266 }
267
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000268 OS << ";";
269
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000270 if (BasePtrOriginSAI)
271 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
272
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000273 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000274}
275
276const ScopArrayInfo *
277ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
278 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
279 assert(Id && "Output dimension didn't have an ID");
280 return getFromId(Id);
281}
282
283const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
284 void *User = isl_id_get_user(Id);
285 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
286 isl_id_free(Id);
287 return SAI;
288}
289
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000290void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000291 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000292 auto *ArraySpace = SAI->getSpace();
293 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000294 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000295
296 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
297 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
298 auto DimsMissing = DimsArray - DimsAccess;
299
Michael Kruse375cb5f2016-02-24 22:08:24 +0000300 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000301 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000302 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000303 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000304
Johannes Doerferta90943d2016-02-21 16:37:25 +0000305 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000306 isl_set_universe(AccessSpace),
307 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000308
309 for (unsigned i = 0; i < DimsMissing; i++)
310 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
311
312 for (unsigned i = DimsMissing; i < DimsArray; i++)
313 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
314
315 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000316
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000317 // For the non delinearized arrays, divide the access function of the last
318 // subscript by the size of the elements in the array.
319 //
320 // A stride one array access in C expressed as A[i] is expressed in
321 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
322 // two subsequent values of 'i' index two values that are stored next to
323 // each other in memory. By this division we make this characteristic
324 // obvious again. If the base pointer was accessed with offsets not divisible
325 // by the accesses element size, we will have choosen a smaller ArrayElemSize
326 // that divides the offsets of all accesses to this base pointer.
327 if (DimsAccess == 1) {
328 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
329 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
330 }
331
332 if (!isAffine())
333 computeBoundsOnAccessRelation(ArrayElemSize);
334
Tobias Grosserd840fc72016-02-04 13:18:42 +0000335 // Introduce multi-element accesses in case the type loaded by this memory
336 // access is larger than the canonical element type of the array.
337 //
338 // An access ((float *)A)[i] to an array char *A is modeled as
339 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000340 if (ElemBytes > ArrayElemSize) {
341 assert(ElemBytes % ArrayElemSize == 0 &&
342 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000343 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000344 isl_set_universe(isl_space_copy(ArraySpace)),
345 isl_set_universe(isl_space_copy(ArraySpace)));
346 for (unsigned i = 0; i < DimsArray - 1; i++)
347 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
348
Tobias Grosserd840fc72016-02-04 13:18:42 +0000349 isl_constraint *C;
350 isl_local_space *LS;
351
352 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000353 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
354
355 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
356 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000357 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000358 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
359 Map = isl_map_add_constraint(Map, C);
360
361 C = isl_constraint_alloc_inequality(LS);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000362 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000363 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
364 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
365 Map = isl_map_add_constraint(Map, C);
366 AccessRelation = isl_map_apply_range(AccessRelation, Map);
367 }
368
369 isl_space_free(ArraySpace);
370
Roman Gareev10595a12016-01-08 14:01:59 +0000371 assumeNoOutOfBound();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000372}
373
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000374const std::string
375MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
376 switch (RT) {
377 case MemoryAccess::RT_NONE:
378 llvm_unreachable("Requested a reduction operator string for a memory "
379 "access which isn't a reduction");
380 case MemoryAccess::RT_ADD:
381 return "+";
382 case MemoryAccess::RT_MUL:
383 return "*";
384 case MemoryAccess::RT_BOR:
385 return "|";
386 case MemoryAccess::RT_BXOR:
387 return "^";
388 case MemoryAccess::RT_BAND:
389 return "&";
390 }
391 llvm_unreachable("Unknown reduction type");
392 return "";
393}
394
Johannes Doerfertf6183392014-07-01 20:52:51 +0000395/// @brief Return the reduction type for a given binary operator
396static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
397 const Instruction *Load) {
398 if (!BinOp)
399 return MemoryAccess::RT_NONE;
400 switch (BinOp->getOpcode()) {
401 case Instruction::FAdd:
402 if (!BinOp->hasUnsafeAlgebra())
403 return MemoryAccess::RT_NONE;
404 // Fall through
405 case Instruction::Add:
406 return MemoryAccess::RT_ADD;
407 case Instruction::Or:
408 return MemoryAccess::RT_BOR;
409 case Instruction::Xor:
410 return MemoryAccess::RT_BXOR;
411 case Instruction::And:
412 return MemoryAccess::RT_BAND;
413 case Instruction::FMul:
414 if (!BinOp->hasUnsafeAlgebra())
415 return MemoryAccess::RT_NONE;
416 // Fall through
417 case Instruction::Mul:
418 if (DisableMultiplicativeReductions)
419 return MemoryAccess::RT_NONE;
420 return MemoryAccess::RT_MUL;
421 default:
422 return MemoryAccess::RT_NONE;
423 }
424}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000425
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000426/// @brief Derive the individual index expressions from a GEP instruction
427///
428/// This function optimistically assumes the GEP references into a fixed size
429/// array. If this is actually true, this function returns a list of array
430/// subscript expressions as SCEV as well as a list of integers describing
431/// the size of the individual array dimensions. Both lists have either equal
432/// length of the size list is one element shorter in case there is no known
433/// size available for the outermost array dimension.
434///
435/// @param GEP The GetElementPtr instruction to analyze.
436///
437/// @return A tuple with the subscript expressions and the dimension sizes.
438static std::tuple<std::vector<const SCEV *>, std::vector<int>>
439getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
440 std::vector<const SCEV *> Subscripts;
441 std::vector<int> Sizes;
442
443 Type *Ty = GEP->getPointerOperandType();
444
445 bool DroppedFirstDim = false;
446
Michael Kruse26ed65e2015-09-24 17:32:49 +0000447 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000448
449 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
450
451 if (i == 1) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000452 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000453 Ty = PtrTy->getElementType();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000454 } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000455 Ty = ArrayTy->getElementType();
456 } else {
457 Subscripts.clear();
458 Sizes.clear();
459 break;
460 }
Johannes Doerferta90943d2016-02-21 16:37:25 +0000461 if (auto *Const = dyn_cast<SCEVConstant>(Expr))
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000462 if (Const->getValue()->isZero()) {
463 DroppedFirstDim = true;
464 continue;
465 }
466 Subscripts.push_back(Expr);
467 continue;
468 }
469
Johannes Doerferta90943d2016-02-21 16:37:25 +0000470 auto *ArrayTy = dyn_cast<ArrayType>(Ty);
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000471 if (!ArrayTy) {
472 Subscripts.clear();
473 Sizes.clear();
474 break;
475 }
476
477 Subscripts.push_back(Expr);
478 if (!(DroppedFirstDim && i == 2))
479 Sizes.push_back(ArrayTy->getNumElements());
480
481 Ty = ArrayTy->getElementType();
482 }
483
484 return std::make_tuple(Subscripts, Sizes);
485}
486
Tobias Grosser75805372011-04-29 06:27:02 +0000487MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000488 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000489 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000490 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000491}
492
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000493const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
494 isl_id *ArrayId = getArrayId();
495 void *User = isl_id_get_user(ArrayId);
496 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
497 isl_id_free(ArrayId);
498 return SAI;
499}
500
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000501__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000502 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
503}
504
Tobias Grosserd840fc72016-02-04 13:18:42 +0000505__isl_give isl_map *MemoryAccess::getAddressFunction() const {
506 return isl_map_lexmin(getAccessRelation());
507}
508
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000509__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
510 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000511 isl_map *Schedule, *ScheduledAccRel;
512 isl_union_set *UDomain;
513
514 UDomain = isl_union_set_from_set(getStatement()->getDomain());
515 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
516 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000517 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000518 return isl_pw_multi_aff_from_map(ScheduledAccRel);
519}
520
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000521__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000522 return isl_map_copy(AccessRelation);
523}
524
Johannes Doerferta99130f2014-10-13 12:58:03 +0000525std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000526 return stringFromIslObj(AccessRelation);
527}
528
Johannes Doerferta99130f2014-10-13 12:58:03 +0000529__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000530 return isl_map_get_space(AccessRelation);
531}
532
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000533__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000534 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000535}
536
Tobias Grosser6f730082015-09-05 07:46:47 +0000537std::string MemoryAccess::getNewAccessRelationStr() const {
538 return stringFromIslObj(NewAccessRelation);
539}
540
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000541__isl_give isl_basic_map *
542MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000543 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000544 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000545
Tobias Grosser084d8f72012-05-29 09:29:44 +0000546 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000547 isl_basic_set_universe(Statement->getDomainSpace()),
548 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000549}
550
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000551// Formalize no out-of-bound access assumption
552//
553// When delinearizing array accesses we optimistically assume that the
554// delinearized accesses do not access out of bound locations (the subscript
555// expression of each array evaluates for each statement instance that is
556// executed to a value that is larger than zero and strictly smaller than the
557// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000558// dimension for which we do not need to assume any upper bound. At this point
559// we formalize this assumption to ensure that at code generation time the
560// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000561//
562// To find the set of constraints necessary to avoid out of bound accesses, we
563// first build the set of data locations that are not within array bounds. We
564// then apply the reverse access relation to obtain the set of iterations that
565// may contain invalid accesses and reduce this set of iterations to the ones
566// that are actually executed by intersecting them with the domain of the
567// statement. If we now project out all loop dimensions, we obtain a set of
568// parameters that may cause statement instances to be executed that may
569// possibly yield out of bound memory accesses. The complement of these
570// constraints is the set of constraints that needs to be assumed to ensure such
571// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000572void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000573 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000574 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000575 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000576 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000577 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
578 isl_pw_aff *Var =
579 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
580 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
581
582 isl_set *DimOutside;
583
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000584 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000585 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000586 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
587 isl_space_dim(Space, isl_dim_set));
588 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
589 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000590
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000591 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000592
593 Outside = isl_set_union(Outside, DimOutside);
594 }
595
596 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
597 Outside = isl_set_intersect(Outside, Statement->getDomain());
598 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000599
600 // Remove divs to avoid the construction of overly complicated assumptions.
601 // Doing so increases the set of parameter combinations that are assumed to
602 // not appear. This is always save, but may make the resulting run-time check
603 // bail out more often than strictly necessary.
604 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000605 Outside = isl_set_complement(Outside);
Johannes Doerfert066dbf32016-03-01 13:06:28 +0000606 auto &Loc = getAccessInstruction() ? getAccessInstruction()->getDebugLoc()
607 : DebugLoc();
608 Statement->getParent()->addAssumption(INBOUNDS, Outside, Loc, AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000609 isl_space_free(Space);
610}
611
Johannes Doerfertcea61932016-02-21 19:13:19 +0000612void MemoryAccess::buildMemIntrinsicAccessRelation() {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000613 assert(isa<MemIntrinsic>(getAccessInstruction()));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000614 assert(Subscripts.size() == 2 && Sizes.size() == 0);
615
Johannes Doerfertcea61932016-02-21 19:13:19 +0000616 auto *SubscriptPWA = Statement->getPwAff(Subscripts[0]);
617 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000618
619 isl_map *LengthMap;
620 if (Subscripts[1] == nullptr) {
621 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
622 } else {
623 auto *LengthPWA = Statement->getPwAff(Subscripts[1]);
624 LengthMap = isl_map_from_pw_aff(LengthPWA);
625 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
626 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
627 }
628 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
629 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000630 SubscriptMap =
631 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000632 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
633 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
634 getStatement()->getDomainId());
635}
636
Johannes Doerferte7044942015-02-24 11:58:30 +0000637void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
638 ScalarEvolution *SE = Statement->getParent()->getSE();
639
Johannes Doerfertcea61932016-02-21 19:13:19 +0000640 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000641 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000642 return;
643
644 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000645 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
646 return;
647
648 auto *PtrSCEV = SE->getSCEV(Ptr);
649 if (isa<SCEVCouldNotCompute>(PtrSCEV))
650 return;
651
652 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
653 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
654 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
655
656 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
657 if (Range.isFullSet())
658 return;
659
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000660 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000661 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000662 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000663 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000664 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000665
666 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000667 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000668
669 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
670 AccessRange =
671 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
672 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
673}
674
Michael Krusee2bccbb2015-09-18 19:59:43 +0000675__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000676 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000677 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000678
679 for (int i = Size - 2; i >= 0; --i) {
680 isl_space *Space;
681 isl_map *MapOne, *MapTwo;
Michael Krusee2bccbb2015-09-18 19:59:43 +0000682 isl_pw_aff *DimSize = Statement->getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000683
684 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
685 isl_pw_aff_free(DimSize);
686 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
687
688 Space = isl_map_get_space(AccessRelation);
689 Space = isl_space_map_from_set(isl_space_range(Space));
690 Space = isl_space_align_params(Space, SpaceSize);
691
692 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
693 isl_id_free(ParamId);
694
695 MapOne = isl_map_universe(isl_space_copy(Space));
696 for (int j = 0; j < Size; ++j)
697 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
698 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
699
700 MapTwo = isl_map_universe(isl_space_copy(Space));
701 for (int j = 0; j < Size; ++j)
702 if (j < i || j > i + 1)
703 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
704
705 isl_local_space *LS = isl_local_space_from_space(Space);
706 isl_constraint *C;
707 C = isl_equality_alloc(isl_local_space_copy(LS));
708 C = isl_constraint_set_constant_si(C, -1);
709 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
710 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
711 MapTwo = isl_map_add_constraint(MapTwo, C);
712 C = isl_equality_alloc(LS);
713 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
714 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
715 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
716 MapTwo = isl_map_add_constraint(MapTwo, C);
717 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
718
719 MapOne = isl_map_union(MapOne, MapTwo);
720 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
721 }
722 return AccessRelation;
723}
724
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000725/// @brief Check if @p Expr is divisible by @p Size.
726static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000727 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000728 if (Size == 1)
729 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000730
731 // Only one factor needs to be divisible.
732 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
733 for (auto *FactorExpr : MulExpr->operands())
734 if (isDivisible(FactorExpr, Size, SE))
735 return true;
736 return false;
737 }
738
739 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
740 // to be divisble.
741 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
742 for (auto *OpExpr : NAryExpr->operands())
743 if (!isDivisible(OpExpr, Size, SE))
744 return false;
745 return true;
746 }
747
748 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
749 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
750 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
751 return MulSCEV == Expr;
752}
753
Michael Krusee2bccbb2015-09-18 19:59:43 +0000754void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
755 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000756
Michael Krusee2bccbb2015-09-18 19:59:43 +0000757 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000758 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000759
Michael Krusee2bccbb2015-09-18 19:59:43 +0000760 if (!isAffine()) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000761 if (isa<MemIntrinsic>(getAccessInstruction()))
762 buildMemIntrinsicAccessRelation();
763
Tobias Grosser4f967492013-06-23 05:21:18 +0000764 // We overapproximate non-affine accesses with a possible access to the
765 // whole array. For read accesses it does not make a difference, if an
766 // access must or may happen. However, for write accesses it is important to
767 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000768 if (!AccessRelation)
769 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
770
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000771 AccessRelation =
772 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000773 return;
774 }
775
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000776 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000777 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000778
Michael Krusee2bccbb2015-09-18 19:59:43 +0000779 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
780 isl_pw_aff *Affine = Statement->getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000781 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000782 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000783 }
784
Tobias Grosser5d51afe2016-02-02 16:46:45 +0000785 if (Sizes.size() >= 1 && !isa<SCEVConstant>(Sizes[0]))
Michael Krusee2bccbb2015-09-18 19:59:43 +0000786 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000787
Tobias Grosser79baa212014-04-10 08:38:02 +0000788 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000789 AccessRelation = isl_map_set_tuple_id(
790 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000791 AccessRelation =
792 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
793
Tobias Grosseraa660a92015-03-30 00:07:50 +0000794 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000795 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000796}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000797
Michael Krusecac948e2015-10-02 13:53:07 +0000798MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000799 AccessType AccType, Value *BaseAddress,
800 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000801 ArrayRef<const SCEV *> Subscripts,
802 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000803 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000804 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
805 BaseAddr(BaseAddress), BaseName(BaseName), ElementType(ElementType),
Michael Krusecac948e2015-10-02 13:53:07 +0000806 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
807 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000808 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000809 NewAccessRelation(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000810 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Johannes Doerfertcea61932016-02-21 19:13:19 +0000811 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000812
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000813 std::string IdName =
814 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000815 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
816}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000817
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000818void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000819 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000820 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000821}
822
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000823const std::string MemoryAccess::getReductionOperatorStr() const {
824 return MemoryAccess::getReductionOperatorStr(getReductionType());
825}
826
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000827__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
828
Johannes Doerfertf6183392014-07-01 20:52:51 +0000829raw_ostream &polly::operator<<(raw_ostream &OS,
830 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000831 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000832 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000833 else
834 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000835 return OS;
836}
837
Tobias Grosser75805372011-04-29 06:27:02 +0000838void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000839 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000840 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000841 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000842 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000843 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000844 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000845 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000846 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000847 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000848 break;
849 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000850 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000851 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000852 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000853 if (hasNewAccessRelation())
854 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000855}
856
Tobias Grosser74394f02013-01-14 22:40:23 +0000857void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000858
859// Create a map in the size of the provided set domain, that maps from the
860// one element of the provided set domain to another element of the provided
861// set domain.
862// The mapping is limited to all points that are equal in all but the last
863// dimension and for which the last dimension of the input is strict smaller
864// than the last dimension of the output.
865//
866// getEqualAndLarger(set[i0, i1, ..., iX]):
867//
868// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
869// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
870//
Tobias Grosserf5338802011-10-06 00:03:35 +0000871static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000872 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000873 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000874 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000875
876 // Set all but the last dimension to be equal for the input and output
877 //
878 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
879 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000880 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000881 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000882
883 // Set the last dimension of the input to be strict smaller than the
884 // last dimension of the output.
885 //
886 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000887 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
888 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000889 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000890}
891
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000892__isl_give isl_set *
893MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000894 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000895 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000896 isl_space *Space = isl_space_range(isl_map_get_space(S));
897 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000898
Sebastian Popa00a0292012-12-18 07:46:06 +0000899 S = isl_map_reverse(S);
900 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000901
Sebastian Popa00a0292012-12-18 07:46:06 +0000902 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
903 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
904 NextScatt = isl_map_apply_domain(NextScatt, S);
905 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000906
Sebastian Popa00a0292012-12-18 07:46:06 +0000907 isl_set *Deltas = isl_map_deltas(NextScatt);
908 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000909}
910
Sebastian Popa00a0292012-12-18 07:46:06 +0000911bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000912 int StrideWidth) const {
913 isl_set *Stride, *StrideX;
914 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000915
Sebastian Popa00a0292012-12-18 07:46:06 +0000916 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000917 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000918 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
919 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
920 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
921 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000922 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000923
Tobias Grosser28dd4862012-01-24 16:42:16 +0000924 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000925 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000926
Tobias Grosser28dd4862012-01-24 16:42:16 +0000927 return IsStrideX;
928}
929
Sebastian Popa00a0292012-12-18 07:46:06 +0000930bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
931 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000932}
933
Sebastian Popa00a0292012-12-18 07:46:06 +0000934bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
935 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000936}
937
Tobias Grosser166c4222015-09-05 07:46:40 +0000938void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
939 isl_map_free(NewAccessRelation);
940 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000941}
Tobias Grosser75805372011-04-29 06:27:02 +0000942
943//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000944
Tobias Grosser808cd692015-07-14 09:33:13 +0000945isl_map *ScopStmt::getSchedule() const {
946 isl_set *Domain = getDomain();
947 if (isl_set_is_empty(Domain)) {
948 isl_set_free(Domain);
949 return isl_map_from_aff(
950 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
951 }
952 auto *Schedule = getParent()->getSchedule();
953 Schedule = isl_union_map_intersect_domain(
954 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
955 if (isl_union_map_is_empty(Schedule)) {
956 isl_set_free(Domain);
957 isl_union_map_free(Schedule);
958 return isl_map_from_aff(
959 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
960 }
961 auto *M = isl_map_from_union_map(Schedule);
962 M = isl_map_coalesce(M);
963 M = isl_map_gist_domain(M, Domain);
964 M = isl_map_coalesce(M);
965 return M;
966}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000967
Johannes Doerfert574182d2015-08-12 10:19:50 +0000968__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Michael Kruse375cb5f2016-02-24 22:08:24 +0000969 return getParent()->getPwAff(E, getEntryBlock());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000970}
971
Tobias Grosser37eb4222014-02-20 21:43:54 +0000972void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
973 assert(isl_set_is_subset(NewDomain, Domain) &&
974 "New domain is not a subset of old domain!");
975 isl_set_free(Domain);
976 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000977}
978
Michael Krusecac948e2015-10-02 13:53:07 +0000979void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000980 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +0000981 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000982 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000983
Tobias Grossera535dff2015-12-13 19:59:01 +0000984 ScopArrayInfo::MemoryKind Ty;
985 if (Access->isPHIKind())
986 Ty = ScopArrayInfo::MK_PHI;
987 else if (Access->isExitPHIKind())
988 Ty = ScopArrayInfo::MK_ExitPHI;
989 else if (Access->isValueKind())
990 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000991 else
Tobias Grossera535dff2015-12-13 19:59:01 +0000992 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000993
Johannes Doerfertadeab372016-02-07 13:57:32 +0000994 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
995 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +0000996 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +0000997 }
998}
999
Michael Krusecac948e2015-10-02 13:53:07 +00001000void ScopStmt::addAccess(MemoryAccess *Access) {
1001 Instruction *AccessInst = Access->getAccessInstruction();
1002
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001003 if (Access->isArrayKind()) {
1004 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1005 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001006 } else if (Access->isValueKind() && Access->isWrite()) {
1007 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001008 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001009 assert(!ValueWrites.lookup(AccessVal));
1010
1011 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001012 } else if (Access->isValueKind() && Access->isRead()) {
1013 Value *AccessVal = Access->getAccessValue();
1014 assert(!ValueReads.lookup(AccessVal));
1015
1016 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001017 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1018 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
1019 assert(!PHIWrites.lookup(PHI));
1020
1021 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001022 }
1023
1024 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001025}
1026
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001027void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001028 for (MemoryAccess *MA : *this)
1029 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001030
1031 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001032}
1033
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001034/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
1035static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1036 void *User) {
1037 isl_set **BoundedParts = static_cast<isl_set **>(User);
1038 if (isl_basic_set_is_bounded(BSet))
1039 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1040 else
1041 isl_basic_set_free(BSet);
1042 return isl_stat_ok;
1043}
1044
1045/// @brief Return the bounded parts of @p S.
1046static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1047 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1048 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1049 isl_set_free(S);
1050 return BoundedParts;
1051}
1052
1053/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
1054///
1055/// @returns A separation of @p S into first an unbounded then a bounded subset,
1056/// both with regards to the dimension @p Dim.
1057static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1058partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1059
1060 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001061 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001062
1063 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001064 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001065
1066 // Remove dimensions that are greater than Dim as they are not interesting.
1067 assert(NumDimsS >= Dim + 1);
1068 OnlyDimS =
1069 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1070
1071 // Create artificial parametric upper bounds for dimensions smaller than Dim
1072 // as we are not interested in them.
1073 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1074 for (unsigned u = 0; u < Dim; u++) {
1075 isl_constraint *C = isl_inequality_alloc(
1076 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1077 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1078 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1079 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1080 }
1081
1082 // Collect all bounded parts of OnlyDimS.
1083 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1084
1085 // Create the dimensions greater than Dim again.
1086 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1087 NumDimsS - Dim - 1);
1088
1089 // Remove the artificial upper bound parameters again.
1090 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1091
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001092 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001093 return std::make_pair(UnboundedParts, BoundedParts);
1094}
1095
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001096/// @brief Set the dimension Ids from @p From in @p To.
1097static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1098 __isl_take isl_set *To) {
1099 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1100 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1101 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1102 }
1103 return To;
1104}
1105
1106/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001107static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001108 __isl_take isl_pw_aff *L,
1109 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001110 switch (Pred) {
1111 case ICmpInst::ICMP_EQ:
1112 return isl_pw_aff_eq_set(L, R);
1113 case ICmpInst::ICMP_NE:
1114 return isl_pw_aff_ne_set(L, R);
1115 case ICmpInst::ICMP_SLT:
1116 return isl_pw_aff_lt_set(L, R);
1117 case ICmpInst::ICMP_SLE:
1118 return isl_pw_aff_le_set(L, R);
1119 case ICmpInst::ICMP_SGT:
1120 return isl_pw_aff_gt_set(L, R);
1121 case ICmpInst::ICMP_SGE:
1122 return isl_pw_aff_ge_set(L, R);
1123 case ICmpInst::ICMP_ULT:
1124 return isl_pw_aff_lt_set(L, R);
1125 case ICmpInst::ICMP_UGT:
1126 return isl_pw_aff_gt_set(L, R);
1127 case ICmpInst::ICMP_ULE:
1128 return isl_pw_aff_le_set(L, R);
1129 case ICmpInst::ICMP_UGE:
1130 return isl_pw_aff_ge_set(L, R);
1131 default:
1132 llvm_unreachable("Non integer predicate not supported");
1133 }
1134}
1135
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001136/// @brief Create the conditions under which @p L @p Pred @p R is true.
1137///
1138/// Helper function that will make sure the dimensions of the result have the
1139/// same isl_id's as the @p Domain.
1140static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1141 __isl_take isl_pw_aff *L,
1142 __isl_take isl_pw_aff *R,
1143 __isl_keep isl_set *Domain) {
1144 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1145 return setDimensionIds(Domain, ConsequenceCondSet);
1146}
1147
1148/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001149///
1150/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001151/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1152/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001153static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001154buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001155 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1156
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001157 Value *Condition = getConditionFromTerminator(SI);
1158 assert(Condition && "No condition for switch");
1159
1160 ScalarEvolution &SE = *S.getSE();
1161 BasicBlock *BB = SI->getParent();
1162 isl_pw_aff *LHS, *RHS;
1163 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
1164
1165 unsigned NumSuccessors = SI->getNumSuccessors();
1166 ConditionSets.resize(NumSuccessors);
1167 for (auto &Case : SI->cases()) {
1168 unsigned Idx = Case.getSuccessorIndex();
1169 ConstantInt *CaseValue = Case.getCaseValue();
1170
1171 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
1172 isl_set *CaseConditionSet =
1173 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1174 ConditionSets[Idx] = isl_set_coalesce(
1175 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1176 }
1177
1178 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1179 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1180 for (unsigned u = 2; u < NumSuccessors; u++)
1181 ConditionSetUnion =
1182 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1183 ConditionSets[0] = setDimensionIds(
1184 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1185
1186 S.markAsOptimized();
1187 isl_pw_aff_free(LHS);
1188}
1189
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001190/// @brief Build the conditions sets for the branch condition @p Condition in
1191/// the @p Domain.
1192///
1193/// This will fill @p ConditionSets with the conditions under which control
1194/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001195/// have as many elements as @p TI has successors. If @p TI is nullptr the
1196/// context under which @p Condition is true/false will be returned as the
1197/// new elements of @p ConditionSets.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001198static void
1199buildConditionSets(Scop &S, Value *Condition, TerminatorInst *TI, Loop *L,
1200 __isl_keep isl_set *Domain,
1201 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1202
1203 isl_set *ConsequenceCondSet = nullptr;
1204 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1205 if (CCond->isZero())
1206 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1207 else
1208 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1209 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1210 auto Opcode = BinOp->getOpcode();
1211 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1212
1213 buildConditionSets(S, BinOp->getOperand(0), TI, L, Domain, ConditionSets);
1214 buildConditionSets(S, BinOp->getOperand(1), TI, L, Domain, ConditionSets);
1215
1216 isl_set_free(ConditionSets.pop_back_val());
1217 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1218 isl_set_free(ConditionSets.pop_back_val());
1219 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1220
1221 if (Opcode == Instruction::And)
1222 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1223 else
1224 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1225 } else {
1226 auto *ICond = dyn_cast<ICmpInst>(Condition);
1227 assert(ICond &&
1228 "Condition of exiting branch was neither constant nor ICmp!");
1229
1230 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001231 BasicBlock *BB = TI ? TI->getParent() : nullptr;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001232 isl_pw_aff *LHS, *RHS;
1233 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1234 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
1235 ConsequenceCondSet =
1236 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1237 }
1238
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001239 // If no terminator was given we are only looking for parameter constraints
1240 // under which @p Condition is true/false.
1241 if (!TI)
1242 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
1243
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001244 assert(ConsequenceCondSet);
1245 isl_set *AlternativeCondSet =
1246 isl_set_complement(isl_set_copy(ConsequenceCondSet));
1247
1248 ConditionSets.push_back(isl_set_coalesce(
1249 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
1250 ConditionSets.push_back(isl_set_coalesce(
1251 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
1252}
1253
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001254/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1255///
1256/// This will fill @p ConditionSets with the conditions under which control
1257/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1258/// have as many elements as @p TI has successors.
1259static void
1260buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1261 __isl_keep isl_set *Domain,
1262 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1263
1264 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1265 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1266
1267 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1268
1269 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001270 ConditionSets.push_back(isl_set_copy(Domain));
1271 return;
1272 }
1273
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001274 Value *Condition = getConditionFromTerminator(TI);
1275 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001276
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001277 return buildConditionSets(S, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001278}
1279
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001280void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001281 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001282
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001283 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001284 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001285}
1286
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001287void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP,
1288 ScopDetection &SD) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001289 isl_ctx *Ctx = Parent.getIslCtx();
1290 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1291 Type *Ty = GEP->getPointerOperandType();
1292 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001293
1294 // The set of loads that are required to be invariant.
1295 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001296
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001297 std::vector<const SCEV *> Subscripts;
1298 std::vector<int> Sizes;
1299
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001300 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001301
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001302 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001303 Ty = PtrTy->getElementType();
1304 }
1305
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001306 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001307
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001308 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001309
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001310 auto *NotExecuted = isl_set_complement(isl_set_params(getDomain()));
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001311 for (size_t i = 0; i < Sizes.size(); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001312 auto *Expr = Subscripts[i + IndexOffset];
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001313 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001314
Michael Kruse09eb4452016-03-03 22:10:47 +00001315 auto *Scope = SD.getLI()->getLoopFor(getEntryBlock());
Johannes Doerfert09e36972015-10-07 20:17:36 +00001316 InvariantLoadsSetTy AccessILS;
Michael Kruse09eb4452016-03-03 22:10:47 +00001317 if (!isAffineExpr(&Parent.getRegion(), Scope, Expr, SE, nullptr,
1318 &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +00001319 continue;
1320
1321 bool NonAffine = false;
1322 for (LoadInst *LInst : AccessILS)
1323 if (!ScopRIL.count(LInst))
1324 NonAffine = true;
1325
1326 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001327 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001328
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001329 isl_pw_aff *AccessOffset = getPwAff(Expr);
1330 AccessOffset =
1331 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001332
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001333 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1334 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001335
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001336 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1337 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1338 OutOfBound = isl_set_params(OutOfBound);
1339 isl_set *InBound = isl_set_complement(OutOfBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001340
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001341 // A => B == !A or B
1342 isl_set *InBoundIfExecuted =
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001343 isl_set_union(isl_set_copy(NotExecuted), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001344
Roman Gareev10595a12016-01-08 14:01:59 +00001345 InBoundIfExecuted = isl_set_coalesce(InBoundIfExecuted);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001346 Parent.addAssumption(INBOUNDS, InBoundIfExecuted, GEP->getDebugLoc(),
1347 AS_ASSUMPTION);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001348 }
1349
1350 isl_local_space_free(LSpace);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001351 isl_set_free(NotExecuted);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001352}
1353
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001354void ScopStmt::deriveAssumptions(BasicBlock *Block, ScopDetection &SD) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001355 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001356 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001357 deriveAssumptionsFromGEP(GEP, SD);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001358}
1359
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001360void ScopStmt::collectSurroundingLoops() {
1361 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1362 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1363 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1364 isl_id_free(DimId);
1365 }
1366}
1367
Michael Kruse9d080092015-09-11 21:41:48 +00001368ScopStmt::ScopStmt(Scop &parent, Region &R)
Michael Krusecac948e2015-10-02 13:53:07 +00001369 : Parent(parent), Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001370
Tobias Grosser16c44032015-07-09 07:31:45 +00001371 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001372}
1373
Michael Kruse9d080092015-09-11 21:41:48 +00001374ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Michael Krusecac948e2015-10-02 13:53:07 +00001375 : Parent(parent), Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001376
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001377 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001378}
1379
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001380void ScopStmt::init(ScopDetection &SD) {
Michael Krusecac948e2015-10-02 13:53:07 +00001381 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001382
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001383 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001384 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001385 buildAccessRelations();
1386
1387 if (BB) {
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001388 deriveAssumptions(BB, SD);
Michael Krusecac948e2015-10-02 13:53:07 +00001389 } else {
1390 for (BasicBlock *Block : R->blocks()) {
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001391 deriveAssumptions(Block, SD);
Michael Krusecac948e2015-10-02 13:53:07 +00001392 }
1393 }
1394
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001395 if (DetectReductions)
1396 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001397}
1398
Johannes Doerferte58a0122014-06-27 20:31:28 +00001399/// @brief Collect loads which might form a reduction chain with @p StoreMA
1400///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001401/// Check if the stored value for @p StoreMA is a binary operator with one or
1402/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001403/// used only once (by @p StoreMA) and its load operands are also used only
1404/// once, we have found a possible reduction chain. It starts at an operand
1405/// load and includes the binary operator and @p StoreMA.
1406///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001407/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001408/// escape this block or into any other store except @p StoreMA.
1409void ScopStmt::collectCandiateReductionLoads(
1410 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1411 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1412 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001413 return;
1414
1415 // Skip if there is not one binary operator between the load and the store
1416 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001417 if (!BinOp)
1418 return;
1419
1420 // Skip if the binary operators has multiple uses
1421 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001422 return;
1423
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001424 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001425 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1426 return;
1427
Johannes Doerfert9890a052014-07-01 00:32:29 +00001428 // Skip if the binary operator is outside the current SCoP
1429 if (BinOp->getParent() != Store->getParent())
1430 return;
1431
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001432 // Skip if it is a multiplicative reduction and we disabled them
1433 if (DisableMultiplicativeReductions &&
1434 (BinOp->getOpcode() == Instruction::Mul ||
1435 BinOp->getOpcode() == Instruction::FMul))
1436 return;
1437
Johannes Doerferte58a0122014-06-27 20:31:28 +00001438 // Check the binary operator operands for a candidate load
1439 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1440 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1441 if (!PossibleLoad0 && !PossibleLoad1)
1442 return;
1443
1444 // A load is only a candidate if it cannot escape (thus has only this use)
1445 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001446 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001447 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001448 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001449 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001450 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001451}
1452
1453/// @brief Check for reductions in this ScopStmt
1454///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001455/// Iterate over all store memory accesses and check for valid binary reduction
1456/// like chains. For all candidates we check if they have the same base address
1457/// and there are no other accesses which overlap with them. The base address
1458/// check rules out impossible reductions candidates early. The overlap check,
1459/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001460/// guarantees that none of the intermediate results will escape during
1461/// execution of the loop nest. We basically check here that no other memory
1462/// access can access the same memory as the potential reduction.
1463void ScopStmt::checkForReductions() {
1464 SmallVector<MemoryAccess *, 2> Loads;
1465 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1466
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001467 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001468 // stores and collecting possible reduction loads.
1469 for (MemoryAccess *StoreMA : MemAccs) {
1470 if (StoreMA->isRead())
1471 continue;
1472
1473 Loads.clear();
1474 collectCandiateReductionLoads(StoreMA, Loads);
1475 for (MemoryAccess *LoadMA : Loads)
1476 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1477 }
1478
1479 // Then check each possible candidate pair.
1480 for (const auto &CandidatePair : Candidates) {
1481 bool Valid = true;
1482 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1483 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1484
1485 // Skip those with obviously unequal base addresses.
1486 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1487 isl_map_free(LoadAccs);
1488 isl_map_free(StoreAccs);
1489 continue;
1490 }
1491
1492 // And check if the remaining for overlap with other memory accesses.
1493 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1494 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1495 isl_set *AllAccs = isl_map_range(AllAccsRel);
1496
1497 for (MemoryAccess *MA : MemAccs) {
1498 if (MA == CandidatePair.first || MA == CandidatePair.second)
1499 continue;
1500
1501 isl_map *AccRel =
1502 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1503 isl_set *Accs = isl_map_range(AccRel);
1504
1505 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1506 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1507 Valid = Valid && isl_set_is_empty(OverlapAccs);
1508 isl_set_free(OverlapAccs);
1509 }
1510 }
1511
1512 isl_set_free(AllAccs);
1513 if (!Valid)
1514 continue;
1515
Johannes Doerfertf6183392014-07-01 20:52:51 +00001516 const LoadInst *Load =
1517 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1518 MemoryAccess::ReductionType RT =
1519 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1520
Johannes Doerferte58a0122014-06-27 20:31:28 +00001521 // If no overlapping access was found we mark the load and store as
1522 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001523 CandidatePair.first->markAsReductionLike(RT);
1524 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001525 }
Tobias Grosser75805372011-04-29 06:27:02 +00001526}
1527
Tobias Grosser74394f02013-01-14 22:40:23 +00001528std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001529
Tobias Grosser54839312015-04-21 11:37:25 +00001530std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001531 auto *S = getSchedule();
1532 auto Str = stringFromIslObj(S);
1533 isl_map_free(S);
1534 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001535}
1536
Michael Kruse375cb5f2016-02-24 22:08:24 +00001537BasicBlock *ScopStmt::getEntryBlock() const {
1538 if (isBlockStmt())
1539 return getBasicBlock();
1540 return getRegion()->getEntry();
1541}
1542
Michael Kruse7b5caa42016-02-24 22:08:28 +00001543RegionNode *ScopStmt::getRegionNode() const {
1544 if (isRegionStmt())
1545 return getRegion()->getNode();
1546 return getParent()->getRegion().getBBNode(getBasicBlock());
1547}
1548
Tobias Grosser74394f02013-01-14 22:40:23 +00001549unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001550
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001551unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001552
Tobias Grosser75805372011-04-29 06:27:02 +00001553const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1554
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001555const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001556 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001557}
1558
Tobias Grosser74394f02013-01-14 22:40:23 +00001559isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001560
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001561__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001562
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001563__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001564 return isl_set_get_space(Domain);
1565}
1566
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001567__isl_give isl_id *ScopStmt::getDomainId() const {
1568 return isl_set_get_tuple_id(Domain);
1569}
Tobias Grossercd95b772012-08-30 11:49:38 +00001570
Tobias Grosser10120182015-12-16 16:14:03 +00001571ScopStmt::~ScopStmt() { isl_set_free(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001572
1573void ScopStmt::print(raw_ostream &OS) const {
1574 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001575 OS.indent(12) << "Domain :=\n";
1576
1577 if (Domain) {
1578 OS.indent(16) << getDomainStr() << ";\n";
1579 } else
1580 OS.indent(16) << "n/a\n";
1581
Tobias Grosser54839312015-04-21 11:37:25 +00001582 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001583
1584 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001585 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001586 } else
1587 OS.indent(16) << "n/a\n";
1588
Tobias Grosser083d3d32014-06-28 08:59:45 +00001589 for (MemoryAccess *Access : MemAccs)
1590 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001591}
1592
1593void ScopStmt::dump() const { print(dbgs()); }
1594
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001595void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001596 // Remove all memory accesses in @p InvMAs from this statement
1597 // together with all scalar accesses that were caused by them.
Michael Krusead28e5a2016-01-26 13:33:15 +00001598 // MK_Value READs have no access instruction, hence would not be removed by
1599 // this function. However, it is only used for invariant LoadInst accesses,
1600 // its arguments are always affine, hence synthesizable, and therefore there
1601 // are no MK_Value READ accesses to be removed.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001602 for (MemoryAccess *MA : InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001603 auto Predicate = [&](MemoryAccess *Acc) {
Tobias Grosser3a6ac9f2015-11-30 21:13:43 +00001604 return Acc->getAccessInstruction() == MA->getAccessInstruction();
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001605 };
1606 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1607 MemAccs.end());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001608 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001609 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001610}
1611
Tobias Grosser75805372011-04-29 06:27:02 +00001612//===----------------------------------------------------------------------===//
1613/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001614
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001615void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001616 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1617 isl_set_free(Context);
1618 Context = NewContext;
1619}
1620
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001621/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1622struct SCEVSensitiveParameterRewriter
1623 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1624 ValueToValueMap &VMap;
1625 ScalarEvolution &SE;
1626
1627public:
1628 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1629 : VMap(VMap), SE(SE) {}
1630
1631 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1632 ValueToValueMap &VMap) {
1633 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1634 return SSPR.visit(E);
1635 }
1636
1637 const SCEV *visit(const SCEV *E) {
1638 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1639 }
1640
1641 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1642
1643 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1644 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1645 }
1646
1647 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1648 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1649 }
1650
1651 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1652 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1653 }
1654
1655 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1656 SmallVector<const SCEV *, 4> Operands;
1657 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1658 Operands.push_back(visit(E->getOperand(i)));
1659 return SE.getAddExpr(Operands);
1660 }
1661
1662 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1663 SmallVector<const SCEV *, 4> Operands;
1664 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1665 Operands.push_back(visit(E->getOperand(i)));
1666 return SE.getMulExpr(Operands);
1667 }
1668
1669 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1670 SmallVector<const SCEV *, 4> Operands;
1671 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1672 Operands.push_back(visit(E->getOperand(i)));
1673 return SE.getSMaxExpr(Operands);
1674 }
1675
1676 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1677 SmallVector<const SCEV *, 4> Operands;
1678 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1679 Operands.push_back(visit(E->getOperand(i)));
1680 return SE.getUMaxExpr(Operands);
1681 }
1682
1683 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1684 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1685 }
1686
1687 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1688 auto *Start = visit(E->getStart());
1689 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1690 visit(E->getStepRecurrence(SE)),
1691 E->getLoop(), SCEV::FlagAnyWrap);
1692 return SE.getAddExpr(Start, AddRec);
1693 }
1694
1695 const SCEV *visitUnknown(const SCEVUnknown *E) {
1696 if (auto *NewValue = VMap.lookup(E->getValue()))
1697 return SE.getUnknown(NewValue);
1698 return E;
1699 }
1700};
1701
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001702const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001703 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001704}
1705
Tobias Grosserabfbe632013-02-05 12:09:06 +00001706void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001707 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001708 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001709
1710 // Normalize the SCEV to get the representing element for an invariant load.
1711 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1712
Tobias Grosser60b54f12011-11-08 15:41:28 +00001713 if (ParameterIds.find(Parameter) != ParameterIds.end())
1714 continue;
1715
1716 int dimension = Parameters.size();
1717
1718 Parameters.push_back(Parameter);
1719 ParameterIds[Parameter] = dimension;
1720 }
1721}
1722
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001723__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001724 // Normalize the SCEV to get the representing element for an invariant load.
1725 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1726
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001727 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001728
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001729 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001730 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001731
Tobias Grosser8f99c162011-11-15 11:38:55 +00001732 std::string ParameterName;
1733
Craig Topper7fb6e472016-01-31 20:36:20 +00001734 ParameterName = "p_" + utostr(IdIter->second);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001735
Tobias Grosser8f99c162011-11-15 11:38:55 +00001736 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1737 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001738
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001739 // If this parameter references a specific Value and this value has a name
1740 // we use this name as it is likely to be unique and more useful than just
1741 // a number.
1742 if (Val->hasName())
1743 ParameterName = Val->getName();
1744 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001745 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001746 if (LoadOrigin->hasName()) {
1747 ParameterName += "_loaded_from_";
1748 ParameterName +=
1749 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1750 }
1751 }
1752 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001753
Tobias Grosser20532b82014-04-11 17:56:49 +00001754 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1755 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001756}
Tobias Grosser75805372011-04-29 06:27:02 +00001757
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001758isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1759 isl_set *DomainContext = isl_union_set_params(getDomains());
1760 return isl_set_intersect_params(C, DomainContext);
1761}
1762
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001763void Scop::addWrappingContext() {
1764 if (IgnoreIntegerWrapping)
Tobias Grosser4927c8e2015-11-24 12:50:02 +00001765 return;
Tobias Grosser4927c8e2015-11-24 12:50:02 +00001766
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001767 auto *WrappingContext = Affinator.getWrappingContext();
1768 addAssumption(WRAPPING, WrappingContext, DebugLoc(), AS_RESTRICTION);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001769}
1770
Hongbin Zheng192f69a2016-02-13 15:12:54 +00001771void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
1772 LoopInfo &LI) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001773 auto *R = &getRegion();
1774 auto &F = *R->getEntry()->getParent();
1775 for (auto &Assumption : AC.assumptions()) {
1776 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1777 if (!CI || CI->getNumArgOperands() != 1)
1778 continue;
1779 if (!DT.dominates(CI->getParent(), R->getEntry()))
1780 continue;
1781
Michael Kruse09eb4452016-03-03 22:10:47 +00001782 auto *L = LI.getLoopFor(CI->getParent());
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001783 auto *Val = CI->getArgOperand(0);
1784 std::vector<const SCEV *> Params;
Michael Kruse09eb4452016-03-03 22:10:47 +00001785 if (!isAffineParamConstraint(Val, R, L, *SE, Params)) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001786 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1787 CI->getDebugLoc(),
1788 "Non-affine user assumption ignored.");
1789 continue;
1790 }
1791
1792 addParams(Params);
1793
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001794 SmallVector<isl_set *, 2> ConditionSets;
1795 buildConditionSets(*this, Val, nullptr, L, Context, ConditionSets);
1796 assert(ConditionSets.size() == 2);
1797 isl_set_free(ConditionSets[1]);
1798
1799 auto *AssumptionCtx = ConditionSets[0];
1800 emitOptimizationRemarkAnalysis(
1801 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1802 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1803 Context = isl_set_intersect(Context, AssumptionCtx);
1804 }
1805}
1806
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001807void Scop::addUserContext() {
1808 if (UserContextStr.empty())
1809 return;
1810
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001811 isl_set *UserContext =
1812 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001813 isl_space *Space = getParamSpace();
1814 if (isl_space_dim(Space, isl_dim_param) !=
1815 isl_set_dim(UserContext, isl_dim_param)) {
1816 auto SpaceStr = isl_space_to_str(Space);
1817 errs() << "Error: the context provided in -polly-context has not the same "
1818 << "number of dimensions than the computed context. Due to this "
1819 << "mismatch, the -polly-context option is ignored. Please provide "
1820 << "the context in the parameter space: " << SpaceStr << ".\n";
1821 free(SpaceStr);
1822 isl_set_free(UserContext);
1823 isl_space_free(Space);
1824 return;
1825 }
1826
1827 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001828 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1829 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001830
1831 if (strcmp(NameContext, NameUserContext) != 0) {
1832 auto SpaceStr = isl_space_to_str(Space);
1833 errs() << "Error: the name of dimension " << i
1834 << " provided in -polly-context "
1835 << "is '" << NameUserContext << "', but the name in the computed "
1836 << "context is '" << NameContext
1837 << "'. Due to this name mismatch, "
1838 << "the -polly-context option is ignored. Please provide "
1839 << "the context in the parameter space: " << SpaceStr << ".\n";
1840 free(SpaceStr);
1841 isl_set_free(UserContext);
1842 isl_space_free(Space);
1843 return;
1844 }
1845
1846 UserContext =
1847 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1848 isl_space_get_dim_id(Space, isl_dim_param, i));
1849 }
1850
1851 Context = isl_set_intersect(Context, UserContext);
1852 isl_space_free(Space);
1853}
1854
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001855void Scop::buildInvariantEquivalenceClasses(ScopDetection &SD) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00001856 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001857
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001858 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001859 for (LoadInst *LInst : RIL) {
1860 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1861
Johannes Doerfert96e54712016-02-07 17:30:13 +00001862 Type *Ty = LInst->getType();
1863 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001864 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001865 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001866 continue;
1867 }
1868
1869 ClassRep = LInst;
Johannes Doerfert96e54712016-02-07 17:30:13 +00001870 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(), nullptr,
1871 Ty);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001872 }
1873}
1874
Tobias Grosser6be480c2011-11-08 15:41:13 +00001875void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001876 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001877 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001878 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00001879 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001880}
1881
Tobias Grosser18daaca2012-05-22 10:47:27 +00001882void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001883 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001884 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001885
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001886 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001887
Johannes Doerferte7044942015-02-24 11:58:30 +00001888 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001889 }
1890}
1891
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001892void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001893 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001894 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001895
Tobias Grosser083d3d32014-06-28 08:59:45 +00001896 for (const auto &ParamID : ParameterIds) {
1897 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001898 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001899 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001900 }
1901
1902 // Align the parameters of all data structures to the model.
1903 Context = isl_set_align_params(Context, Space);
1904
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001905 for (ScopStmt &Stmt : *this)
1906 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001907}
1908
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001909static __isl_give isl_set *
1910simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1911 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001912 // If we modelt all blocks in the SCoP that have side effects we can simplify
1913 // the context with the constraints that are needed for anything to be
1914 // executed at all. However, if we have error blocks in the SCoP we already
1915 // assumed some parameter combinations cannot occure and removed them from the
1916 // domains, thus we cannot use the remaining domain to simplify the
1917 // assumptions.
1918 if (!S.hasErrorBlock()) {
1919 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1920 AssumptionContext =
1921 isl_set_gist_params(AssumptionContext, DomainParameters);
1922 }
1923
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001924 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1925 return AssumptionContext;
1926}
1927
1928void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001929 // The parameter constraints of the iteration domains give us a set of
1930 // constraints that need to hold for all cases where at least a single
1931 // statement iteration is executed in the whole scop. We now simplify the
1932 // assumed context under the assumption that such constraints hold and at
1933 // least a single statement iteration is executed. For cases where no
1934 // statement instances are executed, the assumptions we have taken about
1935 // the executed code do not matter and can be changed.
1936 //
1937 // WARNING: This only holds if the assumptions we have taken do not reduce
1938 // the set of statement instances that are executed. Otherwise we
1939 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001940 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001941 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001942 // performed. In such a case, modifying the run-time conditions and
1943 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001944 // to not be executed.
1945 //
1946 // Example:
1947 //
1948 // When delinearizing the following code:
1949 //
1950 // for (long i = 0; i < 100; i++)
1951 // for (long j = 0; j < m; j++)
1952 // A[i+p][j] = 1.0;
1953 //
1954 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001955 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001956 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001957 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001958 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001959}
1960
Johannes Doerfertb164c792014-09-18 11:17:17 +00001961/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001962static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001963 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1964 isl_pw_multi_aff *MinPMA, *MaxPMA;
1965 isl_pw_aff *LastDimAff;
1966 isl_aff *OneAff;
1967 unsigned Pos;
1968
Johannes Doerfert9143d672014-09-27 11:02:39 +00001969 // Restrict the number of parameters involved in the access as the lexmin/
1970 // lexmax computation will take too long if this number is high.
1971 //
1972 // Experiments with a simple test case using an i7 4800MQ:
1973 //
1974 // #Parameters involved | Time (in sec)
1975 // 6 | 0.01
1976 // 7 | 0.04
1977 // 8 | 0.12
1978 // 9 | 0.40
1979 // 10 | 1.54
1980 // 11 | 6.78
1981 // 12 | 30.38
1982 //
1983 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1984 unsigned InvolvedParams = 0;
1985 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1986 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1987 InvolvedParams++;
1988
1989 if (InvolvedParams > RunTimeChecksMaxParameters) {
1990 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001991 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001992 }
1993 }
1994
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001995 Set = isl_set_remove_divs(Set);
1996
Johannes Doerfertb164c792014-09-18 11:17:17 +00001997 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1998 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1999
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002000 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2001 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2002
Johannes Doerfertb164c792014-09-18 11:17:17 +00002003 // Adjust the last dimension of the maximal access by one as we want to
2004 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2005 // we test during code generation might now point after the end of the
2006 // allocated array but we will never dereference it anyway.
2007 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2008 "Assumed at least one output dimension");
2009 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2010 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2011 OneAff = isl_aff_zero_on_domain(
2012 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2013 OneAff = isl_aff_add_constant_si(OneAff, 1);
2014 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2015 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2016
2017 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2018
2019 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002020 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002021}
2022
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002023static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2024 isl_set *Domain = MA->getStatement()->getDomain();
2025 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2026 return isl_set_reset_tuple_id(Domain);
2027}
2028
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002029/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
2030static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00002031 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002032 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002033
2034 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2035 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002036 Locations = isl_union_set_coalesce(Locations);
2037 Locations = isl_union_set_detect_equalities(Locations);
2038 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002039 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002040 isl_union_set_free(Locations);
2041 return Valid;
2042}
2043
Johannes Doerfert96425c22015-08-30 21:13:53 +00002044/// @brief Helper to treat non-affine regions and basic blocks the same.
2045///
2046///{
2047
2048/// @brief Return the block that is the representing block for @p RN.
2049static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2050 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2051 : RN->getNodeAs<BasicBlock>();
2052}
2053
2054/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002055static inline BasicBlock *
2056getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002057 if (RN->isSubRegion()) {
2058 assert(idx == 0);
2059 return RN->getNodeAs<Region>()->getExit();
2060 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002061 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002062}
2063
2064/// @brief Return the smallest loop surrounding @p RN.
2065static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2066 if (!RN->isSubRegion())
2067 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2068
2069 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2070 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2071 while (L && NonAffineSubRegion->contains(L))
2072 L = L->getParentLoop();
2073 return L;
2074}
2075
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002076static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2077 if (!RN->isSubRegion())
2078 return 1;
2079
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002080 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002081 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002082}
2083
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002084static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2085 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002086 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002087 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002088 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002089 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002090 return true;
2091 return false;
2092}
2093
Johannes Doerfert96425c22015-08-30 21:13:53 +00002094///}
2095
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002096static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2097 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002098 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002099 isl_id *DimId =
2100 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2101 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2102}
2103
Johannes Doerfert96425c22015-08-30 21:13:53 +00002104isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002105 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002106}
2107
2108isl_set *Scop::getDomainConditions(BasicBlock *BB) {
2109 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002110 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002111}
2112
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002113void Scop::removeErrorBlockDomains(ScopDetection &SD, DominatorTree &DT,
2114 LoopInfo &LI) {
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002115 auto removeDomains = [this, &DT](BasicBlock *Start) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002116 auto *BBNode = DT.getNode(Start);
2117 for (auto *ErrorChild : depth_first(BBNode)) {
2118 auto *ErrorChildBlock = ErrorChild->getBlock();
2119 auto *CurrentDomain = DomainMap[ErrorChildBlock];
2120 auto *Empty = isl_set_empty(isl_set_get_space(CurrentDomain));
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002121 DomainMap[ErrorChildBlock] = Empty;
2122 isl_set_free(CurrentDomain);
2123 }
2124 };
2125
Tobias Grosser5ef2bc32015-11-23 10:18:23 +00002126 SmallVector<Region *, 4> Todo = {&R};
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002127
2128 while (!Todo.empty()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002129 auto *SubRegion = Todo.back();
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002130 Todo.pop_back();
2131
2132 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
2133 for (auto &Child : *SubRegion)
2134 Todo.push_back(Child.get());
2135 continue;
2136 }
2137 if (containsErrorBlock(SubRegion->getNode(), getRegion(), LI, DT))
2138 removeDomains(SubRegion->getEntry());
2139 }
2140
Johannes Doerferta90943d2016-02-21 16:37:25 +00002141 for (auto *BB : R.blocks())
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002142 if (isErrorBlock(*BB, R, LI, DT))
2143 removeDomains(BB);
2144}
2145
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002146void Scop::buildDomains(Region *R, ScopDetection &SD, DominatorTree &DT,
2147 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002148
Johannes Doerfert432658d2016-01-26 11:01:41 +00002149 bool IsOnlyNonAffineRegion = SD.isNonAffineSubRegion(R, R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002150 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002151 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2152 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002153 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002154
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002155 while (LD-- >= 0) {
2156 S = addDomainDimId(S, LD + 1, L);
2157 L = L->getParentLoop();
2158 }
2159
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002160 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002161
Johannes Doerfert432658d2016-01-26 11:01:41 +00002162 if (IsOnlyNonAffineRegion)
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002163 return;
2164
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002165 buildDomainsWithBranchConstraints(R, SD, DT, LI);
2166 propagateDomainConstraints(R, SD, DT, LI);
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002167
2168 // Error blocks and blocks dominated by them have been assumed to never be
2169 // executed. Representing them in the Scop does not add any value. In fact,
2170 // it is likely to cause issues during construction of the ScopStmts. The
2171 // contents of error blocks have not been verfied to be expressible and
2172 // will cause problems when building up a ScopStmt for them.
2173 // Furthermore, basic blocks dominated by error blocks may reference
2174 // instructions in the error block which, if the error block is not modeled,
2175 // can themselves not be constructed properly.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002176 removeErrorBlockDomains(SD, DT, LI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002177}
2178
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002179void Scop::buildDomainsWithBranchConstraints(Region *R, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002180 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert6f50c292016-01-26 11:03:25 +00002181 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002182
2183 // To create the domain for each block in R we iterate over all blocks and
2184 // subregions in R and propagate the conditions under which the current region
2185 // element is executed. To this end we iterate in reverse post order over R as
2186 // it ensures that we first visit all predecessors of a region node (either a
2187 // basic block or a subregion) before we visit the region node itself.
2188 // Initially, only the domain for the SCoP region entry block is set and from
2189 // there we propagate the current domain to all successors, however we add the
2190 // condition that the successor is actually executed next.
2191 // As we are only interested in non-loop carried constraints here we can
2192 // simply skip loop back edges.
2193
2194 ReversePostOrderTraversal<Region *> RTraversal(R);
2195 for (auto *RN : RTraversal) {
2196
2197 // Recurse for affine subregions but go on for basic blocks and non-affine
2198 // subregions.
2199 if (RN->isSubRegion()) {
2200 Region *SubRegion = RN->getNodeAs<Region>();
2201 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002202 buildDomainsWithBranchConstraints(SubRegion, SD, DT, LI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002203 continue;
2204 }
2205 }
2206
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002207 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002208 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002209
Johannes Doerfert96425c22015-08-30 21:13:53 +00002210 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002211 TerminatorInst *TI = BB->getTerminator();
2212
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002213 if (isa<UnreachableInst>(TI))
2214 continue;
2215
Johannes Doerfertf5673802015-10-01 23:48:18 +00002216 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002217 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002218 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002219
2220 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2221 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2222
2223 // Build the condition sets for the successor nodes of the current region
2224 // node. If it is a non-affine subregion we will always execute the single
2225 // exit node, hence the single entry node domain is the condition set. For
2226 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002227 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002228 if (RN->isSubRegion())
2229 ConditionSets.push_back(isl_set_copy(Domain));
2230 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002231 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002232
2233 // Now iterate over the successors and set their initial domain based on
2234 // their condition set. We skip back edges here and have to be careful when
2235 // we leave a loop not to keep constraints over a dimension that doesn't
2236 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002237 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002238 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002239 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002240 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002241
2242 // Skip back edges.
2243 if (DT.dominates(SuccBB, BB)) {
2244 isl_set_free(CondSet);
2245 continue;
2246 }
2247
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002248 // Do not adjust the number of dimensions if we enter a boxed loop or are
2249 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002250 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfert6f50c292016-01-26 11:03:25 +00002251 while (BoxedLoops.count(SuccBBLoop))
2252 SuccBBLoop = SuccBBLoop->getParentLoop();
Johannes Doerfert634909c2015-10-04 14:57:41 +00002253
2254 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002255
2256 // Check if the edge to SuccBB is a loop entry or exit edge. If so
2257 // adjust the dimensionality accordingly. Lastly, if we leave a loop
2258 // and enter a new one we need to drop the old constraints.
2259 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002260 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002261 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002262 CondSet = isl_set_project_out(CondSet, isl_dim_set,
2263 isl_set_n_dim(CondSet) - LoopDepthDiff,
2264 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002265 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002266 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002267 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002268 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002269 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002270 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002271 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
2272 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002273 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002274 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002275 }
2276
2277 // Set the domain for the successor or merge it with an existing domain in
2278 // case there are multiple paths (without loop back edges) to the
2279 // successor block.
2280 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002281
2282 if (HasComplexCFG) {
2283 isl_set_free(CondSet);
2284 continue;
2285 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002286 if (!SuccDomain)
2287 SuccDomain = CondSet;
2288 else
2289 SuccDomain = isl_set_union(SuccDomain, CondSet);
2290
2291 SuccDomain = isl_set_coalesce(SuccDomain);
Tobias Grosser75dc40c2015-12-20 13:31:48 +00002292 if (isl_set_n_basic_set(SuccDomain) > MaxConjunctsInDomain) {
2293 auto *Empty = isl_set_empty(isl_set_get_space(SuccDomain));
2294 isl_set_free(SuccDomain);
2295 SuccDomain = Empty;
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002296 HasComplexCFG = true;
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00002297 invalidate(COMPLEXITY, DebugLoc());
Tobias Grosser75dc40c2015-12-20 13:31:48 +00002298 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002299 }
2300 }
2301}
2302
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002303/// @brief Return the domain for @p BB wrt @p DomainMap.
2304///
2305/// This helper function will lookup @p BB in @p DomainMap but also handle the
2306/// case where @p BB is contained in a non-affine subregion using the region
2307/// tree obtained by @p RI.
2308static __isl_give isl_set *
2309getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
2310 RegionInfo &RI) {
2311 auto DIt = DomainMap.find(BB);
2312 if (DIt != DomainMap.end())
2313 return isl_set_copy(DIt->getSecond());
2314
2315 Region *R = RI.getRegionFor(BB);
2316 while (R->getEntry() == BB)
2317 R = R->getParent();
2318 return getDomainForBlock(R->getEntry(), DomainMap, RI);
2319}
2320
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002321void Scop::propagateDomainConstraints(Region *R, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002322 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002323 // Iterate over the region R and propagate the domain constrains from the
2324 // predecessors to the current node. In contrast to the
2325 // buildDomainsWithBranchConstraints function, this one will pull the domain
2326 // information from the predecessors instead of pushing it to the successors.
2327 // Additionally, we assume the domains to be already present in the domain
2328 // map here. However, we iterate again in reverse post order so we know all
2329 // predecessors have been visited before a block or non-affine subregion is
2330 // visited.
2331
2332 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2333 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2334
2335 ReversePostOrderTraversal<Region *> RTraversal(R);
2336 for (auto *RN : RTraversal) {
2337
2338 // Recurse for affine subregions but go on for basic blocks and non-affine
2339 // subregions.
2340 if (RN->isSubRegion()) {
2341 Region *SubRegion = RN->getNodeAs<Region>();
2342 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002343 propagateDomainConstraints(SubRegion, SD, DT, LI);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002344 continue;
2345 }
2346 }
2347
Johannes Doerfertf5673802015-10-01 23:48:18 +00002348 // Get the domain for the current block and check if it was initialized or
2349 // not. The only way it was not is if this block is only reachable via error
2350 // blocks, thus will not be executed under the assumptions we make. Such
2351 // blocks have to be skipped as their predecessors might not have domains
2352 // either. It would not benefit us to compute the domain anyway, only the
2353 // domains of the error blocks that are reachable from non-error blocks
2354 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002355 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002356 isl_set *&Domain = DomainMap[BB];
2357 if (!Domain) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002358 DomainMap.erase(BB);
2359 continue;
2360 }
Johannes Doerfertf5673802015-10-01 23:48:18 +00002361
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002362 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Michael Kruse88a22562016-03-29 07:50:52 +00002363 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002364
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002365 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2366 for (auto *PredBB : predecessors(BB)) {
2367
2368 // Skip backedges
2369 if (DT.dominates(BB, PredBB))
2370 continue;
2371
2372 isl_set *PredBBDom = nullptr;
2373
2374 // Handle the SCoP entry block with its outside predecessors.
2375 if (!getRegion().contains(PredBB))
2376 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
2377
2378 if (!PredBBDom) {
2379 // Determine the loop depth of the predecessor and adjust its domain to
Michael Kruse88a22562016-03-29 07:50:52 +00002380 // the domain of the current block. This can mean we have to:
2381 // o) Drop a dimension if this block is the exit of a loop, not the
2382 // header of a new loop and the predecessor was part of the loop.
2383 // o) Add an unconstrainted new dimension if this block is the header
2384 // of a loop and the predecessor is not part of it.
2385 // o) Drop the information about the innermost loop dimension when the
2386 // predecessor and the current block are surrounded by different
2387 // loops in the same depth.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002388 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2389 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2390 while (BoxedLoops.count(PredBBLoop))
2391 PredBBLoop = PredBBLoop->getParentLoop();
2392
Michael Kruse88a22562016-03-29 07:50:52 +00002393 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
2394 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
2395 if (BBLoopDepth < PredBBLoopDepth)
2396 PredBBDom = isl_set_project_out(
2397 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2398 LoopDepthDiff);
2399 else if (PredBBLoopDepth < BBLoopDepth) {
2400 assert(LoopDepthDiff == 1);
2401 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
2402 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2403 assert(LoopDepthDiff <= 1);
2404 PredBBDom = isl_set_drop_constraints_involving_dims(
2405 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002406 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002407 }
2408
2409 PredDom = isl_set_union(PredDom, PredBBDom);
2410 }
2411
2412 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002413 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002414
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002415 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002416 addLoopBoundsToHeaderDomain(BBLoop, LI);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002417
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002418 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002419 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002420 IsOptimized = true;
2421 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002422 addAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2423 AS_RESTRICTION);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002424 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002425 }
2426}
2427
2428/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2429/// is incremented by one and all other dimensions are equal, e.g.,
2430/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2431/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2432static __isl_give isl_map *
2433createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2434 auto *MapSpace = isl_space_map_from_set(SetSpace);
2435 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2436 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2437 if (u != Dim)
2438 NextIterationMap =
2439 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2440 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2441 C = isl_constraint_set_constant_si(C, 1);
2442 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2443 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2444 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2445 return NextIterationMap;
2446}
2447
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002448void Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002449 int LoopDepth = getRelativeLoopDepth(L);
2450 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002451
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002452 BasicBlock *HeaderBB = L->getHeader();
2453 assert(DomainMap.count(HeaderBB));
2454 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002455
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002456 isl_map *NextIterationMap =
2457 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002458
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002459 isl_set *UnionBackedgeCondition =
2460 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002461
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002462 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2463 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002464
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002465 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002466
2467 // If the latch is only reachable via error statements we skip it.
2468 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2469 if (!LatchBBDom)
2470 continue;
2471
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002472 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002473
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002474 TerminatorInst *TI = LatchBB->getTerminator();
2475 BranchInst *BI = dyn_cast<BranchInst>(TI);
2476 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002477 BackedgeCondition = isl_set_copy(LatchBBDom);
2478 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002479 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002480 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002481 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002482
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002483 // Free the non back edge condition set as we do not need it.
2484 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002485
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002486 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002487 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002488
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002489 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2490 assert(LatchLoopDepth >= LoopDepth);
2491 BackedgeCondition =
2492 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2493 LatchLoopDepth - LoopDepth);
2494 UnionBackedgeCondition =
2495 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002496 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002497
2498 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2499 for (int i = 0; i < LoopDepth; i++)
2500 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2501
2502 isl_set *UnionBackedgeConditionComplement =
2503 isl_set_complement(UnionBackedgeCondition);
2504 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2505 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2506 UnionBackedgeConditionComplement =
2507 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2508 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2509 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2510
2511 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2512 HeaderBBDom = Parts.second;
2513
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002514 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2515 // the bounded assumptions to the context as they are already implied by the
2516 // <nsw> tag.
2517 if (Affinator.hasNSWAddRecForLoop(L)) {
2518 isl_set_free(Parts.first);
2519 return;
2520 }
2521
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002522 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002523 addAssumption(INFINITELOOP, UnboundedCtx,
2524 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002525}
2526
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002527void Scop::buildAliasChecks(AliasAnalysis &AA) {
2528 if (!PollyUseRuntimeAliasChecks)
2529 return;
2530
2531 if (buildAliasGroups(AA))
2532 return;
2533
2534 // If a problem occurs while building the alias groups we need to delete
2535 // this SCoP and pretend it wasn't valid in the first place. To this end
2536 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002537 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002538
2539 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2540 << " could not be created as the number of parameters involved "
2541 "is too high. The SCoP will be "
2542 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2543 "the maximal number of parameters but be advised that the "
2544 "compile time might increase exponentially.\n\n");
2545}
2546
Johannes Doerfert9143d672014-09-27 11:02:39 +00002547bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002548 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002549 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002550 // for all memory accesses inside the SCoP.
2551 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002552 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002553 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002554 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002555 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002556 // if their access domains intersect, otherwise they are in different
2557 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002558 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002559 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002560 // and maximal accesses to each array of a group in read only and non
2561 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002562 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2563
2564 AliasSetTracker AST(AA);
2565
2566 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002567 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002568 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002569
2570 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002571 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002572 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2573 isl_set_free(StmtDomain);
2574 if (StmtDomainEmpty)
2575 continue;
2576
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002577 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002578 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002579 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002580 if (!MA->isRead())
2581 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002582 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00002583 if (MA->isRead() && isa<MemTransferInst>(Acc))
2584 PtrToAcc[cast<MemTransferInst>(Acc)->getSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00002585 else
2586 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002587 AST.add(Acc);
2588 }
2589 }
2590
2591 SmallVector<AliasGroupTy, 4> AliasGroups;
2592 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002593 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002594 continue;
2595 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00002596 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00002597 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00002598 if (AG.size() < 2)
2599 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002600 AliasGroups.push_back(std::move(AG));
2601 }
2602
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002603 // Split the alias groups based on their domain.
2604 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2605 AliasGroupTy NewAG;
2606 AliasGroupTy &AG = AliasGroups[u];
2607 AliasGroupTy::iterator AGI = AG.begin();
2608 isl_set *AGDomain = getAccessDomain(*AGI);
2609 while (AGI != AG.end()) {
2610 MemoryAccess *MA = *AGI;
2611 isl_set *MADomain = getAccessDomain(MA);
2612 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2613 NewAG.push_back(MA);
2614 AGI = AG.erase(AGI);
2615 isl_set_free(MADomain);
2616 } else {
2617 AGDomain = isl_set_union(AGDomain, MADomain);
2618 AGI++;
2619 }
2620 }
2621 if (NewAG.size() > 1)
2622 AliasGroups.push_back(std::move(NewAG));
2623 isl_set_free(AGDomain);
2624 }
2625
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002626 auto &F = *getRegion().getEntry()->getParent();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002627 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002628 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2629 for (AliasGroupTy &AG : AliasGroups) {
2630 NonReadOnlyBaseValues.clear();
2631 ReadOnlyPairs.clear();
2632
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002633 if (AG.size() < 2) {
2634 AG.clear();
2635 continue;
2636 }
2637
Johannes Doerfert13771732014-10-01 12:40:46 +00002638 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002639 emitOptimizationRemarkAnalysis(
2640 F.getContext(), DEBUG_TYPE, F,
2641 (*II)->getAccessInstruction()->getDebugLoc(),
2642 "Possibly aliasing pointer, use restrict keyword.");
2643
Johannes Doerfert13771732014-10-01 12:40:46 +00002644 Value *BaseAddr = (*II)->getBaseAddr();
2645 if (HasWriteAccess.count(BaseAddr)) {
2646 NonReadOnlyBaseValues.insert(BaseAddr);
2647 II++;
2648 } else {
2649 ReadOnlyPairs[BaseAddr].insert(*II);
2650 II = AG.erase(II);
2651 }
2652 }
2653
2654 // If we don't have read only pointers check if there are at least two
2655 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002656 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002657 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002658 continue;
2659 }
2660
2661 // If we don't have non read only pointers clear the alias group.
2662 if (NonReadOnlyBaseValues.empty()) {
2663 AG.clear();
2664 continue;
2665 }
2666
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00002667 // Check if we have non-affine accesses left, if so bail out as we cannot
2668 // generate a good access range yet.
2669 for (auto *MA : AG)
2670 if (!MA->isAffine()) {
2671 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
2672 return false;
2673 }
2674 for (auto &ReadOnlyPair : ReadOnlyPairs)
2675 for (auto *MA : ReadOnlyPair.second)
2676 if (!MA->isAffine()) {
2677 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
2678 return false;
2679 }
2680
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002681 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002682 MinMaxAliasGroups.emplace_back();
2683 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2684 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2685 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2686 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002687
2688 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002689
2690 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002691 for (MemoryAccess *MA : AG)
2692 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002693
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002694 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2695 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002696
2697 // Bail out if the number of values we need to compare is too large.
2698 // This is important as the number of comparisions grows quadratically with
2699 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002700 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2701 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002702 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002703
2704 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002705 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002706 Accesses = isl_union_map_empty(getParamSpace());
2707
2708 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2709 for (MemoryAccess *MA : ReadOnlyPair.second)
2710 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2711
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002712 Valid =
2713 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002714
2715 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002716 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002717 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002718
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002719 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002720}
2721
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002722/// @brief Get the smallest loop that contains @p R but is not in @p R.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002723static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002724 // Start with the smallest loop containing the entry and expand that
2725 // loop until it contains all blocks in the region. If there is a loop
2726 // containing all blocks in the region check if it is itself contained
2727 // and if so take the parent loop as it will be the smallest containing
2728 // the region but not contained by it.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002729 Loop *L = LI.getLoopFor(R.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002730 while (L) {
2731 bool AllContained = true;
2732 for (auto *BB : R.blocks())
2733 AllContained &= L->contains(BB);
2734 if (AllContained)
2735 break;
2736 L = L->getParentLoop();
2737 }
2738
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002739 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2740}
2741
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002742static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2743 ScopDetection &SD) {
2744
2745 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2746
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002747 unsigned MinLD = INT_MAX, MaxLD = 0;
2748 for (BasicBlock *BB : R.blocks()) {
2749 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002750 if (!R.contains(L))
2751 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002752 if (BoxedLoops && BoxedLoops->count(L))
2753 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002754 unsigned LD = L->getLoopDepth();
2755 MinLD = std::min(MinLD, LD);
2756 MaxLD = std::max(MaxLD, LD);
2757 }
2758 }
2759
2760 // Handle the case that there is no loop in the SCoP first.
2761 if (MaxLD == 0)
2762 return 1;
2763
2764 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2765 assert(MaxLD >= MinLD &&
2766 "Maximal loop depth was smaller than mininaml loop depth?");
2767 return MaxLD - MinLD + 1;
2768}
2769
Michael Kruse09eb4452016-03-03 22:10:47 +00002770Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
2771 unsigned MaxLoopDepth)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00002772 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002773 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002774 HasComplexCFG(false), MaxLoopDepth(MaxLoopDepth),
2775 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
2776 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
2777 Schedule(nullptr) {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002778 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00002779 buildContext();
2780}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002781
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002782void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002783 DominatorTree &DT, LoopInfo &LI) {
2784 addUserAssumptions(AC, DT, LI);
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002785 buildInvariantEquivalenceClasses(SD);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002786
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002787 buildDomains(&R, SD, DT, LI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002788
Michael Krusecac948e2015-10-02 13:53:07 +00002789 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002790 // Exit early in case there are no executable statements left in this scop.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002791 simplifySCoP(true, DT, LI);
Michael Kruseafe06702015-10-02 16:33:27 +00002792 if (Stmts.empty())
2793 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002794
Michael Krusecac948e2015-10-02 13:53:07 +00002795 // The ScopStmts now have enough information to initialize themselves.
2796 for (ScopStmt &Stmt : Stmts)
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002797 Stmt.init(SD);
Michael Krusecac948e2015-10-02 13:53:07 +00002798
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002799 buildSchedule(SD, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00002800
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002801 if (!hasFeasibleRuntimeContext())
Tobias Grosser8286b832015-11-02 11:29:32 +00002802 return;
2803
2804 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002805 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002806 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002807 addUserContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002808 addWrappingContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002809 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002810 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002811
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002812 hoistInvariantLoads(SD);
Tobias Grosser0865e7752016-02-29 07:29:42 +00002813 verifyInvariantLoads(SD);
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002814 simplifySCoP(false, DT, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00002815}
2816
2817Scop::~Scop() {
2818 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002819 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002820 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002821 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002822
Johannes Doerfert96425c22015-08-30 21:13:53 +00002823 for (auto It : DomainMap)
2824 isl_set_free(It.second);
2825
Johannes Doerfertb164c792014-09-18 11:17:17 +00002826 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002827 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002828 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002829 isl_pw_multi_aff_free(MMA.first);
2830 isl_pw_multi_aff_free(MMA.second);
2831 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002832 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002833 isl_pw_multi_aff_free(MMA.first);
2834 isl_pw_multi_aff_free(MMA.second);
2835 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002836 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002837
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002838 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002839 isl_set_free(std::get<2>(IAClass));
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002840
2841 // Explicitly release all Scop objects and the underlying isl objects before
2842 // we relase the isl context.
2843 Stmts.clear();
2844 ScopArrayInfoMap.clear();
2845 AccFuncMap.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00002846}
2847
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002848void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00002849 // Check all array accesses for each base pointer and find a (virtual) element
2850 // size for the base pointer that divides all access functions.
2851 for (auto &Stmt : *this)
2852 for (auto *Access : Stmt) {
2853 if (!Access->isArrayKind())
2854 continue;
2855 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(),
2856 ScopArrayInfo::MK_Array)];
2857 if (SAI->getNumberOfDimensions() != 1)
2858 continue;
2859 unsigned DivisibleSize = SAI->getElemSizeInBytes();
2860 auto *Subscript = Access->getSubscript(0);
2861 while (!isDivisible(Subscript, DivisibleSize, *SE))
2862 DivisibleSize /= 2;
2863 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
2864 SAI->updateElementType(Ty);
2865 }
2866
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002867 for (auto &Stmt : *this)
2868 for (auto &Access : Stmt)
2869 Access->updateDimensionality();
2870}
2871
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002872void Scop::simplifySCoP(bool RemoveIgnoredStmts, DominatorTree &DT,
2873 LoopInfo &LI) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002874 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2875 ScopStmt &Stmt = *StmtIt;
Michael Kruse7b5caa42016-02-24 22:08:28 +00002876 RegionNode *RN = Stmt.getRegionNode();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002877
Johannes Doerferteca9e892015-11-03 16:54:49 +00002878 bool RemoveStmt = StmtIt->isEmpty();
2879 if (!RemoveStmt)
Michael Kruse375cb5f2016-02-24 22:08:24 +00002880 RemoveStmt = isl_set_is_empty(DomainMap[Stmt.getEntryBlock()]);
Johannes Doerferteca9e892015-11-03 16:54:49 +00002881 if (!RemoveStmt)
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002882 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN, DT, LI));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002883
Johannes Doerferteca9e892015-11-03 16:54:49 +00002884 // Remove read only statements only after invariant loop hoisting.
2885 if (!RemoveStmt && !RemoveIgnoredStmts) {
2886 bool OnlyRead = true;
2887 for (MemoryAccess *MA : Stmt) {
2888 if (MA->isRead())
2889 continue;
2890
2891 OnlyRead = false;
2892 break;
2893 }
2894
2895 RemoveStmt = OnlyRead;
2896 }
2897
2898 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00002899 // Remove the statement because it is unnecessary.
2900 if (Stmt.isRegionStmt())
2901 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2902 StmtMap.erase(BB);
2903 else
2904 StmtMap.erase(Stmt.getBasicBlock());
2905
2906 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002907 continue;
2908 }
2909
Michael Krusecac948e2015-10-02 13:53:07 +00002910 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002911 }
2912}
2913
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002914const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2915 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2916 if (!LInst)
2917 return nullptr;
2918
2919 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2920 LInst = cast<LoadInst>(Rep);
2921
Johannes Doerfert96e54712016-02-07 17:30:13 +00002922 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002923 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00002924 for (auto &IAClass : InvariantEquivClasses) {
2925 if (PointerSCEV != std::get<0>(IAClass) || Ty != std::get<3>(IAClass))
2926 continue;
2927
2928 auto &MAs = std::get<1>(IAClass);
2929 for (auto *MA : MAs)
2930 if (MA->getAccessInstruction() == Val)
2931 return &IAClass;
2932 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002933
2934 return nullptr;
2935}
2936
2937void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2938
2939 // Get the context under which the statement is executed.
2940 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2941 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2942 DomainCtx = isl_set_detect_equalities(DomainCtx);
2943 DomainCtx = isl_set_coalesce(DomainCtx);
2944
2945 // Project out all parameters that relate to loads in the statement. Otherwise
2946 // we could have cyclic dependences on the constraints under which the
2947 // hoisted loads are executed and we could not determine an order in which to
2948 // pre-load them. This happens because not only lower bounds are part of the
2949 // domain but also upper bounds.
2950 for (MemoryAccess *MA : InvMAs) {
2951 Instruction *AccInst = MA->getAccessInstruction();
2952 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00002953 SetVector<Value *> Values;
2954 for (const SCEV *Parameter : Parameters) {
2955 Values.clear();
2956 findValues(Parameter, Values);
2957 if (!Values.count(AccInst))
2958 continue;
2959
2960 if (isl_id *ParamId = getIdForParam(Parameter)) {
2961 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2962 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2963 isl_id_free(ParamId);
2964 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002965 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002966 }
2967 }
2968
2969 for (MemoryAccess *MA : InvMAs) {
2970 // Check for another invariant access that accesses the same location as
2971 // MA and if found consolidate them. Otherwise create a new equivalence
2972 // class at the end of InvariantEquivClasses.
2973 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00002974 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002975 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2976
2977 bool Consolidated = false;
2978 for (auto &IAClass : InvariantEquivClasses) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002979 if (PointerSCEV != std::get<0>(IAClass) || Ty != std::get<3>(IAClass))
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002980 continue;
2981
Johannes Doerfertdf880232016-03-03 12:26:58 +00002982 // If the pointer and the type is equal check if the access function wrt.
2983 // to the domain is equal too. It can happen that the domain fixes
2984 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00002985 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00002986 // create a new invariant load equivalence class.
2987 auto &MAs = std::get<1>(IAClass);
2988 if (!MAs.empty()) {
2989 auto *LastMA = MAs.front();
2990
2991 auto *AR = isl_map_range(MA->getAccessRelation());
2992 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
2993 bool SameAR = isl_set_is_equal(AR, LastAR);
2994 isl_set_free(AR);
2995 isl_set_free(LastAR);
2996
2997 if (!SameAR)
2998 continue;
2999 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003000
3001 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003002 MAs.push_front(MA);
3003
Johannes Doerfertdf880232016-03-03 12:26:58 +00003004 Consolidated = true;
3005
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003006 // Unify the execution context of the class and this statement.
3007 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003008 if (IAClassDomainCtx)
3009 IAClassDomainCtx = isl_set_coalesce(
3010 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
3011 else
3012 IAClassDomainCtx = isl_set_copy(DomainCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003013 break;
3014 }
3015
3016 if (Consolidated)
3017 continue;
3018
3019 // If we did not consolidate MA, thus did not find an equivalence class
3020 // for it, we create a new one.
3021 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
Johannes Doerfert96e54712016-02-07 17:30:13 +00003022 isl_set_copy(DomainCtx), Ty);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003023 }
3024
3025 isl_set_free(DomainCtx);
3026}
3027
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003028bool Scop::isHoistableAccess(MemoryAccess *Access,
3029 __isl_keep isl_union_map *Writes) {
3030 // TODO: Loads that are not loop carried, hence are in a statement with
3031 // zero iterators, are by construction invariant, though we
3032 // currently "hoist" them anyway. This is necessary because we allow
3033 // them to be treated as parameters (e.g., in conditions) and our code
3034 // generation would otherwise use the old value.
3035
3036 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003037 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003038
3039 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
3040 return false;
3041
3042 // Skip accesses that have an invariant base pointer which is defined but
3043 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3044 // returns a pointer that is used as a base address. However, as we want
3045 // to hoist indirect pointers, we allow the base pointer to be defined in
3046 // the region if it is also a memory access. Each ScopArrayInfo object
3047 // that has a base pointer origin has a base pointer that is loaded and
3048 // that it is invariant, thus it will be hoisted too. However, if there is
3049 // no base pointer origin we check that the base pointer is defined
3050 // outside the region.
3051 const ScopArrayInfo *SAI = Access->getScopArrayInfo();
Johannes Doerfert4cf15802016-02-15 12:42:05 +00003052 auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr());
3053 if (SAI->getBasePtrOriginSAI()) {
3054 assert(BasePtrInst && R.contains(BasePtrInst));
3055 if (!isa<LoadInst>(BasePtrInst))
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003056 return false;
Michael Kruse6f7721f2016-02-24 22:08:19 +00003057 auto *BasePtrStmt = getStmtFor(BasePtrInst);
Johannes Doerfert4cf15802016-02-15 12:42:05 +00003058 assert(BasePtrStmt);
3059 auto *BasePtrMA = BasePtrStmt->getArrayAccessOrNULLFor(BasePtrInst);
3060 if (BasePtrMA && !isHoistableAccess(BasePtrMA, Writes))
3061 return false;
3062 } else if (BasePtrInst && R.contains(BasePtrInst))
3063 return false;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003064
3065 // Skip accesses in non-affine subregions as they might not be executed
3066 // under the same condition as the entry of the non-affine subregion.
3067 if (BB != Access->getAccessInstruction()->getParent())
3068 return false;
3069
3070 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003071 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003072
3073 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3074 Stmt.getNumIterators())) {
3075 isl_map_free(AccessRelation);
3076 return false;
3077 }
3078
3079 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3080 isl_set *AccessRange = isl_map_range(AccessRelation);
3081
3082 isl_union_map *Written = isl_union_map_intersect_range(
3083 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
3084 bool IsWritten = !isl_union_map_is_empty(Written);
3085 isl_union_map_free(Written);
3086
3087 if (IsWritten)
3088 return false;
3089
3090 return true;
3091}
3092
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003093void Scop::verifyInvariantLoads(ScopDetection &SD) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003094 auto &RIL = *SD.getRequiredInvariantLoads(&getRegion());
3095 for (LoadInst *LI : RIL) {
3096 assert(LI && getRegion().contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003097 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003098 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003099 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3100 return;
3101 }
3102 }
3103}
3104
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003105void Scop::hoistInvariantLoads(ScopDetection &SD) {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003106 if (!PollyInvariantLoadHoisting)
3107 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003108
Tobias Grosser0865e7752016-02-29 07:29:42 +00003109 isl_union_map *Writes = getWrites();
3110 for (ScopStmt &Stmt : *this) {
3111 MemoryAccessList InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003112
Tobias Grosser0865e7752016-02-29 07:29:42 +00003113 for (MemoryAccess *Access : Stmt)
3114 if (isHoistableAccess(Access, Writes))
3115 InvariantAccesses.push_front(Access);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003116
Tobias Grosser0865e7752016-02-29 07:29:42 +00003117 // We inserted invariant accesses always in the front but need them to be
3118 // sorted in a "natural order". The statements are already sorted in
3119 // reverse post order and that suffices for the accesses too. The reason
3120 // we require an order in the first place is the dependences between
3121 // invariant loads that can be caused by indirect loads.
3122 InvariantAccesses.reverse();
3123
3124 // Transfer the memory access from the statement to the SCoP.
3125 Stmt.removeMemoryAccesses(InvariantAccesses);
3126 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003127 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003128 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003129}
3130
Johannes Doerfert80ef1102014-11-07 08:31:31 +00003131const ScopArrayInfo *
Tobias Grossercc779502016-02-02 13:22:54 +00003132Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003133 ArrayRef<const SCEV *> Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00003134 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003135 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003136 if (!SAI) {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003137 auto &DL = getRegion().getEntry()->getModule()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003138 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003139 DL, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003140 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003141 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003142 // In case of mismatching array sizes, we bail out by setting the run-time
3143 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003144 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003145 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003146 }
Tobias Grosserab671442015-05-23 05:58:27 +00003147 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003148}
3149
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003150const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00003151 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003152 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003153 assert(SAI && "No ScopArrayInfo available for this base pointer");
3154 return SAI;
3155}
3156
Tobias Grosser74394f02013-01-14 22:40:23 +00003157std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003158
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003159std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003160 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003161 return stringFromIslObj(AssumedContext);
3162}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003163
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003164std::string Scop::getInvalidContextStr() const {
3165 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003166}
Tobias Grosser75805372011-04-29 06:27:02 +00003167
3168std::string Scop::getNameStr() const {
3169 std::string ExitName, EntryName;
3170 raw_string_ostream ExitStr(ExitName);
3171 raw_string_ostream EntryStr(EntryName);
3172
Tobias Grosserf240b482014-01-09 10:42:15 +00003173 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003174 EntryStr.str();
3175
3176 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003177 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003178 ExitStr.str();
3179 } else
3180 ExitName = "FunctionExit";
3181
3182 return EntryName + "---" + ExitName;
3183}
3184
Tobias Grosser74394f02013-01-14 22:40:23 +00003185__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003186__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003187 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003188}
3189
Tobias Grossere86109f2013-10-29 21:05:49 +00003190__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003191 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003192 return isl_set_copy(AssumedContext);
3193}
3194
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003195bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003196 auto *PositiveContext = getAssumedContext();
3197 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3198 bool IsFeasible = !isl_set_is_empty(PositiveContext);
3199 isl_set_free(PositiveContext);
3200 if (!IsFeasible)
3201 return false;
3202
3203 auto *NegativeContext = getInvalidContext();
3204 auto *DomainContext = isl_union_set_params(getDomains());
3205 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
3206 isl_set_free(NegativeContext);
3207 isl_set_free(DomainContext);
3208
Johannes Doerfert43788c52015-08-20 05:58:56 +00003209 return IsFeasible;
3210}
3211
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003212static std::string toString(AssumptionKind Kind) {
3213 switch (Kind) {
3214 case ALIASING:
3215 return "No-aliasing";
3216 case INBOUNDS:
3217 return "Inbounds";
3218 case WRAPPING:
3219 return "No-overflows";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003220 case COMPLEXITY:
3221 return "Low complexity";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003222 case ERRORBLOCK:
3223 return "No-error";
3224 case INFINITELOOP:
3225 return "Finite loop";
3226 case INVARIANTLOAD:
3227 return "Invariant load";
3228 case DELINEARIZATION:
3229 return "Delinearization";
3230 }
3231 llvm_unreachable("Unknown AssumptionKind!");
3232}
3233
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003234bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3235 DebugLoc Loc, AssumptionSign Sign) {
3236 if (Sign == AS_ASSUMPTION) {
3237 if (isl_set_is_subset(Context, Set))
3238 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003239
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003240 if (isl_set_is_subset(AssumedContext, Set))
3241 return false;
3242 } else {
3243 if (isl_set_is_disjoint(Set, Context))
3244 return false;
3245
3246 if (isl_set_is_subset(Set, InvalidContext))
3247 return false;
3248 }
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003249
3250 auto &F = *getRegion().getEntry()->getParent();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003251 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
3252 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003253 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003254 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003255}
3256
3257void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003258 DebugLoc Loc, AssumptionSign Sign) {
3259 if (!trackAssumption(Kind, Set, Loc, Sign)) {
3260 isl_set_free(Set);
3261 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003262 }
3263
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003264 if (Sign == AS_ASSUMPTION) {
3265 AssumedContext = isl_set_intersect(AssumedContext, Set);
3266 AssumedContext = isl_set_coalesce(AssumedContext);
3267 } else {
3268 InvalidContext = isl_set_union(InvalidContext, Set);
3269 InvalidContext = isl_set_coalesce(InvalidContext);
3270 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003271}
3272
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003273void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003274 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003275}
3276
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003277__isl_give isl_set *Scop::getInvalidContext() const {
3278 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003279}
3280
Tobias Grosser75805372011-04-29 06:27:02 +00003281void Scop::printContext(raw_ostream &OS) const {
3282 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003283 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003284
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003285 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003286 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003287
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003288 OS.indent(4) << "Invalid Context:\n";
3289 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003290
Tobias Grosser083d3d32014-06-28 08:59:45 +00003291 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00003292 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00003293 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
3294 }
Tobias Grosser75805372011-04-29 06:27:02 +00003295}
3296
Johannes Doerfertb164c792014-09-18 11:17:17 +00003297void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003298 int noOfGroups = 0;
3299 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003300 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003301 noOfGroups += 1;
3302 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003303 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003304 }
3305
Tobias Grosserbb853c22015-07-25 12:31:03 +00003306 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003307 if (MinMaxAliasGroups.empty()) {
3308 OS.indent(8) << "n/a\n";
3309 return;
3310 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003311
Tobias Grosserbb853c22015-07-25 12:31:03 +00003312 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003313
3314 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003315 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003316 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003317 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003318 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3319 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003320 }
3321 OS << " ]]\n";
3322 }
3323
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003324 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003325 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003326 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003327 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003328 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3329 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003330 }
3331 OS << " ]]\n";
3332 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003333 }
3334}
3335
Tobias Grosser75805372011-04-29 06:27:02 +00003336void Scop::printStatements(raw_ostream &OS) const {
3337 OS << "Statements {\n";
3338
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003339 for (const ScopStmt &Stmt : *this)
3340 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003341
3342 OS.indent(4) << "}\n";
3343}
3344
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003345void Scop::printArrayInfo(raw_ostream &OS) const {
3346 OS << "Arrays {\n";
3347
Tobias Grosserab671442015-05-23 05:58:27 +00003348 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003349 Array.second->print(OS);
3350
3351 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003352
3353 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3354
3355 for (auto &Array : arrays())
3356 Array.second->print(OS, /* SizeAsPwAff */ true);
3357
3358 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003359}
3360
Tobias Grosser75805372011-04-29 06:27:02 +00003361void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00003362 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
3363 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003364 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003365 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003366 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003367 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003368 const auto &MAs = std::get<1>(IAClass);
3369 if (MAs.empty()) {
3370 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003371 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003372 MAs.front()->print(OS);
3373 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003374 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003375 }
3376 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003377 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003378 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003379 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003380 printStatements(OS.indent(4));
3381}
3382
3383void Scop::dump() const { print(dbgs()); }
3384
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003385isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00003386
Johannes Doerfertcef616f2015-09-15 22:49:04 +00003387__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003388 // First try to use the SCEVAffinator to generate a piecewise defined
3389 // affine function from @p E in the context of @p BB. If that tasks becomes to
3390 // complex the affinator might return a nullptr. In such a case we invalidate
3391 // the SCoP and return a dummy value. This way we do not need to add error
3392 // handling cdoe to all users of this function.
3393 auto *PWA = Affinator.getPwAff(E, BB);
3394 if (PWA)
3395 return PWA;
3396
3397 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
3398 invalidate(COMPLEXITY, DL);
3399 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003400}
3401
Tobias Grosser808cd692015-07-14 09:33:13 +00003402__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003403 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003404
Tobias Grosser808cd692015-07-14 09:33:13 +00003405 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003406 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003407
3408 return Domain;
3409}
3410
Tobias Grossere5a35142015-11-12 14:07:09 +00003411__isl_give isl_union_map *
3412Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3413 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003414
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003415 for (ScopStmt &Stmt : *this) {
3416 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003417 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003418 continue;
3419
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003420 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003421 isl_map *AccessDomain = MA->getAccessRelation();
3422 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003423 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003424 }
3425 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003426 return isl_union_map_coalesce(Accesses);
3427}
3428
3429__isl_give isl_union_map *Scop::getMustWrites() {
3430 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003431}
3432
3433__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003434 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003435}
3436
Tobias Grosser37eb4222014-02-20 21:43:54 +00003437__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003438 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003439}
3440
3441__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003442 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003443}
3444
Tobias Grosser2ac23382015-11-12 14:07:13 +00003445__isl_give isl_union_map *Scop::getAccesses() {
3446 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3447}
3448
Tobias Grosser808cd692015-07-14 09:33:13 +00003449__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00003450 auto *Tree = getScheduleTree();
3451 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00003452 isl_schedule_free(Tree);
3453 return S;
3454}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003455
Tobias Grosser808cd692015-07-14 09:33:13 +00003456__isl_give isl_schedule *Scop::getScheduleTree() const {
3457 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3458 getDomains());
3459}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003460
Tobias Grosser808cd692015-07-14 09:33:13 +00003461void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3462 auto *S = isl_schedule_from_domain(getDomains());
3463 S = isl_schedule_insert_partial_schedule(
3464 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3465 isl_schedule_free(Schedule);
3466 Schedule = S;
3467}
3468
3469void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3470 isl_schedule_free(Schedule);
3471 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003472}
3473
3474bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3475 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003476 for (ScopStmt &Stmt : *this) {
3477 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003478 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3479 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3480
3481 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3482 isl_union_set_free(StmtDomain);
3483 isl_union_set_free(NewStmtDomain);
3484 continue;
3485 }
3486
3487 Changed = true;
3488
3489 isl_union_set_free(StmtDomain);
3490 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3491
3492 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003493 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003494 isl_union_set_free(NewStmtDomain);
3495 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003496 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003497 }
3498 isl_union_set_free(Domain);
3499 return Changed;
3500}
3501
Tobias Grosser75805372011-04-29 06:27:02 +00003502ScalarEvolution *Scop::getSE() const { return SE; }
3503
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003504bool Scop::isIgnored(RegionNode *RN, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003505 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Michael Kruse6f7721f2016-02-24 22:08:19 +00003506 ScopStmt *Stmt = getStmtFor(RN);
Michael Krusea902ba62015-12-13 19:21:45 +00003507
3508 // If there is no stmt, then it already has been removed.
3509 if (!Stmt)
3510 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00003511
Johannes Doerfertf5673802015-10-01 23:48:18 +00003512 // Check if there are accesses contained.
Michael Krusea902ba62015-12-13 19:21:45 +00003513 if (Stmt->isEmpty())
Johannes Doerfertf5673802015-10-01 23:48:18 +00003514 return true;
3515
3516 // Check for reachability via non-error blocks.
3517 if (!DomainMap.count(BB))
3518 return true;
3519
3520 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003521 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003522 return true;
3523
3524 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003525}
3526
Tobias Grosser808cd692015-07-14 09:33:13 +00003527struct MapToDimensionDataTy {
3528 int N;
3529 isl_union_pw_multi_aff *Res;
3530};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003531
Tobias Grosser808cd692015-07-14 09:33:13 +00003532// @brief Create a function that maps the elements of 'Set' to its N-th
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003533// dimension and add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00003534//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003535// @param Set The input set.
3536// @param User->N The dimension to map to.
3537// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00003538//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003539// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00003540static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3541 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3542 int Dim;
3543 isl_space *Space;
3544 isl_pw_multi_aff *PMA;
3545
3546 Dim = isl_set_dim(Set, isl_dim_set);
3547 Space = isl_set_get_space(Set);
3548 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3549 Dim - Data->N);
3550 if (Data->N > 1)
3551 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3552 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3553
3554 isl_set_free(Set);
3555
3556 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003557}
3558
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003559// @brief Create an isl_multi_union_aff that defines an identity mapping
3560// from the elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003561//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003562// # Example:
3563//
3564// Domain: { A[i,j]; B[i,j,k] }
3565// N: 1
3566//
3567// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
3568//
3569// @param USet A union set describing the elements for which to generate a
3570// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00003571// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003572// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003573static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003574mapToDimension(__isl_take isl_union_set *USet, int N) {
3575 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00003576 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003577 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003578
Tobias Grosser808cd692015-07-14 09:33:13 +00003579 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00003580
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003581 auto *Space = isl_union_set_get_space(USet);
3582 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00003583
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003584 Data = {N, PwAff};
3585
3586 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00003587 (void)Res;
3588
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003589 assert(Res == isl_stat_ok);
3590
3591 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00003592 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3593}
3594
Tobias Grosser316b5b22015-11-11 19:28:14 +00003595void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003596 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003597 Stmts.emplace_back(*this, *BB);
Johannes Doerferta90943d2016-02-21 16:37:25 +00003598 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003599 StmtMap[BB] = Stmt;
3600 } else {
3601 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003602 Stmts.emplace_back(*this, *R);
Johannes Doerferta90943d2016-02-21 16:37:25 +00003603 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003604 for (BasicBlock *BB : R->blocks())
3605 StmtMap[BB] = Stmt;
3606 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003607}
3608
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003609void Scop::buildSchedule(ScopDetection &SD, LoopInfo &LI) {
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003610 Loop *L = getLoopSurroundingRegion(getRegion(), LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003611 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003612 buildSchedule(getRegion().getNode(), LoopStack, SD, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003613 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
3614 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003615}
3616
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003617/// To generate a schedule for the elements in a Region we traverse the Region
3618/// in reverse-post-order and add the contained RegionNodes in traversal order
3619/// to the schedule of the loop that is currently at the top of the LoopStack.
3620/// For loop-free codes, this results in a correct sequential ordering.
3621///
3622/// Example:
3623/// bb1(0)
3624/// / \.
3625/// bb2(1) bb3(2)
3626/// \ / \.
3627/// bb4(3) bb5(4)
3628/// \ /
3629/// bb6(5)
3630///
3631/// Including loops requires additional processing. Whenever a loop header is
3632/// encountered, the corresponding loop is added to the @p LoopStack. Starting
3633/// from an empty schedule, we first process all RegionNodes that are within
3634/// this loop and complete the sequential schedule at this loop-level before
3635/// processing about any other nodes. To implement this
3636/// loop-nodes-first-processing, the reverse post-order traversal is
3637/// insufficient. Hence, we additionally check if the traversal yields
3638/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
3639/// These region-nodes are then queue and only traverse after the all nodes
3640/// within the current loop have been processed.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003641void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, ScopDetection &SD,
3642 LoopInfo &LI) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003643 Loop *OuterScopLoop = getLoopSurroundingRegion(getRegion(), LI);
3644
3645 ReversePostOrderTraversal<Region *> RTraversal(R);
3646 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
3647 std::deque<RegionNode *> DelayList;
3648 bool LastRNWaiting = false;
3649
3650 // Iterate over the region @p R in reverse post-order but queue
3651 // sub-regions/blocks iff they are not part of the last encountered but not
3652 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
3653 // that we queued the last sub-region/block from the reverse post-order
3654 // iterator. If it is set we have to explore the next sub-region/block from
3655 // the iterator (if any) to guarantee progress. If it is not set we first try
3656 // the next queued sub-region/blocks.
3657 while (!WorkList.empty() || !DelayList.empty()) {
3658 RegionNode *RN;
3659
3660 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
3661 RN = WorkList.front();
3662 WorkList.pop_front();
3663 LastRNWaiting = false;
3664 } else {
3665 RN = DelayList.front();
3666 DelayList.pop_front();
3667 }
3668
3669 Loop *L = getRegionNodeLoop(RN, LI);
3670 if (!getRegion().contains(L))
3671 L = OuterScopLoop;
3672
3673 Loop *LastLoop = LoopStack.back().L;
3674 if (LastLoop != L) {
3675 if (!LastLoop->contains(L)) {
3676 LastRNWaiting = true;
3677 DelayList.push_back(RN);
3678 continue;
3679 }
3680 LoopStack.push_back({L, nullptr, 0});
3681 }
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003682 buildSchedule(RN, LoopStack, SD, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003683 }
3684
3685 return;
3686}
3687
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003688void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003689 ScopDetection &SD, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00003690
Tobias Grosser8362c262016-01-06 15:30:06 +00003691 if (RN->isSubRegion()) {
3692 auto *LocalRegion = RN->getNodeAs<Region>();
3693 if (!SD.isNonAffineSubRegion(LocalRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003694 buildSchedule(LocalRegion, LoopStack, SD, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00003695 return;
3696 }
3697 }
Michael Kruse046dde42015-08-10 13:01:57 +00003698
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003699 auto &LoopData = LoopStack.back();
3700 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00003701
Michael Kruse6f7721f2016-02-24 22:08:19 +00003702 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00003703 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3704 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003705 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00003706 }
3707
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003708 // Check if we just processed the last node in this loop. If we did, finalize
3709 // the loop by:
3710 //
3711 // - adding new schedule dimensions
3712 // - folding the resulting schedule into the parent loop schedule
3713 // - dropping the loop schedule from the LoopStack.
3714 //
3715 // Then continue to check surrounding loops, which might also have been
3716 // completed by this node.
3717 while (LoopData.L &&
3718 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00003719 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003720 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00003721
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003722 LoopStack.pop_back();
3723 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00003724
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003725 if (Schedule) {
3726 auto *Domain = isl_schedule_get_domain(Schedule);
3727 auto *MUPA = mapToDimension(Domain, LoopStack.size());
3728 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
3729 NextLoopData.Schedule =
3730 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003731 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003732
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003733 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
3734 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00003735 }
Tobias Grosser75805372011-04-29 06:27:02 +00003736}
3737
Michael Kruse6f7721f2016-02-24 22:08:19 +00003738ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003739 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003740 if (StmtMapIt == StmtMap.end())
3741 return nullptr;
3742 return StmtMapIt->second;
3743}
3744
Michael Kruse6f7721f2016-02-24 22:08:19 +00003745ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
3746 if (RN->isSubRegion())
3747 return getStmtFor(RN->getNodeAs<Region>());
3748 return getStmtFor(RN->getNodeAs<BasicBlock>());
3749}
3750
3751ScopStmt *Scop::getStmtFor(Region *R) const {
3752 ScopStmt *Stmt = getStmtFor(R->getEntry());
3753 assert(!Stmt || Stmt->getRegion() == R);
3754 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00003755}
3756
Johannes Doerfert96425c22015-08-30 21:13:53 +00003757int Scop::getRelativeLoopDepth(const Loop *L) const {
3758 Loop *OuterLoop =
3759 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3760 if (!OuterLoop)
3761 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003762 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3763}
3764
Michael Krused868b5d2015-09-10 15:25:24 +00003765void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003766 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003767
3768 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3769 // true, are not modeled as ordinary PHI nodes as they are not part of the
3770 // region. However, we model the operands in the predecessor blocks that are
3771 // part of the region as regular scalar accesses.
3772
3773 // If we can synthesize a PHI we can skip it, however only if it is in
3774 // the region. If it is not it can only be in the exit block of the region.
3775 // In this case we model the operands but not the PHI itself.
Michael Krusec7e0d9c2016-03-01 21:44:06 +00003776 auto *Scope = LI->getLoopFor(PHI->getParent());
3777 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R, Scope))
Michael Kruse7bf39442015-09-10 12:46:52 +00003778 return;
3779
3780 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3781 // detection. Hence, the PHI is a load of a new memory location in which the
3782 // incoming value was written at the end of the incoming basic block.
3783 bool OnlyNonAffineSubRegionOperands = true;
3784 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3785 Value *Op = PHI->getIncomingValue(u);
3786 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3787
3788 // Do not build scalar dependences inside a non-affine subregion.
3789 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3790 continue;
3791
3792 OnlyNonAffineSubRegionOperands = false;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00003793 ensurePHIWrite(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003794 }
3795
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003796 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3797 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003798 }
3799}
3800
Michael Kruse2e02d562016-02-06 09:19:40 +00003801void ScopInfo::buildScalarDependences(Instruction *Inst) {
3802 assert(!isa<PHINode>(Inst));
Michael Kruse7bf39442015-09-10 12:46:52 +00003803
Michael Kruse2e02d562016-02-06 09:19:40 +00003804 // Pull-in required operands.
3805 for (Use &Op : Inst->operands())
3806 ensureValueRead(Op.get(), Inst->getParent());
3807}
Michael Kruse7bf39442015-09-10 12:46:52 +00003808
Michael Kruse2e02d562016-02-06 09:19:40 +00003809void ScopInfo::buildEscapingDependences(Instruction *Inst) {
3810 Region *R = &scop->getRegion();
Michael Kruse7bf39442015-09-10 12:46:52 +00003811
Michael Kruse2e02d562016-02-06 09:19:40 +00003812 // Check for uses of this instruction outside the scop. Because we do not
3813 // iterate over such instructions and therefore did not "ensure" the existence
3814 // of a write, we must determine such use here.
3815 for (Use &U : Inst->uses()) {
3816 Instruction *UI = dyn_cast<Instruction>(U.getUser());
3817 if (!UI)
Michael Kruse7bf39442015-09-10 12:46:52 +00003818 continue;
3819
Michael Kruse2e02d562016-02-06 09:19:40 +00003820 BasicBlock *UseParent = getUseBlock(U);
3821 BasicBlock *UserParent = UI->getParent();
Michael Kruse7bf39442015-09-10 12:46:52 +00003822
Michael Kruse2e02d562016-02-06 09:19:40 +00003823 // An escaping value is either used by an instruction not within the scop,
3824 // or (when the scop region's exit needs to be simplified) by a PHI in the
3825 // scop's exit block. This is because region simplification before code
3826 // generation inserts new basic blocks before the PHI such that its incoming
3827 // blocks are not in the scop anymore.
3828 if (!R->contains(UseParent) ||
3829 (isa<PHINode>(UI) && UserParent == R->getExit() &&
3830 R->getExitingBlock())) {
3831 // At least one escaping use found.
3832 ensureValueWrite(Inst);
3833 break;
Michael Kruse7bf39442015-09-10 12:46:52 +00003834 }
3835 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003836}
3837
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003838bool ScopInfo::buildAccessMultiDimFixed(
Michael Kruse70131d32016-01-27 17:09:17 +00003839 MemAccInst Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003840 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3841 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse70131d32016-01-27 17:09:17 +00003842 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00003843 Type *ElementType = Val->getType();
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003844 Value *Address = Inst.getPointerOperand();
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003845 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003846 const SCEVUnknown *BasePointer =
3847 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003848 enum MemoryAccess::AccessType Type =
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003849 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003850
Michael Kruse37d136e2016-02-26 16:08:24 +00003851 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3852 auto *Src = BitCast->getOperand(0);
3853 auto *SrcTy = Src->getType();
3854 auto *DstTy = BitCast->getType();
3855 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3856 Address = Src;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003857 }
Michael Kruse37d136e2016-02-26 16:08:24 +00003858
3859 auto *GEP = dyn_cast<GetElementPtrInst>(Address);
3860 if (!GEP)
3861 return false;
3862
3863 std::vector<const SCEV *> Subscripts;
3864 std::vector<int> Sizes;
3865 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3866 auto *BasePtr = GEP->getOperand(0);
3867
3868 std::vector<const SCEV *> SizesSCEV;
3869
3870 for (auto *Subscript : Subscripts) {
3871 InvariantLoadsSetTy AccessILS;
Michael Kruse09eb4452016-03-03 22:10:47 +00003872 if (!isAffineExpr(R, L, Subscript, *SE, nullptr, &AccessILS))
Michael Kruse37d136e2016-02-26 16:08:24 +00003873 return false;
3874
3875 for (LoadInst *LInst : AccessILS)
3876 if (!ScopRIL.count(LInst))
3877 return false;
3878 }
3879
3880 if (Sizes.empty())
3881 return false;
3882
3883 for (auto V : Sizes)
3884 SizesSCEV.push_back(SE->getSCEV(
3885 ConstantInt::get(IntegerType::getInt64Ty(BasePtr->getContext()), V)));
3886
3887 addArrayAccess(Inst, Type, BasePointer->getValue(), ElementType, true,
3888 Subscripts, SizesSCEV, Val);
3889 return true;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003890}
3891
3892bool ScopInfo::buildAccessMultiDimParam(
3893 MemAccInst Inst, Loop *L, Region *R,
3894 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
Hongbin Zheng22623202016-02-15 00:20:58 +00003895 const InvariantLoadsSetTy &ScopRIL, const MapInsnToMemAcc &InsnToMemAcc) {
Michael Kruse37d136e2016-02-26 16:08:24 +00003896 if (!PollyDelinearize)
3897 return false;
3898
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003899 Value *Address = Inst.getPointerOperand();
3900 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00003901 Type *ElementType = Val->getType();
3902 unsigned ElementSize = DL->getTypeAllocSize(ElementType);
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003903 enum MemoryAccess::AccessType Type =
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003904 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003905
3906 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
3907 const SCEVUnknown *BasePointer =
3908 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3909
3910 assert(BasePointer && "Could not find base pointer");
3911 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003912
Michael Kruse7bf39442015-09-10 12:46:52 +00003913 auto AccItr = InsnToMemAcc.find(Inst);
Michael Kruse37d136e2016-02-26 16:08:24 +00003914 if (AccItr == InsnToMemAcc.end())
3915 return false;
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003916
Michael Kruse37d136e2016-02-26 16:08:24 +00003917 std::vector<const SCEV *> Sizes(
3918 AccItr->second.Shape->DelinearizedSizes.begin(),
3919 AccItr->second.Shape->DelinearizedSizes.end());
3920 // Remove the element size. This information is already provided by the
3921 // ElementSize parameter. In case the element size of this access and the
3922 // element size used for delinearization differs the delinearization is
3923 // incorrect. Hence, we invalidate the scop.
3924 //
3925 // TODO: Handle delinearization with differing element sizes.
3926 auto DelinearizedSize =
3927 cast<SCEVConstant>(Sizes.back())->getAPInt().getSExtValue();
3928 Sizes.pop_back();
3929 if (ElementSize != DelinearizedSize)
3930 scop->invalidate(DELINEARIZATION, Inst->getDebugLoc());
3931
3932 addArrayAccess(Inst, Type, BasePointer->getValue(), ElementType, true,
3933 AccItr->second.DelinearizedSubscripts, Sizes, Val);
3934 return true;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003935}
3936
Johannes Doerfertcea61932016-02-21 19:13:19 +00003937bool ScopInfo::buildAccessMemIntrinsic(
3938 MemAccInst Inst, Loop *L, Region *R,
3939 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3940 const InvariantLoadsSetTy &ScopRIL) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003941 auto *MemIntr = dyn_cast_or_null<MemIntrinsic>(Inst);
3942
3943 if (MemIntr == nullptr)
Johannes Doerfertcea61932016-02-21 19:13:19 +00003944 return false;
3945
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003946 auto *LengthVal = SE->getSCEVAtScope(MemIntr->getLength(), L);
Johannes Doerfertcea61932016-02-21 19:13:19 +00003947 assert(LengthVal);
3948
Johannes Doerferta7920982016-02-25 14:08:48 +00003949 // Check if the length val is actually affine or if we overapproximate it
3950 InvariantLoadsSetTy AccessILS;
Michael Kruse09eb4452016-03-03 22:10:47 +00003951 bool LengthIsAffine = isAffineExpr(R, L, LengthVal, *SE, nullptr, &AccessILS);
Johannes Doerferta7920982016-02-25 14:08:48 +00003952 for (LoadInst *LInst : AccessILS)
3953 if (!ScopRIL.count(LInst))
3954 LengthIsAffine = false;
3955 if (!LengthIsAffine)
3956 LengthVal = nullptr;
3957
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003958 auto *DestPtrVal = MemIntr->getDest();
Johannes Doerfertcea61932016-02-21 19:13:19 +00003959 assert(DestPtrVal);
Johannes Doerfert733ea342016-03-24 13:50:04 +00003960
Johannes Doerfertcea61932016-02-21 19:13:19 +00003961 auto *DestAccFunc = SE->getSCEVAtScope(DestPtrVal, L);
3962 assert(DestAccFunc);
Johannes Doerfert733ea342016-03-24 13:50:04 +00003963 // Ignore accesses to "NULL".
3964 // TODO: We could use this to optimize the region further, e.g., intersect
3965 // the context with
3966 // isl_set_complement(isl_set_params(getDomain()))
3967 // as we know it would be undefined to execute this instruction anyway.
3968 if (DestAccFunc->isZero())
3969 return true;
3970
Johannes Doerfertcea61932016-02-21 19:13:19 +00003971 auto *DestPtrSCEV = dyn_cast<SCEVUnknown>(SE->getPointerBase(DestAccFunc));
3972 assert(DestPtrSCEV);
3973 DestAccFunc = SE->getMinusSCEV(DestAccFunc, DestPtrSCEV);
3974 addArrayAccess(Inst, MemoryAccess::MUST_WRITE, DestPtrSCEV->getValue(),
3975 IntegerType::getInt8Ty(DestPtrVal->getContext()), false,
3976 {DestAccFunc, LengthVal}, {}, Inst.getValueOperand());
3977
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003978 auto *MemTrans = dyn_cast<MemTransferInst>(MemIntr);
3979 if (!MemTrans)
Johannes Doerfertcea61932016-02-21 19:13:19 +00003980 return true;
3981
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003982 auto *SrcPtrVal = MemTrans->getSource();
Johannes Doerfertcea61932016-02-21 19:13:19 +00003983 assert(SrcPtrVal);
Johannes Doerfert733ea342016-03-24 13:50:04 +00003984
Johannes Doerfertcea61932016-02-21 19:13:19 +00003985 auto *SrcAccFunc = SE->getSCEVAtScope(SrcPtrVal, L);
3986 assert(SrcAccFunc);
Johannes Doerfert733ea342016-03-24 13:50:04 +00003987 // Ignore accesses to "NULL".
3988 // TODO: See above TODO
3989 if (SrcAccFunc->isZero())
3990 return true;
3991
Johannes Doerfertcea61932016-02-21 19:13:19 +00003992 auto *SrcPtrSCEV = dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccFunc));
3993 assert(SrcPtrSCEV);
3994 SrcAccFunc = SE->getMinusSCEV(SrcAccFunc, SrcPtrSCEV);
3995 addArrayAccess(Inst, MemoryAccess::READ, SrcPtrSCEV->getValue(),
3996 IntegerType::getInt8Ty(SrcPtrVal->getContext()), false,
3997 {SrcAccFunc, LengthVal}, {}, Inst.getValueOperand());
3998
3999 return true;
4000}
4001
Johannes Doerferta7920982016-02-25 14:08:48 +00004002bool ScopInfo::buildAccessCallInst(
4003 MemAccInst Inst, Loop *L, Region *R,
4004 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
4005 const InvariantLoadsSetTy &ScopRIL) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004006 auto *CI = dyn_cast_or_null<CallInst>(Inst);
4007
4008 if (CI == nullptr)
Johannes Doerferta7920982016-02-25 14:08:48 +00004009 return false;
4010
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004011 if (CI->doesNotAccessMemory() || isIgnoredIntrinsic(CI))
Johannes Doerferta7920982016-02-25 14:08:48 +00004012 return true;
4013
4014 bool ReadOnly = false;
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004015 auto *AF = SE->getConstant(IntegerType::getInt64Ty(CI->getContext()), 0);
4016 auto *CalledFunction = CI->getCalledFunction();
Johannes Doerferta7920982016-02-25 14:08:48 +00004017 switch (AA->getModRefBehavior(CalledFunction)) {
4018 case llvm::FMRB_UnknownModRefBehavior:
4019 llvm_unreachable("Unknown mod ref behaviour cannot be represented.");
4020 case llvm::FMRB_DoesNotAccessMemory:
4021 return true;
4022 case llvm::FMRB_OnlyReadsMemory:
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004023 GlobalReads.push_back(CI);
Johannes Doerferta7920982016-02-25 14:08:48 +00004024 return true;
4025 case llvm::FMRB_OnlyReadsArgumentPointees:
4026 ReadOnly = true;
4027 // Fall through
4028 case llvm::FMRB_OnlyAccessesArgumentPointees:
4029 auto AccType = ReadOnly ? MemoryAccess::READ : MemoryAccess::MAY_WRITE;
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004030 for (const auto &Arg : CI->arg_operands()) {
Johannes Doerferta7920982016-02-25 14:08:48 +00004031 if (!Arg->getType()->isPointerTy())
4032 continue;
4033
4034 auto *ArgSCEV = SE->getSCEVAtScope(Arg, L);
4035 if (ArgSCEV->isZero())
4036 continue;
4037
4038 auto *ArgBasePtr = cast<SCEVUnknown>(SE->getPointerBase(ArgSCEV));
4039 addArrayAccess(Inst, AccType, ArgBasePtr->getValue(),
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004040 ArgBasePtr->getType(), false, {AF}, {}, CI);
Johannes Doerferta7920982016-02-25 14:08:48 +00004041 }
4042 return true;
4043 }
4044
4045 return true;
4046}
4047
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004048void ScopInfo::buildAccessSingleDim(
4049 MemAccInst Inst, Loop *L, Region *R,
4050 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
4051 const InvariantLoadsSetTy &ScopRIL) {
4052 Value *Address = Inst.getPointerOperand();
4053 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004054 Type *ElementType = Val->getType();
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004055 enum MemoryAccess::AccessType Type =
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004056 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004057
4058 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
4059 const SCEVUnknown *BasePointer =
4060 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
4061
4062 assert(BasePointer && "Could not find base pointer");
4063 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
Michael Kruse7bf39442015-09-10 12:46:52 +00004064
4065 // Check if the access depends on a loop contained in a non-affine subregion.
4066 bool isVariantInNonAffineLoop = false;
4067 if (BoxedLoops) {
4068 SetVector<const Loop *> Loops;
4069 findLoops(AccessFunction, Loops);
4070 for (const Loop *L : Loops)
4071 if (BoxedLoops->count(L))
4072 isVariantInNonAffineLoop = true;
4073 }
4074
Johannes Doerfert09e36972015-10-07 20:17:36 +00004075 InvariantLoadsSetTy AccessILS;
Michael Kruse09eb4452016-03-03 22:10:47 +00004076 bool IsAffine = !isVariantInNonAffineLoop &&
4077 isAffineExpr(R, L, AccessFunction, *SE,
4078 BasePointer->getValue(), &AccessILS);
Johannes Doerfert09e36972015-10-07 20:17:36 +00004079
4080 for (LoadInst *LInst : AccessILS)
4081 if (!ScopRIL.count(LInst))
4082 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00004083
Michael Krusee2bccbb2015-09-18 19:59:43 +00004084 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
4085 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00004086
Johannes Doerfertcea61932016-02-21 19:13:19 +00004087 addArrayAccess(Inst, Type, BasePointer->getValue(), ElementType, IsAffine,
Tobias Grosser5d51afe2016-02-02 16:46:45 +00004088 {AccessFunction}, {}, Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00004089}
4090
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004091void ScopInfo::buildMemoryAccess(
4092 MemAccInst Inst, Loop *L, Region *R,
4093 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
Hongbin Zheng22623202016-02-15 00:20:58 +00004094 const InvariantLoadsSetTy &ScopRIL, const MapInsnToMemAcc &InsnToMemAcc) {
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004095
Johannes Doerfertcea61932016-02-21 19:13:19 +00004096 if (buildAccessMemIntrinsic(Inst, L, R, BoxedLoops, ScopRIL))
4097 return;
4098
Johannes Doerferta7920982016-02-25 14:08:48 +00004099 if (buildAccessCallInst(Inst, L, R, BoxedLoops, ScopRIL))
4100 return;
4101
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004102 if (buildAccessMultiDimFixed(Inst, L, R, BoxedLoops, ScopRIL))
4103 return;
4104
Hongbin Zheng22623202016-02-15 00:20:58 +00004105 if (buildAccessMultiDimParam(Inst, L, R, BoxedLoops, ScopRIL, InsnToMemAcc))
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004106 return;
4107
4108 buildAccessSingleDim(Inst, L, R, BoxedLoops, ScopRIL);
4109}
4110
Hongbin Zheng22623202016-02-15 00:20:58 +00004111void ScopInfo::buildAccessFunctions(Region &R, Region &SR,
4112 const MapInsnToMemAcc &InsnToMemAcc) {
Michael Kruse7bf39442015-09-10 12:46:52 +00004113
4114 if (SD->isNonAffineSubRegion(&SR, &R)) {
4115 for (BasicBlock *BB : SR.blocks())
Hongbin Zheng22623202016-02-15 00:20:58 +00004116 buildAccessFunctions(R, *BB, InsnToMemAcc, &SR);
Michael Kruse7bf39442015-09-10 12:46:52 +00004117 return;
4118 }
4119
4120 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
4121 if (I->isSubRegion())
Hongbin Zheng22623202016-02-15 00:20:58 +00004122 buildAccessFunctions(R, *I->getNodeAs<Region>(), InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00004123 else
Hongbin Zheng22623202016-02-15 00:20:58 +00004124 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>(), InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00004125}
4126
Johannes Doerferta8781032016-02-02 14:14:40 +00004127void ScopInfo::buildStmts(Region &R, Region &SR) {
Michael Krusecac948e2015-10-02 13:53:07 +00004128
Johannes Doerferta8781032016-02-02 14:14:40 +00004129 if (SD->isNonAffineSubRegion(&SR, &R)) {
Michael Krusecac948e2015-10-02 13:53:07 +00004130 scop->addScopStmt(nullptr, &SR);
4131 return;
4132 }
4133
4134 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
4135 if (I->isSubRegion())
Johannes Doerferta8781032016-02-02 14:14:40 +00004136 buildStmts(R, *I->getNodeAs<Region>());
Michael Krusecac948e2015-10-02 13:53:07 +00004137 else
4138 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
4139}
4140
Michael Krused868b5d2015-09-10 15:25:24 +00004141void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
Hongbin Zheng22623202016-02-15 00:20:58 +00004142 const MapInsnToMemAcc &InsnToMemAcc,
Michael Krused868b5d2015-09-10 15:25:24 +00004143 Region *NonAffineSubRegion,
4144 bool IsExitBlock) {
Tobias Grosser910cf262015-11-11 20:15:49 +00004145 // We do not build access functions for error blocks, as they may contain
4146 // instructions we can not model.
Johannes Doerfertc36d39b2016-02-02 14:14:20 +00004147 if (isErrorBlock(BB, R, *LI, *DT) && !IsExitBlock)
Tobias Grosser910cf262015-11-11 20:15:49 +00004148 return;
4149
Michael Kruse7bf39442015-09-10 12:46:52 +00004150 Loop *L = LI->getLoopFor(&BB);
4151
4152 // The set of loops contained in non-affine subregions that are part of R.
4153 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
4154
Johannes Doerfert09e36972015-10-07 20:17:36 +00004155 // The set of loads that are required to be invariant.
4156 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
4157
Michael Kruse2e02d562016-02-06 09:19:40 +00004158 for (Instruction &Inst : BB) {
4159 PHINode *PHI = dyn_cast<PHINode>(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00004160 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00004161 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00004162
4163 // For the exit block we stop modeling after the last PHI node.
4164 if (!PHI && IsExitBlock)
4165 break;
4166
Johannes Doerfert09e36972015-10-07 20:17:36 +00004167 // TODO: At this point we only know that elements of ScopRIL have to be
4168 // invariant and will be hoisted for the SCoP to be processed. Though,
4169 // there might be other invariant accesses that will be hoisted and
4170 // that would allow to make a non-affine access affine.
Michael Kruse70131d32016-01-27 17:09:17 +00004171 if (auto MemInst = MemAccInst::dyn_cast(Inst))
Hongbin Zheng22623202016-02-15 00:20:58 +00004172 buildMemoryAccess(MemInst, L, &R, BoxedLoops, ScopRIL, InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00004173
Michael Kruse2e02d562016-02-06 09:19:40 +00004174 if (isIgnoredIntrinsic(&Inst))
Michael Kruse7bf39442015-09-10 12:46:52 +00004175 continue;
4176
Tobias Grosser0904c692016-03-16 23:33:54 +00004177 // PHI nodes have already been modeled above and TerminatorInsts that are
4178 // not part of a non-affine subregion are fully modeled and regenerated
4179 // from the polyhedral domains. Hence, they do not need to be modeled as
4180 // explicit data dependences.
4181 if (!PHI && (!isa<TerminatorInst>(&Inst) || NonAffineSubRegion))
Michael Kruse2e02d562016-02-06 09:19:40 +00004182 buildScalarDependences(&Inst);
Tobias Grosser0904c692016-03-16 23:33:54 +00004183
Michael Kruse2e02d562016-02-06 09:19:40 +00004184 if (!IsExitBlock)
4185 buildEscapingDependences(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00004186 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00004187}
Michael Kruse7bf39442015-09-10 12:46:52 +00004188
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004189MemoryAccess *ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004190 MemoryAccess::AccessType AccType,
4191 Value *BaseAddress, Type *ElementType,
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004192 bool Affine, Value *AccessValue,
4193 ArrayRef<const SCEV *> Subscripts,
4194 ArrayRef<const SCEV *> Sizes,
4195 ScopArrayInfo::MemoryKind Kind) {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004196 ScopStmt *Stmt = scop->getStmtFor(BB);
Michael Krusecac948e2015-10-02 13:53:07 +00004197
4198 // Do not create a memory access for anything not in the SCoP. It would be
4199 // ignored anyway.
4200 if (!Stmt)
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004201 return nullptr;
Michael Krusecac948e2015-10-02 13:53:07 +00004202
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00004203 AccFuncSetType &AccList = scop->getOrCreateAccessFunctions(BB);
Michael Krusee2bccbb2015-09-18 19:59:43 +00004204 Value *BaseAddr = BaseAddress;
4205 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
4206
Tobias Grosserf4f68702015-12-14 15:05:37 +00004207 bool isKnownMustAccess = false;
4208
4209 // Accesses in single-basic block statements are always excuted.
4210 if (Stmt->isBlockStmt())
4211 isKnownMustAccess = true;
4212
4213 if (Stmt->isRegionStmt()) {
4214 // Accesses that dominate the exit block of a non-affine region are always
4215 // executed. In non-affine regions there may exist MK_Values that do not
4216 // dominate the exit. MK_Values will always dominate the exit and MK_PHIs
4217 // only if there is at most one PHI_WRITE in the non-affine region.
4218 if (DT->dominates(BB, Stmt->getRegion()->getExit()))
4219 isKnownMustAccess = true;
4220 }
4221
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004222 // Non-affine PHI writes do not "happen" at a particular instruction, but
4223 // after exiting the statement. Therefore they are guaranteed execute and
4224 // overwrite the old value.
4225 if (Kind == ScopArrayInfo::MK_PHI || Kind == ScopArrayInfo::MK_ExitPHI)
4226 isKnownMustAccess = true;
4227
Johannes Doerfertcea61932016-02-21 19:13:19 +00004228 if (!isKnownMustAccess && AccType == MemoryAccess::MUST_WRITE)
4229 AccType = MemoryAccess::MAY_WRITE;
Michael Krusecac948e2015-10-02 13:53:07 +00004230
Johannes Doerfertcea61932016-02-21 19:13:19 +00004231 AccList.emplace_back(Stmt, Inst, AccType, BaseAddress, ElementType, Affine,
Tobias Grossera535dff2015-12-13 19:59:01 +00004232 Subscripts, Sizes, AccessValue, Kind, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00004233 Stmt->addAccess(&AccList.back());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004234 return &AccList.back();
Michael Kruse7bf39442015-09-10 12:46:52 +00004235}
4236
Michael Kruse70131d32016-01-27 17:09:17 +00004237void ScopInfo::addArrayAccess(MemAccInst MemAccInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004238 MemoryAccess::AccessType AccType,
4239 Value *BaseAddress, Type *ElementType,
4240 bool IsAffine, ArrayRef<const SCEV *> Subscripts,
Tobias Grossera535dff2015-12-13 19:59:01 +00004241 ArrayRef<const SCEV *> Sizes,
4242 Value *AccessValue) {
Johannes Doerferta7920982016-02-25 14:08:48 +00004243 ArrayBasePointers.insert(BaseAddress);
Hongbin Zhengf3d66122016-02-26 09:47:11 +00004244 addMemoryAccess(MemAccInst->getParent(), MemAccInst, AccType, BaseAddress,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004245 ElementType, IsAffine, AccessValue, Subscripts, Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00004246 ScopArrayInfo::MK_Array);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004247}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004248
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004249void ScopInfo::ensureValueWrite(Instruction *Inst) {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004250 ScopStmt *Stmt = scop->getStmtFor(Inst);
Michael Kruse436db622016-01-26 13:33:10 +00004251
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004252 // Inst not defined within this SCoP.
Michael Kruse436db622016-01-26 13:33:10 +00004253 if (!Stmt)
4254 return;
4255
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004256 // Do not process further if the instruction is already written.
4257 if (Stmt->lookupValueWriteOf(Inst))
Michael Kruse436db622016-01-26 13:33:10 +00004258 return;
4259
Johannes Doerfertcea61932016-02-21 19:13:19 +00004260 addMemoryAccess(Inst->getParent(), Inst, MemoryAccess::MUST_WRITE, Inst,
4261 Inst->getType(), true, Inst, ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004262 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004263}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004264
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004265void ScopInfo::ensureValueRead(Value *V, BasicBlock *UserBB) {
Michael Krusefd463082016-01-27 22:51:56 +00004266
Michael Kruse2e02d562016-02-06 09:19:40 +00004267 // There cannot be an "access" for literal constants. BasicBlock references
4268 // (jump destinations) also never change.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004269 if ((isa<Constant>(V) && !isa<GlobalVariable>(V)) || isa<BasicBlock>(V))
Michael Kruse2e02d562016-02-06 09:19:40 +00004270 return;
4271
Michael Krusefd463082016-01-27 22:51:56 +00004272 // If the instruction can be synthesized and the user is in the region we do
4273 // not need to add a value dependences.
4274 Region &ScopRegion = scop->getRegion();
Michael Krusec7e0d9c2016-03-01 21:44:06 +00004275 auto *Scope = LI->getLoopFor(UserBB);
4276 if (canSynthesize(V, LI, SE, &ScopRegion, Scope))
Michael Krusefd463082016-01-27 22:51:56 +00004277 return;
4278
Michael Kruse2e02d562016-02-06 09:19:40 +00004279 // Do not build scalar dependences for required invariant loads as we will
4280 // hoist them later on anyway or drop the SCoP if we cannot.
Johannes Doerferta90943d2016-02-21 16:37:25 +00004281 auto *ScopRIL = SD->getRequiredInvariantLoads(&ScopRegion);
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004282 if (ScopRIL->count(dyn_cast<LoadInst>(V)))
Michael Kruse2e02d562016-02-06 09:19:40 +00004283 return;
4284
4285 // Determine the ScopStmt containing the value's definition and use. There is
4286 // no defining ScopStmt if the value is a function argument, a global value,
4287 // or defined outside the SCoP.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004288 Instruction *ValueInst = dyn_cast<Instruction>(V);
Michael Kruse6f7721f2016-02-24 22:08:19 +00004289 ScopStmt *ValueStmt = ValueInst ? scop->getStmtFor(ValueInst) : nullptr;
Michael Kruse2e02d562016-02-06 09:19:40 +00004290
Michael Kruse6f7721f2016-02-24 22:08:19 +00004291 ScopStmt *UserStmt = scop->getStmtFor(UserBB);
Michael Krusead28e5a2016-01-26 13:33:15 +00004292
4293 // We do not model uses outside the scop.
4294 if (!UserStmt)
4295 return;
4296
Michael Kruse2e02d562016-02-06 09:19:40 +00004297 // Add MemoryAccess for invariant values only if requested.
4298 if (!ModelReadOnlyScalars && !ValueStmt)
4299 return;
4300
4301 // Ignore use-def chains within the same ScopStmt.
4302 if (ValueStmt == UserStmt)
4303 return;
4304
Michael Krusead28e5a2016-01-26 13:33:15 +00004305 // Do not create another MemoryAccess for reloading the value if one already
4306 // exists.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004307 if (UserStmt->lookupValueReadOf(V))
Michael Krusead28e5a2016-01-26 13:33:15 +00004308 return;
4309
Johannes Doerfertcea61932016-02-21 19:13:19 +00004310 addMemoryAccess(UserBB, nullptr, MemoryAccess::READ, V, V->getType(), true, V,
Michael Kruse8d0b7342015-09-25 21:21:00 +00004311 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004312 ScopArrayInfo::MK_Value);
Michael Kruse2e02d562016-02-06 09:19:40 +00004313 if (ValueInst)
4314 ensureValueWrite(ValueInst);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004315}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004316
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004317void ScopInfo::ensurePHIWrite(PHINode *PHI, BasicBlock *IncomingBlock,
4318 Value *IncomingValue, bool IsExitBlock) {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004319 ScopStmt *IncomingStmt = scop->getStmtFor(IncomingBlock);
Michael Kruse2e02d562016-02-06 09:19:40 +00004320 if (!IncomingStmt)
4321 return;
4322
4323 // Take care for the incoming value being available in the incoming block.
4324 // This must be done before the check for multiple PHI writes because multiple
4325 // exiting edges from subregion each can be the effective written value of the
4326 // subregion. As such, all of them must be made available in the subregion
4327 // statement.
4328 ensureValueRead(IncomingValue, IncomingBlock);
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004329
4330 // Do not add more than one MemoryAccess per PHINode and ScopStmt.
4331 if (MemoryAccess *Acc = IncomingStmt->lookupPHIWriteOf(PHI)) {
4332 assert(Acc->getAccessInstruction() == PHI);
4333 Acc->addIncoming(IncomingBlock, IncomingValue);
4334 return;
4335 }
4336
4337 MemoryAccess *Acc = addMemoryAccess(
Michael Kruse375cb5f2016-02-24 22:08:24 +00004338 IncomingStmt->getEntryBlock(), PHI, MemoryAccess::MUST_WRITE, PHI,
4339 PHI->getType(), true, PHI, ArrayRef<const SCEV *>(),
4340 ArrayRef<const SCEV *>(),
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004341 IsExitBlock ? ScopArrayInfo::MK_ExitPHI : ScopArrayInfo::MK_PHI);
4342 assert(Acc);
4343 Acc->addIncoming(IncomingBlock, IncomingValue);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004344}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004345
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004346void ScopInfo::addPHIReadAccess(PHINode *PHI) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00004347 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI,
4348 PHI->getType(), true, PHI, ArrayRef<const SCEV *>(),
4349 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004350}
4351
Michael Krusedaf66942015-12-13 22:10:37 +00004352void ScopInfo::buildScop(Region &R, AssumptionCache &AC) {
Michael Kruse9d080092015-09-11 21:41:48 +00004353 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Michael Kruse09eb4452016-03-03 22:10:47 +00004354 scop.reset(new Scop(R, *SE, *LI, MaxLoopDepth));
Michael Kruse7bf39442015-09-10 12:46:52 +00004355
Johannes Doerferta8781032016-02-02 14:14:40 +00004356 buildStmts(R, R);
Hongbin Zheng22623202016-02-15 00:20:58 +00004357 buildAccessFunctions(R, R, *SD->getInsnToMemAccMap(&R));
Michael Kruse7bf39442015-09-10 12:46:52 +00004358
4359 // In case the region does not have an exiting block we will later (during
4360 // code generation) split the exit block. This will move potential PHI nodes
4361 // from the current exit block into the new region exiting block. Hence, PHI
4362 // nodes that are at this point not part of the region will be.
4363 // To handle these PHI nodes later we will now model their operands as scalar
4364 // accesses. Note that we do not model anything in the exit block if we have
4365 // an exiting block in the region, as there will not be any splitting later.
4366 if (!R.getExitingBlock())
Hongbin Zheng22623202016-02-15 00:20:58 +00004367 buildAccessFunctions(R, *R.getExit(), *SD->getInsnToMemAccMap(&R), nullptr,
4368 /* IsExitBlock */ true);
Michael Kruse7bf39442015-09-10 12:46:52 +00004369
Johannes Doerferta7920982016-02-25 14:08:48 +00004370 // Create memory accesses for global reads since all arrays are now known.
4371 auto *AF = SE->getConstant(IntegerType::getInt64Ty(SE->getContext()), 0);
4372 for (auto *GlobalRead : GlobalReads)
4373 for (auto *BP : ArrayBasePointers)
4374 addArrayAccess(MemAccInst(GlobalRead), MemoryAccess::READ, BP,
4375 BP->getType(), false, {AF}, {}, GlobalRead);
4376
Hongbin Zheng192f69a2016-02-13 15:12:54 +00004377 scop->init(*AA, AC, *SD, *DT, *LI);
Michael Kruse7bf39442015-09-10 12:46:52 +00004378}
4379
Michael Krused868b5d2015-09-10 15:25:24 +00004380void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00004381 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00004382 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00004383 return;
4384 }
4385
Michael Kruse9d080092015-09-11 21:41:48 +00004386 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00004387}
4388
Hongbin Zhengfec32802016-02-13 15:13:02 +00004389void ScopInfo::clear() { scop.reset(); }
Michael Kruse7bf39442015-09-10 12:46:52 +00004390
4391//===----------------------------------------------------------------------===//
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004392ScopInfo::ScopInfo() : RegionPass(ID) {}
Tobias Grosserb76f38532011-08-20 11:11:25 +00004393
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004394ScopInfo::~ScopInfo() { clear(); }
Tobias Grosserb76f38532011-08-20 11:11:25 +00004395
Tobias Grosser75805372011-04-29 06:27:02 +00004396void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00004397 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00004398 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00004399 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00004400 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4401 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004402 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004403 AU.addRequired<AssumptionCacheTracker>();
Tobias Grosser75805372011-04-29 06:27:02 +00004404 AU.setPreservesAll();
4405}
4406
4407bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00004408 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00004409
Michael Krused868b5d2015-09-10 15:25:24 +00004410 if (!SD->isMaxRegionInScop(*R))
4411 return false;
4412
4413 Function *F = R->getEntry()->getParent();
4414 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4415 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4416 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Johannes Doerferta1f291e2016-02-02 14:15:13 +00004417 DL = &F->getParent()->getDataLayout();
Michael Krusedaf66942015-12-13 22:10:37 +00004418 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004419 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krused868b5d2015-09-10 15:25:24 +00004420
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004421 DebugLoc Beg, End;
4422 getDebugLocations(R, Beg, End);
4423 std::string Msg = "SCoP begins here.";
4424 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg);
4425
Michael Krusedaf66942015-12-13 22:10:37 +00004426 buildScop(*R, AC);
Tobias Grosser75805372011-04-29 06:27:02 +00004427
Tobias Grosserd6a50b32015-05-30 06:26:21 +00004428 DEBUG(scop->print(dbgs()));
4429
Michael Kruseafe06702015-10-02 16:33:27 +00004430 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004431 Msg = "SCoP ends here but was dismissed.";
Hongbin Zhengfec32802016-02-13 15:13:02 +00004432 scop.reset();
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004433 } else {
4434 Msg = "SCoP ends here.";
4435 ++ScopFound;
4436 if (scop->getMaxLoopDepth() > 0)
4437 ++RichScopFound;
Johannes Doerfert43788c52015-08-20 05:58:56 +00004438 }
4439
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004440 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg);
4441
Tobias Grosser75805372011-04-29 06:27:02 +00004442 return false;
4443}
4444
4445char ScopInfo::ID = 0;
4446
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004447Pass *polly::createScopInfoPass() { return new ScopInfo(); }
4448
Tobias Grosser73600b82011-10-08 00:30:40 +00004449INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
4450 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004451 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004452INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004453INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004454INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004455INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004456INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004457INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004458INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00004459INITIALIZE_PASS_END(ScopInfo, "polly-scops",
4460 "Polly - Create polyhedral description of Scops", false,
4461 false)