blob: 47be0dbbe3c877eab42441cdf04a217369d57ad9 [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 Grosser20a4c0c2015-11-11 16:22:36 +0000102static cl::opt<int> MaxDisjunctsAssumed(
103 "polly-max-disjuncts-assumed",
104 cl::desc("The maximal number of disjuncts we allow in the assumption "
105 "context (this bounds compile time)"),
106 cl::Hidden, cl::ZeroOrMore, cl::init(150), cl::cat(PollyCategory));
107
Tobias Grosser4927c8e2015-11-24 12:50:02 +0000108static cl::opt<bool> IgnoreIntegerWrapping(
109 "polly-ignore-integer-wrapping",
110 cl::desc("Do not build run-time checks to proof absence of integer "
111 "wrapping"),
112 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
113
Michael Kruse7bf39442015-09-10 12:46:52 +0000114//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000115
Michael Kruse046dde42015-08-10 13:01:57 +0000116// Create a sequence of two schedules. Either argument may be null and is
117// interpreted as the empty schedule. Can also return null if both schedules are
118// empty.
119static __isl_give isl_schedule *
120combineInSequence(__isl_take isl_schedule *Prev,
121 __isl_take isl_schedule *Succ) {
122 if (!Prev)
123 return Succ;
124 if (!Succ)
125 return Prev;
126
127 return isl_schedule_sequence(Prev, Succ);
128}
129
Johannes Doerferte7044942015-02-24 11:58:30 +0000130static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
131 const ConstantRange &Range,
132 int dim,
133 enum isl_dim_type type) {
134 isl_val *V;
135 isl_ctx *ctx = isl_set_get_ctx(S);
136
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000137 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
138 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000139 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000140 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
141
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000142 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000143 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000144 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000145 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000146 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
147
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000148 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000149 return isl_set_union(SLB, SUB);
150 else
151 return isl_set_intersect(SLB, SUB);
152}
153
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000154static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
155 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
156 if (!BasePtrLI)
157 return nullptr;
158
159 if (!S->getRegion().contains(BasePtrLI))
160 return nullptr;
161
162 ScalarEvolution &SE = *S->getSE();
163
164 auto *OriginBaseSCEV =
165 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
166 if (!OriginBaseSCEV)
167 return nullptr;
168
169 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
170 if (!OriginBaseSCEVUnknown)
171 return nullptr;
172
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000173 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grossera535dff2015-12-13 19:59:01 +0000174 ScopArrayInfo::MK_Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000175}
176
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000177ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grossera535dff2015-12-13 19:59:01 +0000178 ArrayRef<const SCEV *> Sizes, enum MemoryKind Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000179 const DataLayout &DL, Scop *S)
180 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000181 std::string BasePtrName =
Tobias Grossera535dff2015-12-13 19:59:01 +0000182 getIslCompatibleName("MemRef_", BasePtr, Kind == MK_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000183 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000184
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000185 updateSizes(Sizes);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000186 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
187 if (BasePtrOriginSAI)
188 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000189}
190
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000191__isl_give isl_space *ScopArrayInfo::getSpace() const {
192 auto Space =
193 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
194 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
195 return Space;
196}
197
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000198void ScopArrayInfo::updateElementType(Type *NewElementType) {
199 if (NewElementType == ElementType)
200 return;
201
Tobias Grosserd840fc72016-02-04 13:18:42 +0000202 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
203 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
204
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000205 if (NewElementSize == OldElementSize)
206 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000207
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000208 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
209 ElementType = NewElementType;
210 } else {
211 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
212 ElementType = IntegerType::get(ElementType->getContext(), GCD);
213 }
214}
215
216bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000217 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
218 int ExtraDimsNew = NewSizes.size() - SharedDims;
219 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Tobias Grosser8286b832015-11-02 11:29:32 +0000220 for (int i = 0; i < SharedDims; i++)
221 if (NewSizes[i + ExtraDimsNew] != DimensionSizes[i + ExtraDimsOld])
222 return false;
223
224 if (DimensionSizes.size() >= NewSizes.size())
225 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000226
227 DimensionSizes.clear();
228 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
229 NewSizes.end());
230 for (isl_pw_aff *Size : DimensionSizesPw)
231 isl_pw_aff_free(Size);
232 DimensionSizesPw.clear();
233 for (const SCEV *Expr : DimensionSizes) {
234 isl_pw_aff *Size = S.getPwAff(Expr);
235 DimensionSizesPw.push_back(Size);
236 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000237 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000238}
239
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000240ScopArrayInfo::~ScopArrayInfo() {
241 isl_id_free(Id);
242 for (isl_pw_aff *Size : DimensionSizesPw)
243 isl_pw_aff_free(Size);
244}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000245
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000246std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
247
248int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000249 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000250}
251
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000252isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
253
254void ScopArrayInfo::dump() const { print(errs()); }
255
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000256void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000257 OS.indent(8) << *getElementType() << " " << getName();
258 if (getNumberOfDimensions() > 0)
259 OS << "[*]";
Tobias Grosser26253842015-11-10 14:24:21 +0000260 for (unsigned u = 1; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000261 OS << "[";
262
Tobias Grosser26253842015-11-10 14:24:21 +0000263 if (SizeAsPwAff) {
264 auto Size = getDimensionSizePw(u);
265 OS << " " << Size << " ";
266 isl_pw_aff_free(Size);
267 } else {
268 OS << *getDimensionSize(u);
269 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000270
271 OS << "]";
272 }
273
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000274 OS << ";";
275
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000276 if (BasePtrOriginSAI)
277 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
278
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000279 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000280}
281
282const ScopArrayInfo *
283ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
284 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
285 assert(Id && "Output dimension didn't have an ID");
286 return getFromId(Id);
287}
288
289const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
290 void *User = isl_id_get_user(Id);
291 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
292 isl_id_free(Id);
293 return SAI;
294}
295
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000296void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000297 auto *SAI = getScopArrayInfo();
298 auto ArraySpace = SAI->getSpace();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000299 auto AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000300 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000301
302 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
303 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
304 auto DimsMissing = DimsArray - DimsAccess;
305
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000306 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
307
Tobias Grosserd840fc72016-02-04 13:18:42 +0000308 auto Map = isl_map_from_domain_and_range(
309 isl_set_universe(AccessSpace),
310 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000311
312 for (unsigned i = 0; i < DimsMissing; i++)
313 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
314
315 for (unsigned i = DimsMissing; i < DimsArray; i++)
316 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
317
318 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000319
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000320 // For the non delinearized arrays, divide the access function of the last
321 // subscript by the size of the elements in the array.
322 //
323 // A stride one array access in C expressed as A[i] is expressed in
324 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
325 // two subsequent values of 'i' index two values that are stored next to
326 // each other in memory. By this division we make this characteristic
327 // obvious again. If the base pointer was accessed with offsets not divisible
328 // by the accesses element size, we will have choosen a smaller ArrayElemSize
329 // that divides the offsets of all accesses to this base pointer.
330 if (DimsAccess == 1) {
331 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
332 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
333 }
334
335 if (!isAffine())
336 computeBoundsOnAccessRelation(ArrayElemSize);
337
Tobias Grosserd840fc72016-02-04 13:18:42 +0000338 // Introduce multi-element accesses in case the type loaded by this memory
339 // access is larger than the canonical element type of the array.
340 //
341 // An access ((float *)A)[i] to an array char *A is modeled as
342 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000343 if (ElemBytes > ArrayElemSize) {
344 assert(ElemBytes % ArrayElemSize == 0 &&
345 "Loaded element size should be multiple of canonical element size");
346 auto Map = isl_map_from_domain_and_range(
347 isl_set_universe(isl_space_copy(ArraySpace)),
348 isl_set_universe(isl_space_copy(ArraySpace)));
349 for (unsigned i = 0; i < DimsArray - 1; i++)
350 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
351
Tobias Grosserd840fc72016-02-04 13:18:42 +0000352 isl_constraint *C;
353 isl_local_space *LS;
354
355 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000356 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
357
358 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
359 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000360 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000361 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
362 Map = isl_map_add_constraint(Map, C);
363
364 C = isl_constraint_alloc_inequality(LS);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000365 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000366 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
367 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
368 Map = isl_map_add_constraint(Map, C);
369 AccessRelation = isl_map_apply_range(AccessRelation, Map);
370 }
371
372 isl_space_free(ArraySpace);
373
Roman Gareev10595a12016-01-08 14:01:59 +0000374 assumeNoOutOfBound();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000375}
376
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000377const std::string
378MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
379 switch (RT) {
380 case MemoryAccess::RT_NONE:
381 llvm_unreachable("Requested a reduction operator string for a memory "
382 "access which isn't a reduction");
383 case MemoryAccess::RT_ADD:
384 return "+";
385 case MemoryAccess::RT_MUL:
386 return "*";
387 case MemoryAccess::RT_BOR:
388 return "|";
389 case MemoryAccess::RT_BXOR:
390 return "^";
391 case MemoryAccess::RT_BAND:
392 return "&";
393 }
394 llvm_unreachable("Unknown reduction type");
395 return "";
396}
397
Johannes Doerfertf6183392014-07-01 20:52:51 +0000398/// @brief Return the reduction type for a given binary operator
399static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
400 const Instruction *Load) {
401 if (!BinOp)
402 return MemoryAccess::RT_NONE;
403 switch (BinOp->getOpcode()) {
404 case Instruction::FAdd:
405 if (!BinOp->hasUnsafeAlgebra())
406 return MemoryAccess::RT_NONE;
407 // Fall through
408 case Instruction::Add:
409 return MemoryAccess::RT_ADD;
410 case Instruction::Or:
411 return MemoryAccess::RT_BOR;
412 case Instruction::Xor:
413 return MemoryAccess::RT_BXOR;
414 case Instruction::And:
415 return MemoryAccess::RT_BAND;
416 case Instruction::FMul:
417 if (!BinOp->hasUnsafeAlgebra())
418 return MemoryAccess::RT_NONE;
419 // Fall through
420 case Instruction::Mul:
421 if (DisableMultiplicativeReductions)
422 return MemoryAccess::RT_NONE;
423 return MemoryAccess::RT_MUL;
424 default:
425 return MemoryAccess::RT_NONE;
426 }
427}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000428
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000429/// @brief Derive the individual index expressions from a GEP instruction
430///
431/// This function optimistically assumes the GEP references into a fixed size
432/// array. If this is actually true, this function returns a list of array
433/// subscript expressions as SCEV as well as a list of integers describing
434/// the size of the individual array dimensions. Both lists have either equal
435/// length of the size list is one element shorter in case there is no known
436/// size available for the outermost array dimension.
437///
438/// @param GEP The GetElementPtr instruction to analyze.
439///
440/// @return A tuple with the subscript expressions and the dimension sizes.
441static std::tuple<std::vector<const SCEV *>, std::vector<int>>
442getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
443 std::vector<const SCEV *> Subscripts;
444 std::vector<int> Sizes;
445
446 Type *Ty = GEP->getPointerOperandType();
447
448 bool DroppedFirstDim = false;
449
Michael Kruse26ed65e2015-09-24 17:32:49 +0000450 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000451
452 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
453
454 if (i == 1) {
455 if (auto PtrTy = dyn_cast<PointerType>(Ty)) {
456 Ty = PtrTy->getElementType();
457 } else if (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
458 Ty = ArrayTy->getElementType();
459 } else {
460 Subscripts.clear();
461 Sizes.clear();
462 break;
463 }
464 if (auto Const = dyn_cast<SCEVConstant>(Expr))
465 if (Const->getValue()->isZero()) {
466 DroppedFirstDim = true;
467 continue;
468 }
469 Subscripts.push_back(Expr);
470 continue;
471 }
472
473 auto ArrayTy = dyn_cast<ArrayType>(Ty);
474 if (!ArrayTy) {
475 Subscripts.clear();
476 Sizes.clear();
477 break;
478 }
479
480 Subscripts.push_back(Expr);
481 if (!(DroppedFirstDim && i == 2))
482 Sizes.push_back(ArrayTy->getNumElements());
483
484 Ty = ArrayTy->getElementType();
485 }
486
487 return std::make_tuple(Subscripts, Sizes);
488}
489
Tobias Grosser75805372011-04-29 06:27:02 +0000490MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000491 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000492 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000493 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000494}
495
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000496const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
497 isl_id *ArrayId = getArrayId();
498 void *User = isl_id_get_user(ArrayId);
499 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
500 isl_id_free(ArrayId);
501 return SAI;
502}
503
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000504__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000505 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
506}
507
Tobias Grosserd840fc72016-02-04 13:18:42 +0000508__isl_give isl_map *MemoryAccess::getAddressFunction() const {
509 return isl_map_lexmin(getAccessRelation());
510}
511
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000512__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
513 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000514 isl_map *Schedule, *ScheduledAccRel;
515 isl_union_set *UDomain;
516
517 UDomain = isl_union_set_from_set(getStatement()->getDomain());
518 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
519 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000520 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000521 return isl_pw_multi_aff_from_map(ScheduledAccRel);
522}
523
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000524__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000525 return isl_map_copy(AccessRelation);
526}
527
Johannes Doerferta99130f2014-10-13 12:58:03 +0000528std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000529 return stringFromIslObj(AccessRelation);
530}
531
Johannes Doerferta99130f2014-10-13 12:58:03 +0000532__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000533 return isl_map_get_space(AccessRelation);
534}
535
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000536__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000537 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000538}
539
Tobias Grosser6f730082015-09-05 07:46:47 +0000540std::string MemoryAccess::getNewAccessRelationStr() const {
541 return stringFromIslObj(NewAccessRelation);
542}
543
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000544__isl_give isl_basic_map *
545MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000546 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000547 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000548
Tobias Grosser084d8f72012-05-29 09:29:44 +0000549 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000550 isl_basic_set_universe(Statement->getDomainSpace()),
551 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000552}
553
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000554// Formalize no out-of-bound access assumption
555//
556// When delinearizing array accesses we optimistically assume that the
557// delinearized accesses do not access out of bound locations (the subscript
558// expression of each array evaluates for each statement instance that is
559// executed to a value that is larger than zero and strictly smaller than the
560// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000561// dimension for which we do not need to assume any upper bound. At this point
562// we formalize this assumption to ensure that at code generation time the
563// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000564//
565// To find the set of constraints necessary to avoid out of bound accesses, we
566// first build the set of data locations that are not within array bounds. We
567// then apply the reverse access relation to obtain the set of iterations that
568// may contain invalid accesses and reduce this set of iterations to the ones
569// that are actually executed by intersecting them with the domain of the
570// statement. If we now project out all loop dimensions, we obtain a set of
571// parameters that may cause statement instances to be executed that may
572// possibly yield out of bound memory accesses. The complement of these
573// constraints is the set of constraints that needs to be assumed to ensure such
574// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000575void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000576 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000577 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000578 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000579 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000580 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
581 isl_pw_aff *Var =
582 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
583 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
584
585 isl_set *DimOutside;
586
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000587 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000588 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000589 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
590 isl_space_dim(Space, isl_dim_set));
591 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
592 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000593
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000594 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000595
596 Outside = isl_set_union(Outside, DimOutside);
597 }
598
599 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
600 Outside = isl_set_intersect(Outside, Statement->getDomain());
601 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000602
603 // Remove divs to avoid the construction of overly complicated assumptions.
604 // Doing so increases the set of parameter combinations that are assumed to
605 // not appear. This is always save, but may make the resulting run-time check
606 // bail out more often than strictly necessary.
607 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000608 Outside = isl_set_complement(Outside);
Michael Krusead28e5a2016-01-26 13:33:15 +0000609 Statement->getParent()->addAssumption(
610 INBOUNDS, Outside,
611 getAccessInstruction() ? getAccessInstruction()->getDebugLoc() : nullptr);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000612 isl_space_free(Space);
613}
614
Johannes Doerferte7044942015-02-24 11:58:30 +0000615void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
616 ScalarEvolution *SE = Statement->getParent()->getSE();
617
Michael Kruse70131d32016-01-27 17:09:17 +0000618 Value *Ptr = MemAccInst(getAccessInstruction()).getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000619 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
620 return;
621
622 auto *PtrSCEV = SE->getSCEV(Ptr);
623 if (isa<SCEVCouldNotCompute>(PtrSCEV))
624 return;
625
626 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
627 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
628 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
629
630 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
631 if (Range.isFullSet())
632 return;
633
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000634 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000635 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000636 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000637 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000638 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000639
640 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000641 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000642
643 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
644 AccessRange =
645 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
646 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
647}
648
Michael Krusee2bccbb2015-09-18 19:59:43 +0000649__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000650 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000651 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000652
653 for (int i = Size - 2; i >= 0; --i) {
654 isl_space *Space;
655 isl_map *MapOne, *MapTwo;
Michael Krusee2bccbb2015-09-18 19:59:43 +0000656 isl_pw_aff *DimSize = Statement->getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000657
658 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
659 isl_pw_aff_free(DimSize);
660 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
661
662 Space = isl_map_get_space(AccessRelation);
663 Space = isl_space_map_from_set(isl_space_range(Space));
664 Space = isl_space_align_params(Space, SpaceSize);
665
666 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
667 isl_id_free(ParamId);
668
669 MapOne = isl_map_universe(isl_space_copy(Space));
670 for (int j = 0; j < Size; ++j)
671 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
672 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
673
674 MapTwo = isl_map_universe(isl_space_copy(Space));
675 for (int j = 0; j < Size; ++j)
676 if (j < i || j > i + 1)
677 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
678
679 isl_local_space *LS = isl_local_space_from_space(Space);
680 isl_constraint *C;
681 C = isl_equality_alloc(isl_local_space_copy(LS));
682 C = isl_constraint_set_constant_si(C, -1);
683 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
684 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
685 MapTwo = isl_map_add_constraint(MapTwo, C);
686 C = isl_equality_alloc(LS);
687 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
688 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
689 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
690 MapTwo = isl_map_add_constraint(MapTwo, C);
691 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
692
693 MapOne = isl_map_union(MapOne, MapTwo);
694 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
695 }
696 return AccessRelation;
697}
698
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000699/// @brief Check if @p Expr is divisible by @p Size.
700static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000701 if (Size == 1)
702 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000703
704 // Only one factor needs to be divisible.
705 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
706 for (auto *FactorExpr : MulExpr->operands())
707 if (isDivisible(FactorExpr, Size, SE))
708 return true;
709 return false;
710 }
711
712 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
713 // to be divisble.
714 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
715 for (auto *OpExpr : NAryExpr->operands())
716 if (!isDivisible(OpExpr, Size, SE))
717 return false;
718 return true;
719 }
720
721 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
722 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
723 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
724 return MulSCEV == Expr;
725}
726
Michael Krusee2bccbb2015-09-18 19:59:43 +0000727void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
728 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000729
Michael Krusee2bccbb2015-09-18 19:59:43 +0000730 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000731 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000732
Michael Krusee2bccbb2015-09-18 19:59:43 +0000733 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000734 // We overapproximate non-affine accesses with a possible access to the
735 // whole array. For read accesses it does not make a difference, if an
736 // access must or may happen. However, for write accesses it is important to
737 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000738 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000739 AccessRelation =
740 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000741 return;
742 }
743
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000744 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000745 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000746
Michael Krusee2bccbb2015-09-18 19:59:43 +0000747 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
748 isl_pw_aff *Affine = Statement->getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000749 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000750 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000751 }
752
Tobias Grosser5d51afe2016-02-02 16:46:45 +0000753 if (Sizes.size() >= 1 && !isa<SCEVConstant>(Sizes[0]))
Michael Krusee2bccbb2015-09-18 19:59:43 +0000754 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000755
Tobias Grosser79baa212014-04-10 08:38:02 +0000756 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000757 AccessRelation = isl_map_set_tuple_id(
758 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000759 AccessRelation =
760 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
761
Tobias Grosseraa660a92015-03-30 00:07:50 +0000762 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000763 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000764}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000765
Michael Krusecac948e2015-10-02 13:53:07 +0000766MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000767 AccessType Type, Value *BaseAddress,
768 unsigned ElemBytes, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000769 ArrayRef<const SCEV *> Subscripts,
770 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000771 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
772 : Kind(Kind), AccType(Type), RedType(RT_NONE), Statement(Stmt),
Michael Krusecac948e2015-10-02 13:53:07 +0000773 BaseAddr(BaseAddress), BaseName(BaseName), ElemBytes(ElemBytes),
774 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
775 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000776 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000777 NewAccessRelation(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000778 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
779 const std::string Access = TypeStrings[Type] + utostr(Stmt->size()) + "_";
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000780
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000781 std::string IdName =
782 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000783 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
784}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000785
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000786void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000787 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000788 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000789}
790
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000791const std::string MemoryAccess::getReductionOperatorStr() const {
792 return MemoryAccess::getReductionOperatorStr(getReductionType());
793}
794
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000795__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
796
Johannes Doerfertf6183392014-07-01 20:52:51 +0000797raw_ostream &polly::operator<<(raw_ostream &OS,
798 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000799 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000800 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000801 else
802 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000803 return OS;
804}
805
Tobias Grosser75805372011-04-29 06:27:02 +0000806void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000807 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000808 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000809 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000810 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000811 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000812 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000813 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000814 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000815 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000816 break;
817 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000818 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000819 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000820 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000821 if (hasNewAccessRelation())
822 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000823}
824
Tobias Grosser74394f02013-01-14 22:40:23 +0000825void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000826
827// Create a map in the size of the provided set domain, that maps from the
828// one element of the provided set domain to another element of the provided
829// set domain.
830// The mapping is limited to all points that are equal in all but the last
831// dimension and for which the last dimension of the input is strict smaller
832// than the last dimension of the output.
833//
834// getEqualAndLarger(set[i0, i1, ..., iX]):
835//
836// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
837// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
838//
Tobias Grosserf5338802011-10-06 00:03:35 +0000839static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000840 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000841 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000842 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000843
844 // Set all but the last dimension to be equal for the input and output
845 //
846 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
847 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000848 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000849 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000850
851 // Set the last dimension of the input to be strict smaller than the
852 // last dimension of the output.
853 //
854 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000855 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
856 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000857 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000858}
859
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000860__isl_give isl_set *
861MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000862 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000863 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000864 isl_space *Space = isl_space_range(isl_map_get_space(S));
865 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000866
Sebastian Popa00a0292012-12-18 07:46:06 +0000867 S = isl_map_reverse(S);
868 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000869
Sebastian Popa00a0292012-12-18 07:46:06 +0000870 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
871 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
872 NextScatt = isl_map_apply_domain(NextScatt, S);
873 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000874
Sebastian Popa00a0292012-12-18 07:46:06 +0000875 isl_set *Deltas = isl_map_deltas(NextScatt);
876 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000877}
878
Sebastian Popa00a0292012-12-18 07:46:06 +0000879bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000880 int StrideWidth) const {
881 isl_set *Stride, *StrideX;
882 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000883
Sebastian Popa00a0292012-12-18 07:46:06 +0000884 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000885 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000886 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
887 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
888 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
889 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000890 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000891
Tobias Grosser28dd4862012-01-24 16:42:16 +0000892 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000893 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000894
Tobias Grosser28dd4862012-01-24 16:42:16 +0000895 return IsStrideX;
896}
897
Sebastian Popa00a0292012-12-18 07:46:06 +0000898bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
899 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000900}
901
Sebastian Popa00a0292012-12-18 07:46:06 +0000902bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
903 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000904}
905
Tobias Grosser166c4222015-09-05 07:46:40 +0000906void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
907 isl_map_free(NewAccessRelation);
908 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000909}
Tobias Grosser75805372011-04-29 06:27:02 +0000910
911//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000912
Tobias Grosser808cd692015-07-14 09:33:13 +0000913isl_map *ScopStmt::getSchedule() const {
914 isl_set *Domain = getDomain();
915 if (isl_set_is_empty(Domain)) {
916 isl_set_free(Domain);
917 return isl_map_from_aff(
918 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
919 }
920 auto *Schedule = getParent()->getSchedule();
921 Schedule = isl_union_map_intersect_domain(
922 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
923 if (isl_union_map_is_empty(Schedule)) {
924 isl_set_free(Domain);
925 isl_union_map_free(Schedule);
926 return isl_map_from_aff(
927 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
928 }
929 auto *M = isl_map_from_union_map(Schedule);
930 M = isl_map_coalesce(M);
931 M = isl_map_gist_domain(M, Domain);
932 M = isl_map_coalesce(M);
933 return M;
934}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000935
Johannes Doerfert574182d2015-08-12 10:19:50 +0000936__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000937 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
938 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000939}
940
Tobias Grosser37eb4222014-02-20 21:43:54 +0000941void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
942 assert(isl_set_is_subset(NewDomain, Domain) &&
943 "New domain is not a subset of old domain!");
944 isl_set_free(Domain);
945 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000946}
947
Michael Krusecac948e2015-10-02 13:53:07 +0000948void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000949 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +0000950 for (MemoryAccess *Access : MemAccs) {
951 Type *ElementType = Access->getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000952
Tobias Grossera535dff2015-12-13 19:59:01 +0000953 ScopArrayInfo::MemoryKind Ty;
954 if (Access->isPHIKind())
955 Ty = ScopArrayInfo::MK_PHI;
956 else if (Access->isExitPHIKind())
957 Ty = ScopArrayInfo::MK_ExitPHI;
958 else if (Access->isValueKind())
959 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000960 else
Tobias Grossera535dff2015-12-13 19:59:01 +0000961 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000962
Johannes Doerfertadeab372016-02-07 13:57:32 +0000963 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
964 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +0000965 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +0000966 }
967}
968
Michael Krusecac948e2015-10-02 13:53:07 +0000969void ScopStmt::addAccess(MemoryAccess *Access) {
970 Instruction *AccessInst = Access->getAccessInstruction();
971
Michael Kruse58fa3bb2015-12-22 23:25:11 +0000972 if (Access->isArrayKind()) {
973 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
974 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +0000975 } else if (Access->isValueKind() && Access->isWrite()) {
976 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
977 assert(Parent.getStmtForBasicBlock(AccessVal->getParent()) == this);
978 assert(!ValueWrites.lookup(AccessVal));
979
980 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +0000981 } else if (Access->isValueKind() && Access->isRead()) {
982 Value *AccessVal = Access->getAccessValue();
983 assert(!ValueReads.lookup(AccessVal));
984
985 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +0000986 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
987 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
988 assert(!PHIWrites.lookup(PHI));
989
990 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +0000991 }
992
993 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +0000994}
995
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000996void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000997 for (MemoryAccess *MA : *this)
998 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000999
1000 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001001}
1002
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001003/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
1004static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1005 void *User) {
1006 isl_set **BoundedParts = static_cast<isl_set **>(User);
1007 if (isl_basic_set_is_bounded(BSet))
1008 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1009 else
1010 isl_basic_set_free(BSet);
1011 return isl_stat_ok;
1012}
1013
1014/// @brief Return the bounded parts of @p S.
1015static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1016 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1017 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1018 isl_set_free(S);
1019 return BoundedParts;
1020}
1021
1022/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
1023///
1024/// @returns A separation of @p S into first an unbounded then a bounded subset,
1025/// both with regards to the dimension @p Dim.
1026static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1027partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1028
1029 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001030 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001031
1032 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001033 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001034
1035 // Remove dimensions that are greater than Dim as they are not interesting.
1036 assert(NumDimsS >= Dim + 1);
1037 OnlyDimS =
1038 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1039
1040 // Create artificial parametric upper bounds for dimensions smaller than Dim
1041 // as we are not interested in them.
1042 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1043 for (unsigned u = 0; u < Dim; u++) {
1044 isl_constraint *C = isl_inequality_alloc(
1045 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1046 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1047 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1048 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1049 }
1050
1051 // Collect all bounded parts of OnlyDimS.
1052 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1053
1054 // Create the dimensions greater than Dim again.
1055 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1056 NumDimsS - Dim - 1);
1057
1058 // Remove the artificial upper bound parameters again.
1059 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1060
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001061 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001062 return std::make_pair(UnboundedParts, BoundedParts);
1063}
1064
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001065/// @brief Set the dimension Ids from @p From in @p To.
1066static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1067 __isl_take isl_set *To) {
1068 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1069 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1070 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1071 }
1072 return To;
1073}
1074
1075/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001076static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001077 __isl_take isl_pw_aff *L,
1078 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001079 switch (Pred) {
1080 case ICmpInst::ICMP_EQ:
1081 return isl_pw_aff_eq_set(L, R);
1082 case ICmpInst::ICMP_NE:
1083 return isl_pw_aff_ne_set(L, R);
1084 case ICmpInst::ICMP_SLT:
1085 return isl_pw_aff_lt_set(L, R);
1086 case ICmpInst::ICMP_SLE:
1087 return isl_pw_aff_le_set(L, R);
1088 case ICmpInst::ICMP_SGT:
1089 return isl_pw_aff_gt_set(L, R);
1090 case ICmpInst::ICMP_SGE:
1091 return isl_pw_aff_ge_set(L, R);
1092 case ICmpInst::ICMP_ULT:
1093 return isl_pw_aff_lt_set(L, R);
1094 case ICmpInst::ICMP_UGT:
1095 return isl_pw_aff_gt_set(L, R);
1096 case ICmpInst::ICMP_ULE:
1097 return isl_pw_aff_le_set(L, R);
1098 case ICmpInst::ICMP_UGE:
1099 return isl_pw_aff_ge_set(L, R);
1100 default:
1101 llvm_unreachable("Non integer predicate not supported");
1102 }
1103}
1104
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001105/// @brief Create the conditions under which @p L @p Pred @p R is true.
1106///
1107/// Helper function that will make sure the dimensions of the result have the
1108/// same isl_id's as the @p Domain.
1109static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1110 __isl_take isl_pw_aff *L,
1111 __isl_take isl_pw_aff *R,
1112 __isl_keep isl_set *Domain) {
1113 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1114 return setDimensionIds(Domain, ConsequenceCondSet);
1115}
1116
1117/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001118///
1119/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001120/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1121/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001122static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001123buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001124 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1125
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001126 Value *Condition = getConditionFromTerminator(SI);
1127 assert(Condition && "No condition for switch");
1128
1129 ScalarEvolution &SE = *S.getSE();
1130 BasicBlock *BB = SI->getParent();
1131 isl_pw_aff *LHS, *RHS;
1132 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
1133
1134 unsigned NumSuccessors = SI->getNumSuccessors();
1135 ConditionSets.resize(NumSuccessors);
1136 for (auto &Case : SI->cases()) {
1137 unsigned Idx = Case.getSuccessorIndex();
1138 ConstantInt *CaseValue = Case.getCaseValue();
1139
1140 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
1141 isl_set *CaseConditionSet =
1142 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1143 ConditionSets[Idx] = isl_set_coalesce(
1144 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1145 }
1146
1147 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1148 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1149 for (unsigned u = 2; u < NumSuccessors; u++)
1150 ConditionSetUnion =
1151 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1152 ConditionSets[0] = setDimensionIds(
1153 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1154
1155 S.markAsOptimized();
1156 isl_pw_aff_free(LHS);
1157}
1158
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001159/// @brief Build the conditions sets for the branch condition @p Condition in
1160/// the @p Domain.
1161///
1162/// This will fill @p ConditionSets with the conditions under which control
1163/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001164/// have as many elements as @p TI has successors. If @p TI is nullptr the
1165/// context under which @p Condition is true/false will be returned as the
1166/// new elements of @p ConditionSets.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001167static void
1168buildConditionSets(Scop &S, Value *Condition, TerminatorInst *TI, Loop *L,
1169 __isl_keep isl_set *Domain,
1170 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1171
1172 isl_set *ConsequenceCondSet = nullptr;
1173 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1174 if (CCond->isZero())
1175 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1176 else
1177 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1178 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1179 auto Opcode = BinOp->getOpcode();
1180 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1181
1182 buildConditionSets(S, BinOp->getOperand(0), TI, L, Domain, ConditionSets);
1183 buildConditionSets(S, BinOp->getOperand(1), TI, L, Domain, ConditionSets);
1184
1185 isl_set_free(ConditionSets.pop_back_val());
1186 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1187 isl_set_free(ConditionSets.pop_back_val());
1188 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1189
1190 if (Opcode == Instruction::And)
1191 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1192 else
1193 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1194 } else {
1195 auto *ICond = dyn_cast<ICmpInst>(Condition);
1196 assert(ICond &&
1197 "Condition of exiting branch was neither constant nor ICmp!");
1198
1199 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001200 BasicBlock *BB = TI ? TI->getParent() : nullptr;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001201 isl_pw_aff *LHS, *RHS;
1202 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1203 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
1204 ConsequenceCondSet =
1205 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1206 }
1207
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001208 // If no terminator was given we are only looking for parameter constraints
1209 // under which @p Condition is true/false.
1210 if (!TI)
1211 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
1212
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001213 assert(ConsequenceCondSet);
1214 isl_set *AlternativeCondSet =
1215 isl_set_complement(isl_set_copy(ConsequenceCondSet));
1216
1217 ConditionSets.push_back(isl_set_coalesce(
1218 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
1219 ConditionSets.push_back(isl_set_coalesce(
1220 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
1221}
1222
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001223/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1224///
1225/// This will fill @p ConditionSets with the conditions under which control
1226/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1227/// have as many elements as @p TI has successors.
1228static void
1229buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1230 __isl_keep isl_set *Domain,
1231 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1232
1233 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1234 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1235
1236 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1237
1238 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001239 ConditionSets.push_back(isl_set_copy(Domain));
1240 return;
1241 }
1242
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001243 Value *Condition = getConditionFromTerminator(TI);
1244 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001245
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001246 return buildConditionSets(S, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001247}
1248
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001249void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +00001250 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +00001251
Tobias Grosser084d8f72012-05-29 09:29:44 +00001252 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1253
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001254 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001255 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001256}
1257
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001258void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP,
1259 ScopDetection &SD) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001260 isl_ctx *Ctx = Parent.getIslCtx();
1261 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1262 Type *Ty = GEP->getPointerOperandType();
1263 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001264
1265 // The set of loads that are required to be invariant.
1266 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001267
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001268 std::vector<const SCEV *> Subscripts;
1269 std::vector<int> Sizes;
1270
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001271 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001272
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001273 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001274 Ty = PtrTy->getElementType();
1275 }
1276
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001277 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001278
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001279 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001280
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001281 for (size_t i = 0; i < Sizes.size(); i++) {
1282 auto Expr = Subscripts[i + IndexOffset];
1283 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001284
Johannes Doerfert09e36972015-10-07 20:17:36 +00001285 InvariantLoadsSetTy AccessILS;
1286 if (!isAffineExpr(&Parent.getRegion(), Expr, SE, nullptr, &AccessILS))
1287 continue;
1288
1289 bool NonAffine = false;
1290 for (LoadInst *LInst : AccessILS)
1291 if (!ScopRIL.count(LInst))
1292 NonAffine = true;
1293
1294 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001295 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001296
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001297 isl_pw_aff *AccessOffset = getPwAff(Expr);
1298 AccessOffset =
1299 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001300
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001301 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1302 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001303
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001304 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1305 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1306 OutOfBound = isl_set_params(OutOfBound);
1307 isl_set *InBound = isl_set_complement(OutOfBound);
1308 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001309
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001310 // A => B == !A or B
1311 isl_set *InBoundIfExecuted =
1312 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001313
Roman Gareev10595a12016-01-08 14:01:59 +00001314 InBoundIfExecuted = isl_set_coalesce(InBoundIfExecuted);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001315 Parent.addAssumption(INBOUNDS, InBoundIfExecuted, GEP->getDebugLoc());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001316 }
1317
1318 isl_local_space_free(LSpace);
1319}
1320
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001321void ScopStmt::deriveAssumptions(BasicBlock *Block, ScopDetection &SD) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001322 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001323 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001324 deriveAssumptionsFromGEP(GEP, SD);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001325}
1326
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001327void ScopStmt::collectSurroundingLoops() {
1328 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1329 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1330 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1331 isl_id_free(DimId);
1332 }
1333}
1334
Michael Kruse9d080092015-09-11 21:41:48 +00001335ScopStmt::ScopStmt(Scop &parent, Region &R)
Michael Krusecac948e2015-10-02 13:53:07 +00001336 : Parent(parent), Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001337
Tobias Grosser16c44032015-07-09 07:31:45 +00001338 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001339}
1340
Michael Kruse9d080092015-09-11 21:41:48 +00001341ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Michael Krusecac948e2015-10-02 13:53:07 +00001342 : Parent(parent), Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001343
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001344 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001345}
1346
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001347void ScopStmt::init(ScopDetection &SD) {
Michael Krusecac948e2015-10-02 13:53:07 +00001348 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001349
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001350 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001351 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001352 buildAccessRelations();
1353
1354 if (BB) {
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001355 deriveAssumptions(BB, SD);
Michael Krusecac948e2015-10-02 13:53:07 +00001356 } else {
1357 for (BasicBlock *Block : R->blocks()) {
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001358 deriveAssumptions(Block, SD);
Michael Krusecac948e2015-10-02 13:53:07 +00001359 }
1360 }
1361
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001362 if (DetectReductions)
1363 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001364}
1365
Johannes Doerferte58a0122014-06-27 20:31:28 +00001366/// @brief Collect loads which might form a reduction chain with @p StoreMA
1367///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001368/// Check if the stored value for @p StoreMA is a binary operator with one or
1369/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001370/// used only once (by @p StoreMA) and its load operands are also used only
1371/// once, we have found a possible reduction chain. It starts at an operand
1372/// load and includes the binary operator and @p StoreMA.
1373///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001374/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001375/// escape this block or into any other store except @p StoreMA.
1376void ScopStmt::collectCandiateReductionLoads(
1377 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1378 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1379 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001380 return;
1381
1382 // Skip if there is not one binary operator between the load and the store
1383 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001384 if (!BinOp)
1385 return;
1386
1387 // Skip if the binary operators has multiple uses
1388 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001389 return;
1390
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001391 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001392 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1393 return;
1394
Johannes Doerfert9890a052014-07-01 00:32:29 +00001395 // Skip if the binary operator is outside the current SCoP
1396 if (BinOp->getParent() != Store->getParent())
1397 return;
1398
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001399 // Skip if it is a multiplicative reduction and we disabled them
1400 if (DisableMultiplicativeReductions &&
1401 (BinOp->getOpcode() == Instruction::Mul ||
1402 BinOp->getOpcode() == Instruction::FMul))
1403 return;
1404
Johannes Doerferte58a0122014-06-27 20:31:28 +00001405 // Check the binary operator operands for a candidate load
1406 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1407 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1408 if (!PossibleLoad0 && !PossibleLoad1)
1409 return;
1410
1411 // A load is only a candidate if it cannot escape (thus has only this use)
1412 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001413 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001414 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001415 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001416 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001417 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001418}
1419
1420/// @brief Check for reductions in this ScopStmt
1421///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001422/// Iterate over all store memory accesses and check for valid binary reduction
1423/// like chains. For all candidates we check if they have the same base address
1424/// and there are no other accesses which overlap with them. The base address
1425/// check rules out impossible reductions candidates early. The overlap check,
1426/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001427/// guarantees that none of the intermediate results will escape during
1428/// execution of the loop nest. We basically check here that no other memory
1429/// access can access the same memory as the potential reduction.
1430void ScopStmt::checkForReductions() {
1431 SmallVector<MemoryAccess *, 2> Loads;
1432 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1433
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001434 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001435 // stores and collecting possible reduction loads.
1436 for (MemoryAccess *StoreMA : MemAccs) {
1437 if (StoreMA->isRead())
1438 continue;
1439
1440 Loads.clear();
1441 collectCandiateReductionLoads(StoreMA, Loads);
1442 for (MemoryAccess *LoadMA : Loads)
1443 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1444 }
1445
1446 // Then check each possible candidate pair.
1447 for (const auto &CandidatePair : Candidates) {
1448 bool Valid = true;
1449 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1450 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1451
1452 // Skip those with obviously unequal base addresses.
1453 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1454 isl_map_free(LoadAccs);
1455 isl_map_free(StoreAccs);
1456 continue;
1457 }
1458
1459 // And check if the remaining for overlap with other memory accesses.
1460 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1461 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1462 isl_set *AllAccs = isl_map_range(AllAccsRel);
1463
1464 for (MemoryAccess *MA : MemAccs) {
1465 if (MA == CandidatePair.first || MA == CandidatePair.second)
1466 continue;
1467
1468 isl_map *AccRel =
1469 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1470 isl_set *Accs = isl_map_range(AccRel);
1471
1472 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1473 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1474 Valid = Valid && isl_set_is_empty(OverlapAccs);
1475 isl_set_free(OverlapAccs);
1476 }
1477 }
1478
1479 isl_set_free(AllAccs);
1480 if (!Valid)
1481 continue;
1482
Johannes Doerfertf6183392014-07-01 20:52:51 +00001483 const LoadInst *Load =
1484 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1485 MemoryAccess::ReductionType RT =
1486 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1487
Johannes Doerferte58a0122014-06-27 20:31:28 +00001488 // If no overlapping access was found we mark the load and store as
1489 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001490 CandidatePair.first->markAsReductionLike(RT);
1491 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001492 }
Tobias Grosser75805372011-04-29 06:27:02 +00001493}
1494
Tobias Grosser74394f02013-01-14 22:40:23 +00001495std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001496
Tobias Grosser54839312015-04-21 11:37:25 +00001497std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001498 auto *S = getSchedule();
1499 auto Str = stringFromIslObj(S);
1500 isl_map_free(S);
1501 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001502}
1503
Tobias Grosser74394f02013-01-14 22:40:23 +00001504unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001505
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001506unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001507
Tobias Grosser75805372011-04-29 06:27:02 +00001508const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1509
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001510const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001511 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001512}
1513
Tobias Grosser74394f02013-01-14 22:40:23 +00001514isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001515
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001516__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001517
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001518__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001519 return isl_set_get_space(Domain);
1520}
1521
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001522__isl_give isl_id *ScopStmt::getDomainId() const {
1523 return isl_set_get_tuple_id(Domain);
1524}
Tobias Grossercd95b772012-08-30 11:49:38 +00001525
Tobias Grosser10120182015-12-16 16:14:03 +00001526ScopStmt::~ScopStmt() { isl_set_free(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001527
1528void ScopStmt::print(raw_ostream &OS) const {
1529 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001530 OS.indent(12) << "Domain :=\n";
1531
1532 if (Domain) {
1533 OS.indent(16) << getDomainStr() << ";\n";
1534 } else
1535 OS.indent(16) << "n/a\n";
1536
Tobias Grosser54839312015-04-21 11:37:25 +00001537 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001538
1539 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001540 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001541 } else
1542 OS.indent(16) << "n/a\n";
1543
Tobias Grosser083d3d32014-06-28 08:59:45 +00001544 for (MemoryAccess *Access : MemAccs)
1545 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001546}
1547
1548void ScopStmt::dump() const { print(dbgs()); }
1549
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001550void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001551 // Remove all memory accesses in @p InvMAs from this statement
1552 // together with all scalar accesses that were caused by them.
Michael Krusead28e5a2016-01-26 13:33:15 +00001553 // MK_Value READs have no access instruction, hence would not be removed by
1554 // this function. However, it is only used for invariant LoadInst accesses,
1555 // its arguments are always affine, hence synthesizable, and therefore there
1556 // are no MK_Value READ accesses to be removed.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001557 for (MemoryAccess *MA : InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001558 auto Predicate = [&](MemoryAccess *Acc) {
Tobias Grosser3a6ac9f2015-11-30 21:13:43 +00001559 return Acc->getAccessInstruction() == MA->getAccessInstruction();
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001560 };
1561 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1562 MemAccs.end());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001563 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001564 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001565}
1566
Tobias Grosser75805372011-04-29 06:27:02 +00001567//===----------------------------------------------------------------------===//
1568/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001569
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001570void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001571 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1572 isl_set_free(Context);
1573 Context = NewContext;
1574}
1575
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001576/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1577struct SCEVSensitiveParameterRewriter
1578 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1579 ValueToValueMap &VMap;
1580 ScalarEvolution &SE;
1581
1582public:
1583 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1584 : VMap(VMap), SE(SE) {}
1585
1586 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1587 ValueToValueMap &VMap) {
1588 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1589 return SSPR.visit(E);
1590 }
1591
1592 const SCEV *visit(const SCEV *E) {
1593 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1594 }
1595
1596 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1597
1598 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1599 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1600 }
1601
1602 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1603 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1604 }
1605
1606 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1607 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1608 }
1609
1610 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1611 SmallVector<const SCEV *, 4> Operands;
1612 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1613 Operands.push_back(visit(E->getOperand(i)));
1614 return SE.getAddExpr(Operands);
1615 }
1616
1617 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1618 SmallVector<const SCEV *, 4> Operands;
1619 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1620 Operands.push_back(visit(E->getOperand(i)));
1621 return SE.getMulExpr(Operands);
1622 }
1623
1624 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1625 SmallVector<const SCEV *, 4> Operands;
1626 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1627 Operands.push_back(visit(E->getOperand(i)));
1628 return SE.getSMaxExpr(Operands);
1629 }
1630
1631 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1632 SmallVector<const SCEV *, 4> Operands;
1633 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1634 Operands.push_back(visit(E->getOperand(i)));
1635 return SE.getUMaxExpr(Operands);
1636 }
1637
1638 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1639 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1640 }
1641
1642 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1643 auto *Start = visit(E->getStart());
1644 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1645 visit(E->getStepRecurrence(SE)),
1646 E->getLoop(), SCEV::FlagAnyWrap);
1647 return SE.getAddExpr(Start, AddRec);
1648 }
1649
1650 const SCEV *visitUnknown(const SCEVUnknown *E) {
1651 if (auto *NewValue = VMap.lookup(E->getValue()))
1652 return SE.getUnknown(NewValue);
1653 return E;
1654 }
1655};
1656
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001657const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001658 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001659}
1660
Tobias Grosserabfbe632013-02-05 12:09:06 +00001661void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001662 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001663 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001664
1665 // Normalize the SCEV to get the representing element for an invariant load.
1666 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1667
Tobias Grosser60b54f12011-11-08 15:41:28 +00001668 if (ParameterIds.find(Parameter) != ParameterIds.end())
1669 continue;
1670
1671 int dimension = Parameters.size();
1672
1673 Parameters.push_back(Parameter);
1674 ParameterIds[Parameter] = dimension;
1675 }
1676}
1677
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001678__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001679 // Normalize the SCEV to get the representing element for an invariant load.
1680 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1681
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001682 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001683
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001684 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001685 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001686
Tobias Grosser8f99c162011-11-15 11:38:55 +00001687 std::string ParameterName;
1688
Craig Topper7fb6e472016-01-31 20:36:20 +00001689 ParameterName = "p_" + utostr(IdIter->second);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001690
Tobias Grosser8f99c162011-11-15 11:38:55 +00001691 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1692 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001693
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001694 // If this parameter references a specific Value and this value has a name
1695 // we use this name as it is likely to be unique and more useful than just
1696 // a number.
1697 if (Val->hasName())
1698 ParameterName = Val->getName();
1699 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
1700 auto LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
1701 if (LoadOrigin->hasName()) {
1702 ParameterName += "_loaded_from_";
1703 ParameterName +=
1704 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1705 }
1706 }
1707 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001708
Tobias Grosser20532b82014-04-11 17:56:49 +00001709 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1710 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001711}
Tobias Grosser75805372011-04-29 06:27:02 +00001712
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001713isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1714 isl_set *DomainContext = isl_union_set_params(getDomains());
1715 return isl_set_intersect_params(C, DomainContext);
1716}
1717
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001718void Scop::buildBoundaryContext() {
Tobias Grosser4927c8e2015-11-24 12:50:02 +00001719 if (IgnoreIntegerWrapping) {
1720 BoundaryContext = isl_set_universe(getParamSpace());
1721 return;
1722 }
1723
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001724 BoundaryContext = Affinator.getWrappingContext();
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001725
1726 // The isl_set_complement operation used to create the boundary context
1727 // can possibly become very expensive. We bound the compile time of
1728 // this operation by setting a compute out.
1729 //
1730 // TODO: We can probably get around using isl_set_complement and directly
1731 // AST generate BoundaryContext.
1732 long MaxOpsOld = isl_ctx_get_max_operations(getIslCtx());
Tobias Grosserf920fb12015-11-13 16:56:13 +00001733 isl_ctx_reset_operations(getIslCtx());
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001734 isl_ctx_set_max_operations(getIslCtx(), 300000);
1735 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_CONTINUE);
1736
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001737 BoundaryContext = isl_set_complement(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001738
Tobias Grossera52b4da2015-11-11 17:59:53 +00001739 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
1740 isl_set_free(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001741 BoundaryContext = isl_set_empty(getParamSpace());
Tobias Grossera52b4da2015-11-11 17:59:53 +00001742 }
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001743
1744 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
1745 isl_ctx_reset_operations(getIslCtx());
1746 isl_ctx_set_max_operations(getIslCtx(), MaxOpsOld);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001747 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001748 trackAssumption(WRAPPING, BoundaryContext, DebugLoc());
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001749}
1750
Hongbin Zheng192f69a2016-02-13 15:12:54 +00001751void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
1752 LoopInfo &LI) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001753 auto *R = &getRegion();
1754 auto &F = *R->getEntry()->getParent();
1755 for (auto &Assumption : AC.assumptions()) {
1756 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1757 if (!CI || CI->getNumArgOperands() != 1)
1758 continue;
1759 if (!DT.dominates(CI->getParent(), R->getEntry()))
1760 continue;
1761
1762 auto *Val = CI->getArgOperand(0);
1763 std::vector<const SCEV *> Params;
1764 if (!isAffineParamConstraint(Val, R, *SE, Params)) {
1765 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1766 CI->getDebugLoc(),
1767 "Non-affine user assumption ignored.");
1768 continue;
1769 }
1770
1771 addParams(Params);
1772
1773 auto *L = LI.getLoopFor(CI->getParent());
1774 SmallVector<isl_set *, 2> ConditionSets;
1775 buildConditionSets(*this, Val, nullptr, L, Context, ConditionSets);
1776 assert(ConditionSets.size() == 2);
1777 isl_set_free(ConditionSets[1]);
1778
1779 auto *AssumptionCtx = ConditionSets[0];
1780 emitOptimizationRemarkAnalysis(
1781 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1782 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1783 Context = isl_set_intersect(Context, AssumptionCtx);
1784 }
1785}
1786
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001787void Scop::addUserContext() {
1788 if (UserContextStr.empty())
1789 return;
1790
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001791 isl_set *UserContext =
1792 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001793 isl_space *Space = getParamSpace();
1794 if (isl_space_dim(Space, isl_dim_param) !=
1795 isl_set_dim(UserContext, isl_dim_param)) {
1796 auto SpaceStr = isl_space_to_str(Space);
1797 errs() << "Error: the context provided in -polly-context has not the same "
1798 << "number of dimensions than the computed context. Due to this "
1799 << "mismatch, the -polly-context option is ignored. Please provide "
1800 << "the context in the parameter space: " << SpaceStr << ".\n";
1801 free(SpaceStr);
1802 isl_set_free(UserContext);
1803 isl_space_free(Space);
1804 return;
1805 }
1806
1807 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1808 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1809 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1810
1811 if (strcmp(NameContext, NameUserContext) != 0) {
1812 auto SpaceStr = isl_space_to_str(Space);
1813 errs() << "Error: the name of dimension " << i
1814 << " provided in -polly-context "
1815 << "is '" << NameUserContext << "', but the name in the computed "
1816 << "context is '" << NameContext
1817 << "'. Due to this name mismatch, "
1818 << "the -polly-context option is ignored. Please provide "
1819 << "the context in the parameter space: " << SpaceStr << ".\n";
1820 free(SpaceStr);
1821 isl_set_free(UserContext);
1822 isl_space_free(Space);
1823 return;
1824 }
1825
1826 UserContext =
1827 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1828 isl_space_get_dim_id(Space, isl_dim_param, i));
1829 }
1830
1831 Context = isl_set_intersect(Context, UserContext);
1832 isl_space_free(Space);
1833}
1834
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001835void Scop::buildInvariantEquivalenceClasses(ScopDetection &SD) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00001836 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001837
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001838 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001839 for (LoadInst *LInst : RIL) {
1840 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1841
Johannes Doerfert96e54712016-02-07 17:30:13 +00001842 Type *Ty = LInst->getType();
1843 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001844 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001845 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001846 continue;
1847 }
1848
1849 ClassRep = LInst;
Johannes Doerfert96e54712016-02-07 17:30:13 +00001850 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(), nullptr,
1851 Ty);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001852 }
1853}
1854
Tobias Grosser6be480c2011-11-08 15:41:13 +00001855void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001856 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001857 Context = isl_set_universe(isl_space_copy(Space));
1858 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001859}
1860
Tobias Grosser18daaca2012-05-22 10:47:27 +00001861void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001862 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001863 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001864
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001865 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001866
Johannes Doerferte7044942015-02-24 11:58:30 +00001867 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001868 }
1869}
1870
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001871void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001872 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001873 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001874
Tobias Grosser083d3d32014-06-28 08:59:45 +00001875 for (const auto &ParamID : ParameterIds) {
1876 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001877 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001878 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001879 }
1880
1881 // Align the parameters of all data structures to the model.
1882 Context = isl_set_align_params(Context, Space);
1883
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001884 for (ScopStmt &Stmt : *this)
1885 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001886}
1887
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001888static __isl_give isl_set *
1889simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1890 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001891 // If we modelt all blocks in the SCoP that have side effects we can simplify
1892 // the context with the constraints that are needed for anything to be
1893 // executed at all. However, if we have error blocks in the SCoP we already
1894 // assumed some parameter combinations cannot occure and removed them from the
1895 // domains, thus we cannot use the remaining domain to simplify the
1896 // assumptions.
1897 if (!S.hasErrorBlock()) {
1898 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1899 AssumptionContext =
1900 isl_set_gist_params(AssumptionContext, DomainParameters);
1901 }
1902
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001903 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1904 return AssumptionContext;
1905}
1906
1907void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001908 // The parameter constraints of the iteration domains give us a set of
1909 // constraints that need to hold for all cases where at least a single
1910 // statement iteration is executed in the whole scop. We now simplify the
1911 // assumed context under the assumption that such constraints hold and at
1912 // least a single statement iteration is executed. For cases where no
1913 // statement instances are executed, the assumptions we have taken about
1914 // the executed code do not matter and can be changed.
1915 //
1916 // WARNING: This only holds if the assumptions we have taken do not reduce
1917 // the set of statement instances that are executed. Otherwise we
1918 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001919 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001920 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001921 // performed. In such a case, modifying the run-time conditions and
1922 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001923 // to not be executed.
1924 //
1925 // Example:
1926 //
1927 // When delinearizing the following code:
1928 //
1929 // for (long i = 0; i < 100; i++)
1930 // for (long j = 0; j < m; j++)
1931 // A[i+p][j] = 1.0;
1932 //
1933 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001934 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001935 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001936 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1937 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001938}
1939
Johannes Doerfertb164c792014-09-18 11:17:17 +00001940/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001941static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001942 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1943 isl_pw_multi_aff *MinPMA, *MaxPMA;
1944 isl_pw_aff *LastDimAff;
1945 isl_aff *OneAff;
1946 unsigned Pos;
1947
Johannes Doerfert9143d672014-09-27 11:02:39 +00001948 // Restrict the number of parameters involved in the access as the lexmin/
1949 // lexmax computation will take too long if this number is high.
1950 //
1951 // Experiments with a simple test case using an i7 4800MQ:
1952 //
1953 // #Parameters involved | Time (in sec)
1954 // 6 | 0.01
1955 // 7 | 0.04
1956 // 8 | 0.12
1957 // 9 | 0.40
1958 // 10 | 1.54
1959 // 11 | 6.78
1960 // 12 | 30.38
1961 //
1962 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1963 unsigned InvolvedParams = 0;
1964 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1965 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1966 InvolvedParams++;
1967
1968 if (InvolvedParams > RunTimeChecksMaxParameters) {
1969 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001970 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001971 }
1972 }
1973
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001974 Set = isl_set_remove_divs(Set);
1975
Johannes Doerfertb164c792014-09-18 11:17:17 +00001976 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1977 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1978
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001979 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1980 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1981
Johannes Doerfertb164c792014-09-18 11:17:17 +00001982 // Adjust the last dimension of the maximal access by one as we want to
1983 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1984 // we test during code generation might now point after the end of the
1985 // allocated array but we will never dereference it anyway.
1986 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1987 "Assumed at least one output dimension");
1988 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1989 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1990 OneAff = isl_aff_zero_on_domain(
1991 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1992 OneAff = isl_aff_add_constant_si(OneAff, 1);
1993 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1994 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1995
1996 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1997
1998 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001999 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002000}
2001
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002002static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2003 isl_set *Domain = MA->getStatement()->getDomain();
2004 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2005 return isl_set_reset_tuple_id(Domain);
2006}
2007
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002008/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
2009static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00002010 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002011 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002012
2013 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2014 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002015 Locations = isl_union_set_coalesce(Locations);
2016 Locations = isl_union_set_detect_equalities(Locations);
2017 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002018 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002019 isl_union_set_free(Locations);
2020 return Valid;
2021}
2022
Johannes Doerfert96425c22015-08-30 21:13:53 +00002023/// @brief Helper to treat non-affine regions and basic blocks the same.
2024///
2025///{
2026
2027/// @brief Return the block that is the representing block for @p RN.
2028static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2029 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2030 : RN->getNodeAs<BasicBlock>();
2031}
2032
2033/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002034static inline BasicBlock *
2035getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002036 if (RN->isSubRegion()) {
2037 assert(idx == 0);
2038 return RN->getNodeAs<Region>()->getExit();
2039 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002040 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002041}
2042
2043/// @brief Return the smallest loop surrounding @p RN.
2044static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2045 if (!RN->isSubRegion())
2046 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2047
2048 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2049 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2050 while (L && NonAffineSubRegion->contains(L))
2051 L = L->getParentLoop();
2052 return L;
2053}
2054
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002055static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2056 if (!RN->isSubRegion())
2057 return 1;
2058
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002059 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002060 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002061}
2062
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002063static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2064 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002065 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002066 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002067 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002068 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002069 return true;
2070 return false;
2071}
2072
Johannes Doerfert96425c22015-08-30 21:13:53 +00002073///}
2074
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002075static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2076 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002077 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002078 isl_id *DimId =
2079 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2080 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2081}
2082
Johannes Doerfert96425c22015-08-30 21:13:53 +00002083isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
2084 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
2085 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002086 return getDomainConditions(BB);
2087}
2088
2089isl_set *Scop::getDomainConditions(BasicBlock *BB) {
2090 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002091 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002092}
2093
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002094void Scop::removeErrorBlockDomains(ScopDetection &SD, DominatorTree &DT,
2095 LoopInfo &LI) {
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002096 auto removeDomains = [this, &DT](BasicBlock *Start) {
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002097 auto BBNode = DT.getNode(Start);
2098 for (auto ErrorChild : depth_first(BBNode)) {
2099 auto ErrorChildBlock = ErrorChild->getBlock();
2100 auto CurrentDomain = DomainMap[ErrorChildBlock];
2101 auto Empty = isl_set_empty(isl_set_get_space(CurrentDomain));
2102 DomainMap[ErrorChildBlock] = Empty;
2103 isl_set_free(CurrentDomain);
2104 }
2105 };
2106
Tobias Grosser5ef2bc32015-11-23 10:18:23 +00002107 SmallVector<Region *, 4> Todo = {&R};
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002108
2109 while (!Todo.empty()) {
2110 auto SubRegion = Todo.back();
2111 Todo.pop_back();
2112
2113 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
2114 for (auto &Child : *SubRegion)
2115 Todo.push_back(Child.get());
2116 continue;
2117 }
2118 if (containsErrorBlock(SubRegion->getNode(), getRegion(), LI, DT))
2119 removeDomains(SubRegion->getEntry());
2120 }
2121
2122 for (auto BB : R.blocks())
2123 if (isErrorBlock(*BB, R, LI, DT))
2124 removeDomains(BB);
2125}
2126
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002127void Scop::buildDomains(Region *R, ScopDetection &SD, DominatorTree &DT,
2128 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002129
Johannes Doerfert432658d2016-01-26 11:01:41 +00002130 bool IsOnlyNonAffineRegion = SD.isNonAffineSubRegion(R, R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002131 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002132 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2133 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002134 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002135
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002136 while (LD-- >= 0) {
2137 S = addDomainDimId(S, LD + 1, L);
2138 L = L->getParentLoop();
2139 }
2140
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002141 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002142
Johannes Doerfert432658d2016-01-26 11:01:41 +00002143 if (IsOnlyNonAffineRegion)
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002144 return;
2145
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002146 buildDomainsWithBranchConstraints(R, SD, DT, LI);
2147 propagateDomainConstraints(R, SD, DT, LI);
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002148
2149 // Error blocks and blocks dominated by them have been assumed to never be
2150 // executed. Representing them in the Scop does not add any value. In fact,
2151 // it is likely to cause issues during construction of the ScopStmts. The
2152 // contents of error blocks have not been verfied to be expressible and
2153 // will cause problems when building up a ScopStmt for them.
2154 // Furthermore, basic blocks dominated by error blocks may reference
2155 // instructions in the error block which, if the error block is not modeled,
2156 // can themselves not be constructed properly.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002157 removeErrorBlockDomains(SD, DT, LI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002158}
2159
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002160void Scop::buildDomainsWithBranchConstraints(Region *R, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002161 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert6f50c292016-01-26 11:03:25 +00002162 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002163
2164 // To create the domain for each block in R we iterate over all blocks and
2165 // subregions in R and propagate the conditions under which the current region
2166 // element is executed. To this end we iterate in reverse post order over R as
2167 // it ensures that we first visit all predecessors of a region node (either a
2168 // basic block or a subregion) before we visit the region node itself.
2169 // Initially, only the domain for the SCoP region entry block is set and from
2170 // there we propagate the current domain to all successors, however we add the
2171 // condition that the successor is actually executed next.
2172 // As we are only interested in non-loop carried constraints here we can
2173 // simply skip loop back edges.
2174
2175 ReversePostOrderTraversal<Region *> RTraversal(R);
2176 for (auto *RN : RTraversal) {
2177
2178 // Recurse for affine subregions but go on for basic blocks and non-affine
2179 // subregions.
2180 if (RN->isSubRegion()) {
2181 Region *SubRegion = RN->getNodeAs<Region>();
2182 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002183 buildDomainsWithBranchConstraints(SubRegion, SD, DT, LI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002184 continue;
2185 }
2186 }
2187
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002188 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002189 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002190
Johannes Doerfert96425c22015-08-30 21:13:53 +00002191 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002192 TerminatorInst *TI = BB->getTerminator();
2193
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002194 if (isa<UnreachableInst>(TI))
2195 continue;
2196
Johannes Doerfertf5673802015-10-01 23:48:18 +00002197 isl_set *Domain = DomainMap.lookup(BB);
2198 if (!Domain) {
2199 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2200 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002201 continue;
2202 }
2203
Johannes Doerfert96425c22015-08-30 21:13:53 +00002204 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002205
2206 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2207 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2208
2209 // Build the condition sets for the successor nodes of the current region
2210 // node. If it is a non-affine subregion we will always execute the single
2211 // exit node, hence the single entry node domain is the condition set. For
2212 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002213 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002214 if (RN->isSubRegion())
2215 ConditionSets.push_back(isl_set_copy(Domain));
2216 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002217 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002218
2219 // Now iterate over the successors and set their initial domain based on
2220 // their condition set. We skip back edges here and have to be careful when
2221 // we leave a loop not to keep constraints over a dimension that doesn't
2222 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002223 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002224 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002225 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002226 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002227
2228 // Skip back edges.
2229 if (DT.dominates(SuccBB, BB)) {
2230 isl_set_free(CondSet);
2231 continue;
2232 }
2233
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002234 // Do not adjust the number of dimensions if we enter a boxed loop or are
2235 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002236 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfert6f50c292016-01-26 11:03:25 +00002237 while (BoxedLoops.count(SuccBBLoop))
2238 SuccBBLoop = SuccBBLoop->getParentLoop();
Johannes Doerfert634909c2015-10-04 14:57:41 +00002239
2240 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002241
2242 // Check if the edge to SuccBB is a loop entry or exit edge. If so
2243 // adjust the dimensionality accordingly. Lastly, if we leave a loop
2244 // and enter a new one we need to drop the old constraints.
2245 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002246 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002247 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002248 CondSet = isl_set_project_out(CondSet, isl_dim_set,
2249 isl_set_n_dim(CondSet) - LoopDepthDiff,
2250 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002251 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002252 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002253 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002254 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002255 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002256 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002257 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
2258 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002259 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002260 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002261 }
2262
2263 // Set the domain for the successor or merge it with an existing domain in
2264 // case there are multiple paths (without loop back edges) to the
2265 // successor block.
2266 isl_set *&SuccDomain = DomainMap[SuccBB];
2267 if (!SuccDomain)
2268 SuccDomain = CondSet;
2269 else
2270 SuccDomain = isl_set_union(SuccDomain, CondSet);
2271
2272 SuccDomain = isl_set_coalesce(SuccDomain);
Tobias Grosser75dc40c2015-12-20 13:31:48 +00002273 if (isl_set_n_basic_set(SuccDomain) > MaxConjunctsInDomain) {
2274 auto *Empty = isl_set_empty(isl_set_get_space(SuccDomain));
2275 isl_set_free(SuccDomain);
2276 SuccDomain = Empty;
2277 invalidate(ERROR_DOMAINCONJUNCTS, DebugLoc());
2278 }
Johannes Doerfert634909c2015-10-04 14:57:41 +00002279 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
2280 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002281 }
2282 }
2283}
2284
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002285/// @brief Return the domain for @p BB wrt @p DomainMap.
2286///
2287/// This helper function will lookup @p BB in @p DomainMap but also handle the
2288/// case where @p BB is contained in a non-affine subregion using the region
2289/// tree obtained by @p RI.
2290static __isl_give isl_set *
2291getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
2292 RegionInfo &RI) {
2293 auto DIt = DomainMap.find(BB);
2294 if (DIt != DomainMap.end())
2295 return isl_set_copy(DIt->getSecond());
2296
2297 Region *R = RI.getRegionFor(BB);
2298 while (R->getEntry() == BB)
2299 R = R->getParent();
2300 return getDomainForBlock(R->getEntry(), DomainMap, RI);
2301}
2302
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002303void Scop::propagateDomainConstraints(Region *R, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002304 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002305 // Iterate over the region R and propagate the domain constrains from the
2306 // predecessors to the current node. In contrast to the
2307 // buildDomainsWithBranchConstraints function, this one will pull the domain
2308 // information from the predecessors instead of pushing it to the successors.
2309 // Additionally, we assume the domains to be already present in the domain
2310 // map here. However, we iterate again in reverse post order so we know all
2311 // predecessors have been visited before a block or non-affine subregion is
2312 // visited.
2313
2314 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2315 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2316
2317 ReversePostOrderTraversal<Region *> RTraversal(R);
2318 for (auto *RN : RTraversal) {
2319
2320 // Recurse for affine subregions but go on for basic blocks and non-affine
2321 // subregions.
2322 if (RN->isSubRegion()) {
2323 Region *SubRegion = RN->getNodeAs<Region>();
2324 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002325 propagateDomainConstraints(SubRegion, SD, DT, LI);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002326 continue;
2327 }
2328 }
2329
Johannes Doerfertf5673802015-10-01 23:48:18 +00002330 // Get the domain for the current block and check if it was initialized or
2331 // not. The only way it was not is if this block is only reachable via error
2332 // blocks, thus will not be executed under the assumptions we make. Such
2333 // blocks have to be skipped as their predecessors might not have domains
2334 // either. It would not benefit us to compute the domain anyway, only the
2335 // domains of the error blocks that are reachable from non-error blocks
2336 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002337 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002338 isl_set *&Domain = DomainMap[BB];
2339 if (!Domain) {
2340 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2341 << ", it is only reachable from error blocks.\n");
2342 DomainMap.erase(BB);
2343 continue;
2344 }
2345 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
2346
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002347 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2348 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2349
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002350 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2351 for (auto *PredBB : predecessors(BB)) {
2352
2353 // Skip backedges
2354 if (DT.dominates(BB, PredBB))
2355 continue;
2356
2357 isl_set *PredBBDom = nullptr;
2358
2359 // Handle the SCoP entry block with its outside predecessors.
2360 if (!getRegion().contains(PredBB))
2361 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
2362
2363 if (!PredBBDom) {
2364 // Determine the loop depth of the predecessor and adjust its domain to
2365 // the domain of the current block. This can mean we have to:
2366 // o) Drop a dimension if this block is the exit of a loop, not the
2367 // header of a new loop and the predecessor was part of the loop.
2368 // o) Add an unconstrainted new dimension if this block is the header
2369 // of a loop and the predecessor is not part of it.
2370 // o) Drop the information about the innermost loop dimension when the
2371 // predecessor and the current block are surrounded by different
2372 // loops in the same depth.
2373 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2374 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2375 while (BoxedLoops.count(PredBBLoop))
2376 PredBBLoop = PredBBLoop->getParentLoop();
2377
2378 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002379 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002380 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002381 PredBBDom = isl_set_project_out(
2382 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2383 LoopDepthDiff);
2384 else if (PredBBLoopDepth < BBLoopDepth) {
2385 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002386 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002387 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2388 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002389 PredBBDom = isl_set_drop_constraints_involving_dims(
2390 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002391 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002392 }
2393
2394 PredDom = isl_set_union(PredDom, PredBBDom);
2395 }
2396
2397 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002398 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002399
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002400 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002401 addLoopBoundsToHeaderDomain(BBLoop, LI);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002402
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002403 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002404 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002405 IsOptimized = true;
2406 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002407 addAssumption(ERRORBLOCK, isl_set_complement(DomPar),
2408 BB->getTerminator()->getDebugLoc());
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002409 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002410 }
2411}
2412
2413/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2414/// is incremented by one and all other dimensions are equal, e.g.,
2415/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2416/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2417static __isl_give isl_map *
2418createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2419 auto *MapSpace = isl_space_map_from_set(SetSpace);
2420 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2421 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2422 if (u != Dim)
2423 NextIterationMap =
2424 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2425 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2426 C = isl_constraint_set_constant_si(C, 1);
2427 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2428 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2429 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2430 return NextIterationMap;
2431}
2432
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002433void Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002434 int LoopDepth = getRelativeLoopDepth(L);
2435 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002436
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002437 BasicBlock *HeaderBB = L->getHeader();
2438 assert(DomainMap.count(HeaderBB));
2439 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002440
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002441 isl_map *NextIterationMap =
2442 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002443
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002444 isl_set *UnionBackedgeCondition =
2445 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002446
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002447 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2448 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002449
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002450 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002451
2452 // If the latch is only reachable via error statements we skip it.
2453 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2454 if (!LatchBBDom)
2455 continue;
2456
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002457 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002458
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002459 TerminatorInst *TI = LatchBB->getTerminator();
2460 BranchInst *BI = dyn_cast<BranchInst>(TI);
2461 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002462 BackedgeCondition = isl_set_copy(LatchBBDom);
2463 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002464 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002465 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002466 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002467
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002468 // Free the non back edge condition set as we do not need it.
2469 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002470
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002471 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002472 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002473
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002474 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2475 assert(LatchLoopDepth >= LoopDepth);
2476 BackedgeCondition =
2477 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2478 LatchLoopDepth - LoopDepth);
2479 UnionBackedgeCondition =
2480 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002481 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002482
2483 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2484 for (int i = 0; i < LoopDepth; i++)
2485 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2486
2487 isl_set *UnionBackedgeConditionComplement =
2488 isl_set_complement(UnionBackedgeCondition);
2489 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2490 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2491 UnionBackedgeConditionComplement =
2492 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2493 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2494 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2495
2496 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2497 HeaderBBDom = Parts.second;
2498
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002499 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2500 // the bounded assumptions to the context as they are already implied by the
2501 // <nsw> tag.
2502 if (Affinator.hasNSWAddRecForLoop(L)) {
2503 isl_set_free(Parts.first);
2504 return;
2505 }
2506
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002507 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2508 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002509 addAssumption(INFINITELOOP, BoundedCtx,
2510 HeaderBB->getTerminator()->getDebugLoc());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002511}
2512
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002513void Scop::buildAliasChecks(AliasAnalysis &AA) {
2514 if (!PollyUseRuntimeAliasChecks)
2515 return;
2516
2517 if (buildAliasGroups(AA))
2518 return;
2519
2520 // If a problem occurs while building the alias groups we need to delete
2521 // this SCoP and pretend it wasn't valid in the first place. To this end
2522 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002523 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002524
2525 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2526 << " could not be created as the number of parameters involved "
2527 "is too high. The SCoP will be "
2528 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2529 "the maximal number of parameters but be advised that the "
2530 "compile time might increase exponentially.\n\n");
2531}
2532
Johannes Doerfert9143d672014-09-27 11:02:39 +00002533bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002534 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002535 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002536 // for all memory accesses inside the SCoP.
2537 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002538 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002539 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002540 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002541 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002542 // if their access domains intersect, otherwise they are in different
2543 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002544 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002545 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002546 // and maximal accesses to each array of a group in read only and non
2547 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002548 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2549
2550 AliasSetTracker AST(AA);
2551
2552 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002553 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002554 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002555
2556 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002557 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002558 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2559 isl_set_free(StmtDomain);
2560 if (StmtDomainEmpty)
2561 continue;
2562
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002563 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002564 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002565 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002566 if (!MA->isRead())
2567 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002568 MemAccInst Acc(MA->getAccessInstruction());
2569 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002570 AST.add(Acc);
2571 }
2572 }
2573
2574 SmallVector<AliasGroupTy, 4> AliasGroups;
2575 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002576 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002577 continue;
2578 AliasGroupTy AG;
2579 for (auto PR : AS)
2580 AG.push_back(PtrToAcc[PR.getValue()]);
2581 assert(AG.size() > 1 &&
2582 "Alias groups should contain at least two accesses");
2583 AliasGroups.push_back(std::move(AG));
2584 }
2585
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002586 // Split the alias groups based on their domain.
2587 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2588 AliasGroupTy NewAG;
2589 AliasGroupTy &AG = AliasGroups[u];
2590 AliasGroupTy::iterator AGI = AG.begin();
2591 isl_set *AGDomain = getAccessDomain(*AGI);
2592 while (AGI != AG.end()) {
2593 MemoryAccess *MA = *AGI;
2594 isl_set *MADomain = getAccessDomain(MA);
2595 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2596 NewAG.push_back(MA);
2597 AGI = AG.erase(AGI);
2598 isl_set_free(MADomain);
2599 } else {
2600 AGDomain = isl_set_union(AGDomain, MADomain);
2601 AGI++;
2602 }
2603 }
2604 if (NewAG.size() > 1)
2605 AliasGroups.push_back(std::move(NewAG));
2606 isl_set_free(AGDomain);
2607 }
2608
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002609 auto &F = *getRegion().getEntry()->getParent();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002610 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002611 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2612 for (AliasGroupTy &AG : AliasGroups) {
2613 NonReadOnlyBaseValues.clear();
2614 ReadOnlyPairs.clear();
2615
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002616 if (AG.size() < 2) {
2617 AG.clear();
2618 continue;
2619 }
2620
Johannes Doerfert13771732014-10-01 12:40:46 +00002621 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002622 emitOptimizationRemarkAnalysis(
2623 F.getContext(), DEBUG_TYPE, F,
2624 (*II)->getAccessInstruction()->getDebugLoc(),
2625 "Possibly aliasing pointer, use restrict keyword.");
2626
Johannes Doerfert13771732014-10-01 12:40:46 +00002627 Value *BaseAddr = (*II)->getBaseAddr();
2628 if (HasWriteAccess.count(BaseAddr)) {
2629 NonReadOnlyBaseValues.insert(BaseAddr);
2630 II++;
2631 } else {
2632 ReadOnlyPairs[BaseAddr].insert(*II);
2633 II = AG.erase(II);
2634 }
2635 }
2636
2637 // If we don't have read only pointers check if there are at least two
2638 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002639 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002640 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002641 continue;
2642 }
2643
2644 // If we don't have non read only pointers clear the alias group.
2645 if (NonReadOnlyBaseValues.empty()) {
2646 AG.clear();
2647 continue;
2648 }
2649
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002650 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002651 MinMaxAliasGroups.emplace_back();
2652 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2653 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2654 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2655 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002656
2657 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002658
2659 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002660 for (MemoryAccess *MA : AG)
2661 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002662
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002663 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2664 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002665
2666 // Bail out if the number of values we need to compare is too large.
2667 // This is important as the number of comparisions grows quadratically with
2668 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002669 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2670 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002671 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002672
2673 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002674 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002675 Accesses = isl_union_map_empty(getParamSpace());
2676
2677 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2678 for (MemoryAccess *MA : ReadOnlyPair.second)
2679 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2680
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002681 Valid =
2682 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002683
2684 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002685 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002686 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002687
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002688 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002689}
2690
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002691/// @brief Get the smallest loop that contains @p R but is not in @p R.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002692static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002693 // Start with the smallest loop containing the entry and expand that
2694 // loop until it contains all blocks in the region. If there is a loop
2695 // containing all blocks in the region check if it is itself contained
2696 // and if so take the parent loop as it will be the smallest containing
2697 // the region but not contained by it.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002698 Loop *L = LI.getLoopFor(R.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002699 while (L) {
2700 bool AllContained = true;
2701 for (auto *BB : R.blocks())
2702 AllContained &= L->contains(BB);
2703 if (AllContained)
2704 break;
2705 L = L->getParentLoop();
2706 }
2707
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002708 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2709}
2710
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002711static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2712 ScopDetection &SD) {
2713
2714 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2715
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002716 unsigned MinLD = INT_MAX, MaxLD = 0;
2717 for (BasicBlock *BB : R.blocks()) {
2718 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002719 if (!R.contains(L))
2720 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002721 if (BoxedLoops && BoxedLoops->count(L))
2722 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002723 unsigned LD = L->getLoopDepth();
2724 MinLD = std::min(MinLD, LD);
2725 MaxLD = std::max(MaxLD, LD);
2726 }
2727 }
2728
2729 // Handle the case that there is no loop in the SCoP first.
2730 if (MaxLD == 0)
2731 return 1;
2732
2733 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2734 assert(MaxLD >= MinLD &&
2735 "Maximal loop depth was smaller than mininaml loop depth?");
2736 return MaxLD - MinLD + 1;
2737}
2738
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002739Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, unsigned MaxLoopDepth)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00002740 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002741 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002742 MaxLoopDepth(MaxLoopDepth), IslCtx(isl_ctx_alloc(), isl_ctx_free),
2743 Context(nullptr), Affinator(this), AssumedContext(nullptr),
2744 BoundaryContext(nullptr), Schedule(nullptr) {
2745 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00002746 buildContext();
2747}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002748
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002749void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002750 DominatorTree &DT, LoopInfo &LI) {
2751 addUserAssumptions(AC, DT, LI);
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002752 buildInvariantEquivalenceClasses(SD);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002753
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002754 buildDomains(&R, SD, DT, LI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002755
Michael Krusecac948e2015-10-02 13:53:07 +00002756 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002757 // Exit early in case there are no executable statements left in this scop.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002758 simplifySCoP(true, DT, LI);
Michael Kruseafe06702015-10-02 16:33:27 +00002759 if (Stmts.empty())
2760 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002761
Michael Krusecac948e2015-10-02 13:53:07 +00002762 // The ScopStmts now have enough information to initialize themselves.
2763 for (ScopStmt &Stmt : Stmts)
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002764 Stmt.init(SD);
Michael Krusecac948e2015-10-02 13:53:07 +00002765
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002766 buildSchedule(SD, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00002767
Tobias Grosser8286b832015-11-02 11:29:32 +00002768 if (isl_set_is_empty(AssumedContext))
2769 return;
2770
2771 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002772 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002773 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002774 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002775 buildBoundaryContext();
2776 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002777 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002778
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002779 hoistInvariantLoads(SD);
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002780 simplifySCoP(false, DT, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00002781}
2782
2783Scop::~Scop() {
2784 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002785 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002786 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002787 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002788
Johannes Doerfert96425c22015-08-30 21:13:53 +00002789 for (auto It : DomainMap)
2790 isl_set_free(It.second);
2791
Johannes Doerfertb164c792014-09-18 11:17:17 +00002792 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002793 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002794 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002795 isl_pw_multi_aff_free(MMA.first);
2796 isl_pw_multi_aff_free(MMA.second);
2797 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002798 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002799 isl_pw_multi_aff_free(MMA.first);
2800 isl_pw_multi_aff_free(MMA.second);
2801 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002802 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002803
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002804 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002805 isl_set_free(std::get<2>(IAClass));
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002806
2807 // Explicitly release all Scop objects and the underlying isl objects before
2808 // we relase the isl context.
2809 Stmts.clear();
2810 ScopArrayInfoMap.clear();
2811 AccFuncMap.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00002812}
2813
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002814void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00002815 // Check all array accesses for each base pointer and find a (virtual) element
2816 // size for the base pointer that divides all access functions.
2817 for (auto &Stmt : *this)
2818 for (auto *Access : Stmt) {
2819 if (!Access->isArrayKind())
2820 continue;
2821 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(),
2822 ScopArrayInfo::MK_Array)];
2823 if (SAI->getNumberOfDimensions() != 1)
2824 continue;
2825 unsigned DivisibleSize = SAI->getElemSizeInBytes();
2826 auto *Subscript = Access->getSubscript(0);
2827 while (!isDivisible(Subscript, DivisibleSize, *SE))
2828 DivisibleSize /= 2;
2829 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
2830 SAI->updateElementType(Ty);
2831 }
2832
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002833 for (auto &Stmt : *this)
2834 for (auto &Access : Stmt)
2835 Access->updateDimensionality();
2836}
2837
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002838void Scop::simplifySCoP(bool RemoveIgnoredStmts, DominatorTree &DT,
2839 LoopInfo &LI) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002840 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2841 ScopStmt &Stmt = *StmtIt;
Michael Krusecac948e2015-10-02 13:53:07 +00002842 RegionNode *RN = Stmt.isRegionStmt()
2843 ? Stmt.getRegion()->getNode()
2844 : getRegion().getBBNode(Stmt.getBasicBlock());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002845
Johannes Doerferteca9e892015-11-03 16:54:49 +00002846 bool RemoveStmt = StmtIt->isEmpty();
2847 if (!RemoveStmt)
2848 RemoveStmt = isl_set_is_empty(DomainMap[getRegionNodeBasicBlock(RN)]);
2849 if (!RemoveStmt)
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002850 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN, DT, LI));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002851
Johannes Doerferteca9e892015-11-03 16:54:49 +00002852 // Remove read only statements only after invariant loop hoisting.
2853 if (!RemoveStmt && !RemoveIgnoredStmts) {
2854 bool OnlyRead = true;
2855 for (MemoryAccess *MA : Stmt) {
2856 if (MA->isRead())
2857 continue;
2858
2859 OnlyRead = false;
2860 break;
2861 }
2862
2863 RemoveStmt = OnlyRead;
2864 }
2865
2866 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00002867 // Remove the statement because it is unnecessary.
2868 if (Stmt.isRegionStmt())
2869 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2870 StmtMap.erase(BB);
2871 else
2872 StmtMap.erase(Stmt.getBasicBlock());
2873
2874 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002875 continue;
2876 }
2877
Michael Krusecac948e2015-10-02 13:53:07 +00002878 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002879 }
2880}
2881
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002882const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2883 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2884 if (!LInst)
2885 return nullptr;
2886
2887 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2888 LInst = cast<LoadInst>(Rep);
2889
Johannes Doerfert96e54712016-02-07 17:30:13 +00002890 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002891 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2892 for (auto &IAClass : InvariantEquivClasses)
Johannes Doerfert96e54712016-02-07 17:30:13 +00002893 if (PointerSCEV == std::get<0>(IAClass) && Ty == std::get<3>(IAClass))
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002894 return &IAClass;
2895
2896 return nullptr;
2897}
2898
2899void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2900
2901 // Get the context under which the statement is executed.
2902 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2903 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2904 DomainCtx = isl_set_detect_equalities(DomainCtx);
2905 DomainCtx = isl_set_coalesce(DomainCtx);
2906
2907 // Project out all parameters that relate to loads in the statement. Otherwise
2908 // we could have cyclic dependences on the constraints under which the
2909 // hoisted loads are executed and we could not determine an order in which to
2910 // pre-load them. This happens because not only lower bounds are part of the
2911 // domain but also upper bounds.
2912 for (MemoryAccess *MA : InvMAs) {
2913 Instruction *AccInst = MA->getAccessInstruction();
2914 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00002915 SetVector<Value *> Values;
2916 for (const SCEV *Parameter : Parameters) {
2917 Values.clear();
2918 findValues(Parameter, Values);
2919 if (!Values.count(AccInst))
2920 continue;
2921
2922 if (isl_id *ParamId = getIdForParam(Parameter)) {
2923 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2924 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2925 isl_id_free(ParamId);
2926 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002927 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002928 }
2929 }
2930
2931 for (MemoryAccess *MA : InvMAs) {
2932 // Check for another invariant access that accesses the same location as
2933 // MA and if found consolidate them. Otherwise create a new equivalence
2934 // class at the end of InvariantEquivClasses.
2935 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00002936 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002937 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2938
2939 bool Consolidated = false;
2940 for (auto &IAClass : InvariantEquivClasses) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002941 if (PointerSCEV != std::get<0>(IAClass) || Ty != std::get<3>(IAClass))
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002942 continue;
2943
2944 Consolidated = true;
2945
2946 // Add MA to the list of accesses that are in this class.
2947 auto &MAs = std::get<1>(IAClass);
2948 MAs.push_front(MA);
2949
2950 // Unify the execution context of the class and this statement.
2951 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002952 if (IAClassDomainCtx)
2953 IAClassDomainCtx = isl_set_coalesce(
2954 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
2955 else
2956 IAClassDomainCtx = isl_set_copy(DomainCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002957 break;
2958 }
2959
2960 if (Consolidated)
2961 continue;
2962
2963 // If we did not consolidate MA, thus did not find an equivalence class
2964 // for it, we create a new one.
2965 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
Johannes Doerfert96e54712016-02-07 17:30:13 +00002966 isl_set_copy(DomainCtx), Ty);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002967 }
2968
2969 isl_set_free(DomainCtx);
2970}
2971
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002972bool Scop::isHoistableAccess(MemoryAccess *Access,
2973 __isl_keep isl_union_map *Writes) {
2974 // TODO: Loads that are not loop carried, hence are in a statement with
2975 // zero iterators, are by construction invariant, though we
2976 // currently "hoist" them anyway. This is necessary because we allow
2977 // them to be treated as parameters (e.g., in conditions) and our code
2978 // generation would otherwise use the old value.
2979
2980 auto &Stmt = *Access->getStatement();
2981 BasicBlock *BB =
2982 Stmt.isBlockStmt() ? Stmt.getBasicBlock() : Stmt.getRegion()->getEntry();
2983
2984 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
2985 return false;
2986
2987 // Skip accesses that have an invariant base pointer which is defined but
2988 // not loaded inside the SCoP. This can happened e.g., if a readnone call
2989 // returns a pointer that is used as a base address. However, as we want
2990 // to hoist indirect pointers, we allow the base pointer to be defined in
2991 // the region if it is also a memory access. Each ScopArrayInfo object
2992 // that has a base pointer origin has a base pointer that is loaded and
2993 // that it is invariant, thus it will be hoisted too. However, if there is
2994 // no base pointer origin we check that the base pointer is defined
2995 // outside the region.
2996 const ScopArrayInfo *SAI = Access->getScopArrayInfo();
Johannes Doerfert4cf15802016-02-15 12:42:05 +00002997 auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr());
2998 if (SAI->getBasePtrOriginSAI()) {
2999 assert(BasePtrInst && R.contains(BasePtrInst));
3000 if (!isa<LoadInst>(BasePtrInst))
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003001 return false;
Johannes Doerfert4cf15802016-02-15 12:42:05 +00003002 auto *BasePtrStmt = getStmtForBasicBlock(BasePtrInst->getParent());
3003 assert(BasePtrStmt);
3004 auto *BasePtrMA = BasePtrStmt->getArrayAccessOrNULLFor(BasePtrInst);
3005 if (BasePtrMA && !isHoistableAccess(BasePtrMA, Writes))
3006 return false;
3007 } else if (BasePtrInst && R.contains(BasePtrInst))
3008 return false;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003009
3010 // Skip accesses in non-affine subregions as they might not be executed
3011 // under the same condition as the entry of the non-affine subregion.
3012 if (BB != Access->getAccessInstruction()->getParent())
3013 return false;
3014
3015 isl_map *AccessRelation = Access->getAccessRelation();
3016
3017 // Skip accesses that have an empty access relation. These can be caused
3018 // by multiple offsets with a type cast in-between that cause the overall
3019 // byte offset to be not divisible by the new types sizes.
3020 if (isl_map_is_empty(AccessRelation)) {
3021 isl_map_free(AccessRelation);
3022 return false;
3023 }
3024
3025 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3026 Stmt.getNumIterators())) {
3027 isl_map_free(AccessRelation);
3028 return false;
3029 }
3030
3031 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3032 isl_set *AccessRange = isl_map_range(AccessRelation);
3033
3034 isl_union_map *Written = isl_union_map_intersect_range(
3035 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
3036 bool IsWritten = !isl_union_map_is_empty(Written);
3037 isl_union_map_free(Written);
3038
3039 if (IsWritten)
3040 return false;
3041
3042 return true;
3043}
3044
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003045void Scop::verifyInvariantLoads(ScopDetection &SD) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003046 auto &RIL = *SD.getRequiredInvariantLoads(&getRegion());
3047 for (LoadInst *LI : RIL) {
3048 assert(LI && getRegion().contains(LI));
3049 ScopStmt *Stmt = getStmtForBasicBlock(LI->getParent());
Tobias Grosser949e8c62015-12-21 07:10:39 +00003050 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003051 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3052 return;
3053 }
3054 }
3055}
3056
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003057void Scop::hoistInvariantLoads(ScopDetection &SD) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003058 isl_union_map *Writes = getWrites();
3059 for (ScopStmt &Stmt : *this) {
3060
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003061 MemoryAccessList InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003062
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003063 for (MemoryAccess *Access : Stmt)
3064 if (isHoistableAccess(Access, Writes))
3065 InvariantAccesses.push_front(Access);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003066
3067 // We inserted invariant accesses always in the front but need them to be
3068 // sorted in a "natural order". The statements are already sorted in reverse
3069 // post order and that suffices for the accesses too. The reason we require
3070 // an order in the first place is the dependences between invariant loads
3071 // that can be caused by indirect loads.
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003072 InvariantAccesses.reverse();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003073
3074 // Transfer the memory access from the statement to the SCoP.
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003075 Stmt.removeMemoryAccesses(InvariantAccesses);
3076 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003077 }
3078 isl_union_map_free(Writes);
3079
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003080 verifyInvariantLoads(SD);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003081}
3082
Johannes Doerfert80ef1102014-11-07 08:31:31 +00003083const ScopArrayInfo *
Tobias Grossercc779502016-02-02 13:22:54 +00003084Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003085 ArrayRef<const SCEV *> Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00003086 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003087 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003088 if (!SAI) {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003089 auto &DL = getRegion().getEntry()->getModule()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003090 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003091 DL, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003092 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003093 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003094 // In case of mismatching array sizes, we bail out by setting the run-time
3095 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003096 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003097 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003098 }
Tobias Grosserab671442015-05-23 05:58:27 +00003099 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003100}
3101
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003102const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00003103 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003104 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003105 assert(SAI && "No ScopArrayInfo available for this base pointer");
3106 return SAI;
3107}
3108
Tobias Grosser74394f02013-01-14 22:40:23 +00003109std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003110std::string Scop::getAssumedContextStr() const {
3111 return stringFromIslObj(AssumedContext);
3112}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003113std::string Scop::getBoundaryContextStr() const {
3114 return stringFromIslObj(BoundaryContext);
3115}
Tobias Grosser75805372011-04-29 06:27:02 +00003116
3117std::string Scop::getNameStr() const {
3118 std::string ExitName, EntryName;
3119 raw_string_ostream ExitStr(ExitName);
3120 raw_string_ostream EntryStr(EntryName);
3121
Tobias Grosserf240b482014-01-09 10:42:15 +00003122 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003123 EntryStr.str();
3124
3125 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003126 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003127 ExitStr.str();
3128 } else
3129 ExitName = "FunctionExit";
3130
3131 return EntryName + "---" + ExitName;
3132}
3133
Tobias Grosser74394f02013-01-14 22:40:23 +00003134__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003135__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003136 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003137}
3138
Tobias Grossere86109f2013-10-29 21:05:49 +00003139__isl_give isl_set *Scop::getAssumedContext() const {
3140 return isl_set_copy(AssumedContext);
3141}
3142
Johannes Doerfert43788c52015-08-20 05:58:56 +00003143__isl_give isl_set *Scop::getRuntimeCheckContext() const {
3144 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003145 RuntimeCheckContext =
3146 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
3147 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00003148 return RuntimeCheckContext;
3149}
3150
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003151bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003152 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003153 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00003154 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
3155 isl_set_free(RuntimeCheckContext);
3156 return IsFeasible;
3157}
3158
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003159static std::string toString(AssumptionKind Kind) {
3160 switch (Kind) {
3161 case ALIASING:
3162 return "No-aliasing";
3163 case INBOUNDS:
3164 return "Inbounds";
3165 case WRAPPING:
3166 return "No-overflows";
3167 case ERRORBLOCK:
3168 return "No-error";
3169 case INFINITELOOP:
3170 return "Finite loop";
3171 case INVARIANTLOAD:
3172 return "Invariant load";
3173 case DELINEARIZATION:
3174 return "Delinearization";
Tobias Grosser75dc40c2015-12-20 13:31:48 +00003175 case ERROR_DOMAINCONJUNCTS:
3176 return "Low number of domain conjuncts";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003177 }
3178 llvm_unreachable("Unknown AssumptionKind!");
3179}
3180
3181void Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3182 DebugLoc Loc) {
3183 if (isl_set_is_subset(Context, Set))
3184 return;
3185
3186 if (isl_set_is_subset(AssumedContext, Set))
3187 return;
3188
3189 auto &F = *getRegion().getEntry()->getParent();
3190 std::string Msg = toString(Kind) + " assumption:\t" + stringFromIslObj(Set);
3191 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
3192}
3193
3194void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
3195 DebugLoc Loc) {
3196 trackAssumption(Kind, Set, Loc);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003197 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003198
Johannes Doerfert9d7899e2015-11-11 20:01:31 +00003199 int NSets = isl_set_n_basic_set(AssumedContext);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003200 if (NSets >= MaxDisjunctsAssumed) {
3201 isl_space *Space = isl_set_get_space(AssumedContext);
3202 isl_set_free(AssumedContext);
Tobias Grossere19fca42015-11-11 20:21:39 +00003203 AssumedContext = isl_set_empty(Space);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003204 }
3205
Tobias Grosser7b50bee2014-11-25 10:51:12 +00003206 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003207}
3208
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003209void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
3210 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc);
3211}
3212
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003213__isl_give isl_set *Scop::getBoundaryContext() const {
3214 return isl_set_copy(BoundaryContext);
3215}
3216
Tobias Grosser75805372011-04-29 06:27:02 +00003217void Scop::printContext(raw_ostream &OS) const {
3218 OS << "Context:\n";
3219
3220 if (!Context) {
3221 OS.indent(4) << "n/a\n\n";
3222 return;
3223 }
3224
3225 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003226
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003227 OS.indent(4) << "Assumed Context:\n";
3228 if (!AssumedContext) {
3229 OS.indent(4) << "n/a\n\n";
3230 return;
3231 }
3232
3233 OS.indent(4) << getAssumedContextStr() << "\n";
3234
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003235 OS.indent(4) << "Boundary Context:\n";
3236 if (!BoundaryContext) {
3237 OS.indent(4) << "n/a\n\n";
3238 return;
3239 }
3240
3241 OS.indent(4) << getBoundaryContextStr() << "\n";
3242
Tobias Grosser083d3d32014-06-28 08:59:45 +00003243 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00003244 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00003245 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
3246 }
Tobias Grosser75805372011-04-29 06:27:02 +00003247}
3248
Johannes Doerfertb164c792014-09-18 11:17:17 +00003249void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003250 int noOfGroups = 0;
3251 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003252 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003253 noOfGroups += 1;
3254 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003255 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003256 }
3257
Tobias Grosserbb853c22015-07-25 12:31:03 +00003258 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003259 if (MinMaxAliasGroups.empty()) {
3260 OS.indent(8) << "n/a\n";
3261 return;
3262 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003263
Tobias Grosserbb853c22015-07-25 12:31:03 +00003264 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003265
3266 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003267 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003268 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003269 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003270 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3271 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003272 }
3273 OS << " ]]\n";
3274 }
3275
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003276 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003277 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003278 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003279 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003280 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3281 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003282 }
3283 OS << " ]]\n";
3284 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003285 }
3286}
3287
Tobias Grosser75805372011-04-29 06:27:02 +00003288void Scop::printStatements(raw_ostream &OS) const {
3289 OS << "Statements {\n";
3290
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003291 for (const ScopStmt &Stmt : *this)
3292 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003293
3294 OS.indent(4) << "}\n";
3295}
3296
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003297void Scop::printArrayInfo(raw_ostream &OS) const {
3298 OS << "Arrays {\n";
3299
Tobias Grosserab671442015-05-23 05:58:27 +00003300 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003301 Array.second->print(OS);
3302
3303 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003304
3305 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3306
3307 for (auto &Array : arrays())
3308 Array.second->print(OS, /* SizeAsPwAff */ true);
3309
3310 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003311}
3312
Tobias Grosser75805372011-04-29 06:27:02 +00003313void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00003314 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
3315 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003316 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003317 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003318 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003319 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003320 const auto &MAs = std::get<1>(IAClass);
3321 if (MAs.empty()) {
3322 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003323 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003324 MAs.front()->print(OS);
3325 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003326 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003327 }
3328 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003329 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003330 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003331 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003332 printStatements(OS.indent(4));
3333}
3334
3335void Scop::dump() const { print(dbgs()); }
3336
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003337isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00003338
Johannes Doerfertcef616f2015-09-15 22:49:04 +00003339__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
3340 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003341}
3342
Tobias Grosser808cd692015-07-14 09:33:13 +00003343__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003344 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003345
Tobias Grosser808cd692015-07-14 09:33:13 +00003346 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003347 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003348
3349 return Domain;
3350}
3351
Tobias Grossere5a35142015-11-12 14:07:09 +00003352__isl_give isl_union_map *
3353Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3354 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003355
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003356 for (ScopStmt &Stmt : *this) {
3357 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003358 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003359 continue;
3360
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003361 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003362 isl_map *AccessDomain = MA->getAccessRelation();
3363 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003364 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003365 }
3366 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003367 return isl_union_map_coalesce(Accesses);
3368}
3369
3370__isl_give isl_union_map *Scop::getMustWrites() {
3371 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003372}
3373
3374__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003375 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003376}
3377
Tobias Grosser37eb4222014-02-20 21:43:54 +00003378__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003379 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003380}
3381
3382__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003383 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003384}
3385
Tobias Grosser2ac23382015-11-12 14:07:13 +00003386__isl_give isl_union_map *Scop::getAccesses() {
3387 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3388}
3389
Tobias Grosser808cd692015-07-14 09:33:13 +00003390__isl_give isl_union_map *Scop::getSchedule() const {
3391 auto Tree = getScheduleTree();
3392 auto S = isl_schedule_get_map(Tree);
3393 isl_schedule_free(Tree);
3394 return S;
3395}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003396
Tobias Grosser808cd692015-07-14 09:33:13 +00003397__isl_give isl_schedule *Scop::getScheduleTree() const {
3398 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3399 getDomains());
3400}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003401
Tobias Grosser808cd692015-07-14 09:33:13 +00003402void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3403 auto *S = isl_schedule_from_domain(getDomains());
3404 S = isl_schedule_insert_partial_schedule(
3405 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3406 isl_schedule_free(Schedule);
3407 Schedule = S;
3408}
3409
3410void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3411 isl_schedule_free(Schedule);
3412 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003413}
3414
3415bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3416 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003417 for (ScopStmt &Stmt : *this) {
3418 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003419 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3420 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3421
3422 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3423 isl_union_set_free(StmtDomain);
3424 isl_union_set_free(NewStmtDomain);
3425 continue;
3426 }
3427
3428 Changed = true;
3429
3430 isl_union_set_free(StmtDomain);
3431 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3432
3433 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003434 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003435 isl_union_set_free(NewStmtDomain);
3436 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003437 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003438 }
3439 isl_union_set_free(Domain);
3440 return Changed;
3441}
3442
Tobias Grosser75805372011-04-29 06:27:02 +00003443ScalarEvolution *Scop::getSE() const { return SE; }
3444
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003445bool Scop::isIgnored(RegionNode *RN, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003446 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Michael Krusea902ba62015-12-13 19:21:45 +00003447 ScopStmt *Stmt = getStmtForRegionNode(RN);
3448
3449 // If there is no stmt, then it already has been removed.
3450 if (!Stmt)
3451 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00003452
Johannes Doerfertf5673802015-10-01 23:48:18 +00003453 // Check if there are accesses contained.
Michael Krusea902ba62015-12-13 19:21:45 +00003454 if (Stmt->isEmpty())
Johannes Doerfertf5673802015-10-01 23:48:18 +00003455 return true;
3456
3457 // Check for reachability via non-error blocks.
3458 if (!DomainMap.count(BB))
3459 return true;
3460
3461 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003462 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003463 return true;
3464
3465 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003466}
3467
Tobias Grosser808cd692015-07-14 09:33:13 +00003468struct MapToDimensionDataTy {
3469 int N;
3470 isl_union_pw_multi_aff *Res;
3471};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003472
Tobias Grosser808cd692015-07-14 09:33:13 +00003473// @brief Create a function that maps the elements of 'Set' to its N-th
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003474// dimension and add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00003475//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003476// @param Set The input set.
3477// @param User->N The dimension to map to.
3478// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00003479//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003480// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00003481static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3482 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3483 int Dim;
3484 isl_space *Space;
3485 isl_pw_multi_aff *PMA;
3486
3487 Dim = isl_set_dim(Set, isl_dim_set);
3488 Space = isl_set_get_space(Set);
3489 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3490 Dim - Data->N);
3491 if (Data->N > 1)
3492 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3493 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3494
3495 isl_set_free(Set);
3496
3497 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003498}
3499
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003500// @brief Create an isl_multi_union_aff that defines an identity mapping
3501// from the elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003502//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003503// # Example:
3504//
3505// Domain: { A[i,j]; B[i,j,k] }
3506// N: 1
3507//
3508// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
3509//
3510// @param USet A union set describing the elements for which to generate a
3511// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00003512// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003513// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003514static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003515mapToDimension(__isl_take isl_union_set *USet, int N) {
3516 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00003517 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003518 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003519
Tobias Grosser808cd692015-07-14 09:33:13 +00003520 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00003521
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003522 auto *Space = isl_union_set_get_space(USet);
3523 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00003524
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003525 Data = {N, PwAff};
3526
3527 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
3528
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00003529 (void)Res;
3530
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003531 assert(Res == isl_stat_ok);
3532
3533 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00003534 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3535}
3536
Tobias Grosser316b5b22015-11-11 19:28:14 +00003537void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003538 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003539 Stmts.emplace_back(*this, *BB);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003540 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003541 StmtMap[BB] = Stmt;
3542 } else {
3543 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003544 Stmts.emplace_back(*this, *R);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003545 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003546 for (BasicBlock *BB : R->blocks())
3547 StmtMap[BB] = Stmt;
3548 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003549}
3550
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003551void Scop::buildSchedule(ScopDetection &SD, LoopInfo &LI) {
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003552 Loop *L = getLoopSurroundingRegion(getRegion(), LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003553 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003554 buildSchedule(getRegion().getNode(), LoopStack, SD, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003555 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
3556 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003557}
3558
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003559/// To generate a schedule for the elements in a Region we traverse the Region
3560/// in reverse-post-order and add the contained RegionNodes in traversal order
3561/// to the schedule of the loop that is currently at the top of the LoopStack.
3562/// For loop-free codes, this results in a correct sequential ordering.
3563///
3564/// Example:
3565/// bb1(0)
3566/// / \.
3567/// bb2(1) bb3(2)
3568/// \ / \.
3569/// bb4(3) bb5(4)
3570/// \ /
3571/// bb6(5)
3572///
3573/// Including loops requires additional processing. Whenever a loop header is
3574/// encountered, the corresponding loop is added to the @p LoopStack. Starting
3575/// from an empty schedule, we first process all RegionNodes that are within
3576/// this loop and complete the sequential schedule at this loop-level before
3577/// processing about any other nodes. To implement this
3578/// loop-nodes-first-processing, the reverse post-order traversal is
3579/// insufficient. Hence, we additionally check if the traversal yields
3580/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
3581/// These region-nodes are then queue and only traverse after the all nodes
3582/// within the current loop have been processed.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003583void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, ScopDetection &SD,
3584 LoopInfo &LI) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003585 Loop *OuterScopLoop = getLoopSurroundingRegion(getRegion(), LI);
3586
3587 ReversePostOrderTraversal<Region *> RTraversal(R);
3588 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
3589 std::deque<RegionNode *> DelayList;
3590 bool LastRNWaiting = false;
3591
3592 // Iterate over the region @p R in reverse post-order but queue
3593 // sub-regions/blocks iff they are not part of the last encountered but not
3594 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
3595 // that we queued the last sub-region/block from the reverse post-order
3596 // iterator. If it is set we have to explore the next sub-region/block from
3597 // the iterator (if any) to guarantee progress. If it is not set we first try
3598 // the next queued sub-region/blocks.
3599 while (!WorkList.empty() || !DelayList.empty()) {
3600 RegionNode *RN;
3601
3602 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
3603 RN = WorkList.front();
3604 WorkList.pop_front();
3605 LastRNWaiting = false;
3606 } else {
3607 RN = DelayList.front();
3608 DelayList.pop_front();
3609 }
3610
3611 Loop *L = getRegionNodeLoop(RN, LI);
3612 if (!getRegion().contains(L))
3613 L = OuterScopLoop;
3614
3615 Loop *LastLoop = LoopStack.back().L;
3616 if (LastLoop != L) {
3617 if (!LastLoop->contains(L)) {
3618 LastRNWaiting = true;
3619 DelayList.push_back(RN);
3620 continue;
3621 }
3622 LoopStack.push_back({L, nullptr, 0});
3623 }
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003624 buildSchedule(RN, LoopStack, SD, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003625 }
3626
3627 return;
3628}
3629
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003630void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003631 ScopDetection &SD, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00003632
Tobias Grosser8362c262016-01-06 15:30:06 +00003633 if (RN->isSubRegion()) {
3634 auto *LocalRegion = RN->getNodeAs<Region>();
3635 if (!SD.isNonAffineSubRegion(LocalRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003636 buildSchedule(LocalRegion, LoopStack, SD, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00003637 return;
3638 }
3639 }
Michael Kruse046dde42015-08-10 13:01:57 +00003640
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003641 auto &LoopData = LoopStack.back();
3642 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00003643
Tobias Grosserc9abde82016-01-23 20:23:06 +00003644 if (auto *Stmt = getStmtForRegionNode(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00003645 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3646 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003647 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00003648 }
3649
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003650 // Check if we just processed the last node in this loop. If we did, finalize
3651 // the loop by:
3652 //
3653 // - adding new schedule dimensions
3654 // - folding the resulting schedule into the parent loop schedule
3655 // - dropping the loop schedule from the LoopStack.
3656 //
3657 // Then continue to check surrounding loops, which might also have been
3658 // completed by this node.
3659 while (LoopData.L &&
3660 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
3661 auto Schedule = LoopData.Schedule;
3662 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00003663
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003664 LoopStack.pop_back();
3665 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00003666
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003667 if (Schedule) {
3668 auto *Domain = isl_schedule_get_domain(Schedule);
3669 auto *MUPA = mapToDimension(Domain, LoopStack.size());
3670 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
3671 NextLoopData.Schedule =
3672 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003673 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003674
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003675 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
3676 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00003677 }
Tobias Grosser75805372011-04-29 06:27:02 +00003678}
3679
Johannes Doerfert7c494212014-10-31 23:13:39 +00003680ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003681 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003682 if (StmtMapIt == StmtMap.end())
3683 return nullptr;
3684 return StmtMapIt->second;
3685}
3686
Michael Krusea902ba62015-12-13 19:21:45 +00003687ScopStmt *Scop::getStmtForRegionNode(RegionNode *RN) const {
3688 return getStmtForBasicBlock(getRegionNodeBasicBlock(RN));
3689}
3690
Johannes Doerfert96425c22015-08-30 21:13:53 +00003691int Scop::getRelativeLoopDepth(const Loop *L) const {
3692 Loop *OuterLoop =
3693 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3694 if (!OuterLoop)
3695 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003696 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3697}
3698
Michael Krused868b5d2015-09-10 15:25:24 +00003699void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003700 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003701
3702 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3703 // true, are not modeled as ordinary PHI nodes as they are not part of the
3704 // region. However, we model the operands in the predecessor blocks that are
3705 // part of the region as regular scalar accesses.
3706
3707 // If we can synthesize a PHI we can skip it, however only if it is in
3708 // the region. If it is not it can only be in the exit block of the region.
3709 // In this case we model the operands but not the PHI itself.
3710 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3711 return;
3712
3713 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3714 // detection. Hence, the PHI is a load of a new memory location in which the
3715 // incoming value was written at the end of the incoming basic block.
3716 bool OnlyNonAffineSubRegionOperands = true;
3717 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3718 Value *Op = PHI->getIncomingValue(u);
3719 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3720
3721 // Do not build scalar dependences inside a non-affine subregion.
3722 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3723 continue;
3724
3725 OnlyNonAffineSubRegionOperands = false;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00003726 ensurePHIWrite(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003727 }
3728
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003729 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3730 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003731 }
3732}
3733
Michael Kruse2e02d562016-02-06 09:19:40 +00003734void ScopInfo::buildScalarDependences(Instruction *Inst) {
3735 assert(!isa<PHINode>(Inst));
Michael Kruse7bf39442015-09-10 12:46:52 +00003736
Michael Kruse2e02d562016-02-06 09:19:40 +00003737 // Pull-in required operands.
3738 for (Use &Op : Inst->operands())
3739 ensureValueRead(Op.get(), Inst->getParent());
3740}
Michael Kruse7bf39442015-09-10 12:46:52 +00003741
Michael Kruse2e02d562016-02-06 09:19:40 +00003742void ScopInfo::buildEscapingDependences(Instruction *Inst) {
3743 Region *R = &scop->getRegion();
Michael Kruse7bf39442015-09-10 12:46:52 +00003744
Michael Kruse2e02d562016-02-06 09:19:40 +00003745 // Check for uses of this instruction outside the scop. Because we do not
3746 // iterate over such instructions and therefore did not "ensure" the existence
3747 // of a write, we must determine such use here.
3748 for (Use &U : Inst->uses()) {
3749 Instruction *UI = dyn_cast<Instruction>(U.getUser());
3750 if (!UI)
Michael Kruse7bf39442015-09-10 12:46:52 +00003751 continue;
3752
Michael Kruse2e02d562016-02-06 09:19:40 +00003753 BasicBlock *UseParent = getUseBlock(U);
3754 BasicBlock *UserParent = UI->getParent();
Michael Kruse7bf39442015-09-10 12:46:52 +00003755
Michael Kruse2e02d562016-02-06 09:19:40 +00003756 // An escaping value is either used by an instruction not within the scop,
3757 // or (when the scop region's exit needs to be simplified) by a PHI in the
3758 // scop's exit block. This is because region simplification before code
3759 // generation inserts new basic blocks before the PHI such that its incoming
3760 // blocks are not in the scop anymore.
3761 if (!R->contains(UseParent) ||
3762 (isa<PHINode>(UI) && UserParent == R->getExit() &&
3763 R->getExitingBlock())) {
3764 // At least one escaping use found.
3765 ensureValueWrite(Inst);
3766 break;
Michael Kruse7bf39442015-09-10 12:46:52 +00003767 }
3768 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003769}
3770
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003771bool ScopInfo::buildAccessMultiDimFixed(
Michael Kruse70131d32016-01-27 17:09:17 +00003772 MemAccInst Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003773 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3774 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse70131d32016-01-27 17:09:17 +00003775 Value *Val = Inst.getValueOperand();
3776 Type *SizeType = Val->getType();
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003777 unsigned ElementSize = DL->getTypeAllocSize(SizeType);
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003778 Value *Address = Inst.getPointerOperand();
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003779 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003780 const SCEVUnknown *BasePointer =
3781 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003782 enum MemoryAccess::AccessType Type =
3783 Inst.isLoad() ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003784
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003785 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3786 auto NewAddress = Address;
3787 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3788 auto Src = BitCast->getOperand(0);
3789 auto SrcTy = Src->getType();
3790 auto DstTy = BitCast->getType();
3791 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3792 NewAddress = Src;
3793 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003794
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003795 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3796 std::vector<const SCEV *> Subscripts;
3797 std::vector<int> Sizes;
3798 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3799 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003800
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003801 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003802
Johannes Doerfert09e36972015-10-07 20:17:36 +00003803 for (auto Subscript : Subscripts) {
3804 InvariantLoadsSetTy AccessILS;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003805 if (!isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS))
3806 return false;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003807
3808 for (LoadInst *LInst : AccessILS)
3809 if (!ScopRIL.count(LInst))
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003810 return false;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003811 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003812
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003813 if (Sizes.size() > 0) {
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003814 for (auto V : Sizes)
3815 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3816 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003817
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003818 addArrayAccess(Inst, Type, BasePointer->getValue(), ElementSize, true,
Tobias Grossera535dff2015-12-13 19:59:01 +00003819 Subscripts, SizesSCEV, Val);
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003820 return true;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003821 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003822 }
3823 }
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003824 return false;
3825}
3826
3827bool ScopInfo::buildAccessMultiDimParam(
3828 MemAccInst Inst, Loop *L, Region *R,
3829 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
Hongbin Zheng22623202016-02-15 00:20:58 +00003830 const InvariantLoadsSetTy &ScopRIL, const MapInsnToMemAcc &InsnToMemAcc) {
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003831 Value *Address = Inst.getPointerOperand();
3832 Value *Val = Inst.getValueOperand();
3833 Type *SizeType = Val->getType();
3834 unsigned ElementSize = DL->getTypeAllocSize(SizeType);
3835 enum MemoryAccess::AccessType Type =
3836 Inst.isLoad() ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
3837
3838 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
3839 const SCEVUnknown *BasePointer =
3840 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3841
3842 assert(BasePointer && "Could not find base pointer");
3843 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003844
Michael Kruse7bf39442015-09-10 12:46:52 +00003845 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003846 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003847 std::vector<const SCEV *> Sizes(
3848 AccItr->second.Shape->DelinearizedSizes.begin(),
3849 AccItr->second.Shape->DelinearizedSizes.end());
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003850 // Remove the element size. This information is already provided by the
Tobias Grosserd840fc72016-02-04 13:18:42 +00003851 // ElementSize parameter. In case the element size of this access and the
3852 // element size used for delinearization differs the delinearization is
3853 // incorrect. Hence, we invalidate the scop.
3854 //
3855 // TODO: Handle delinearization with differing element sizes.
3856 auto DelinearizedSize =
3857 cast<SCEVConstant>(Sizes.back())->getAPInt().getSExtValue();
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003858 Sizes.pop_back();
Tobias Grosserd840fc72016-02-04 13:18:42 +00003859 if (ElementSize != DelinearizedSize)
3860 scop->invalidate(DELINEARIZATION, Inst.getDebugLoc());
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003861
3862 addArrayAccess(Inst, Type, BasePointer->getValue(), ElementSize, true,
3863 AccItr->second.DelinearizedSubscripts, Sizes, Val);
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003864 return true;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003865 }
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003866 return false;
3867}
3868
3869void ScopInfo::buildAccessSingleDim(
3870 MemAccInst Inst, Loop *L, Region *R,
3871 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3872 const InvariantLoadsSetTy &ScopRIL) {
3873 Value *Address = Inst.getPointerOperand();
3874 Value *Val = Inst.getValueOperand();
3875 Type *SizeType = Val->getType();
3876 unsigned ElementSize = DL->getTypeAllocSize(SizeType);
3877 enum MemoryAccess::AccessType Type =
3878 Inst.isLoad() ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
3879
3880 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
3881 const SCEVUnknown *BasePointer =
3882 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3883
3884 assert(BasePointer && "Could not find base pointer");
3885 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
Michael Kruse7bf39442015-09-10 12:46:52 +00003886
3887 // Check if the access depends on a loop contained in a non-affine subregion.
3888 bool isVariantInNonAffineLoop = false;
3889 if (BoxedLoops) {
3890 SetVector<const Loop *> Loops;
3891 findLoops(AccessFunction, Loops);
3892 for (const Loop *L : Loops)
3893 if (BoxedLoops->count(L))
3894 isVariantInNonAffineLoop = true;
3895 }
3896
Johannes Doerfert09e36972015-10-07 20:17:36 +00003897 InvariantLoadsSetTy AccessILS;
3898 bool IsAffine =
3899 !isVariantInNonAffineLoop &&
3900 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3901
3902 for (LoadInst *LInst : AccessILS)
3903 if (!ScopRIL.count(LInst))
3904 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003905
Michael Krusee2bccbb2015-09-18 19:59:43 +00003906 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3907 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003908
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003909 addArrayAccess(Inst, Type, BasePointer->getValue(), ElementSize, IsAffine,
3910 {AccessFunction}, {}, Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003911}
3912
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003913void ScopInfo::buildMemoryAccess(
3914 MemAccInst Inst, Loop *L, Region *R,
3915 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
Hongbin Zheng22623202016-02-15 00:20:58 +00003916 const InvariantLoadsSetTy &ScopRIL, const MapInsnToMemAcc &InsnToMemAcc) {
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003917
3918 if (buildAccessMultiDimFixed(Inst, L, R, BoxedLoops, ScopRIL))
3919 return;
3920
Hongbin Zheng22623202016-02-15 00:20:58 +00003921 if (buildAccessMultiDimParam(Inst, L, R, BoxedLoops, ScopRIL, InsnToMemAcc))
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003922 return;
3923
3924 buildAccessSingleDim(Inst, L, R, BoxedLoops, ScopRIL);
3925}
3926
Hongbin Zheng22623202016-02-15 00:20:58 +00003927void ScopInfo::buildAccessFunctions(Region &R, Region &SR,
3928 const MapInsnToMemAcc &InsnToMemAcc) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003929
3930 if (SD->isNonAffineSubRegion(&SR, &R)) {
3931 for (BasicBlock *BB : SR.blocks())
Hongbin Zheng22623202016-02-15 00:20:58 +00003932 buildAccessFunctions(R, *BB, InsnToMemAcc, &SR);
Michael Kruse7bf39442015-09-10 12:46:52 +00003933 return;
3934 }
3935
3936 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3937 if (I->isSubRegion())
Hongbin Zheng22623202016-02-15 00:20:58 +00003938 buildAccessFunctions(R, *I->getNodeAs<Region>(), InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00003939 else
Hongbin Zheng22623202016-02-15 00:20:58 +00003940 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>(), InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00003941}
3942
Johannes Doerferta8781032016-02-02 14:14:40 +00003943void ScopInfo::buildStmts(Region &R, Region &SR) {
Michael Krusecac948e2015-10-02 13:53:07 +00003944
Johannes Doerferta8781032016-02-02 14:14:40 +00003945 if (SD->isNonAffineSubRegion(&SR, &R)) {
Michael Krusecac948e2015-10-02 13:53:07 +00003946 scop->addScopStmt(nullptr, &SR);
3947 return;
3948 }
3949
3950 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3951 if (I->isSubRegion())
Johannes Doerferta8781032016-02-02 14:14:40 +00003952 buildStmts(R, *I->getNodeAs<Region>());
Michael Krusecac948e2015-10-02 13:53:07 +00003953 else
3954 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
3955}
3956
Michael Krused868b5d2015-09-10 15:25:24 +00003957void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
Hongbin Zheng22623202016-02-15 00:20:58 +00003958 const MapInsnToMemAcc &InsnToMemAcc,
Michael Krused868b5d2015-09-10 15:25:24 +00003959 Region *NonAffineSubRegion,
3960 bool IsExitBlock) {
Tobias Grosser910cf262015-11-11 20:15:49 +00003961 // We do not build access functions for error blocks, as they may contain
3962 // instructions we can not model.
Johannes Doerfertc36d39b2016-02-02 14:14:20 +00003963 if (isErrorBlock(BB, R, *LI, *DT) && !IsExitBlock)
Tobias Grosser910cf262015-11-11 20:15:49 +00003964 return;
3965
Michael Kruse7bf39442015-09-10 12:46:52 +00003966 Loop *L = LI->getLoopFor(&BB);
3967
3968 // The set of loops contained in non-affine subregions that are part of R.
3969 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3970
Johannes Doerfert09e36972015-10-07 20:17:36 +00003971 // The set of loads that are required to be invariant.
3972 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
3973
Michael Kruse2e02d562016-02-06 09:19:40 +00003974 for (Instruction &Inst : BB) {
3975 PHINode *PHI = dyn_cast<PHINode>(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003976 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003977 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003978
3979 // For the exit block we stop modeling after the last PHI node.
3980 if (!PHI && IsExitBlock)
3981 break;
3982
Johannes Doerfert09e36972015-10-07 20:17:36 +00003983 // TODO: At this point we only know that elements of ScopRIL have to be
3984 // invariant and will be hoisted for the SCoP to be processed. Though,
3985 // there might be other invariant accesses that will be hoisted and
3986 // that would allow to make a non-affine access affine.
Michael Kruse70131d32016-01-27 17:09:17 +00003987 if (auto MemInst = MemAccInst::dyn_cast(Inst))
Hongbin Zheng22623202016-02-15 00:20:58 +00003988 buildMemoryAccess(MemInst, L, &R, BoxedLoops, ScopRIL, InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00003989
Michael Kruse2e02d562016-02-06 09:19:40 +00003990 if (isIgnoredIntrinsic(&Inst))
Michael Kruse7bf39442015-09-10 12:46:52 +00003991 continue;
3992
Michael Kruse2e02d562016-02-06 09:19:40 +00003993 if (!PHI)
3994 buildScalarDependences(&Inst);
3995 if (!IsExitBlock)
3996 buildEscapingDependences(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003997 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003998}
Michael Kruse7bf39442015-09-10 12:46:52 +00003999
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004000MemoryAccess *ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
4001 MemoryAccess::AccessType Type,
4002 Value *BaseAddress, unsigned ElemBytes,
4003 bool Affine, Value *AccessValue,
4004 ArrayRef<const SCEV *> Subscripts,
4005 ArrayRef<const SCEV *> Sizes,
4006 ScopArrayInfo::MemoryKind Kind) {
Michael Krusecac948e2015-10-02 13:53:07 +00004007 ScopStmt *Stmt = scop->getStmtForBasicBlock(BB);
4008
4009 // Do not create a memory access for anything not in the SCoP. It would be
4010 // ignored anyway.
4011 if (!Stmt)
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004012 return nullptr;
Michael Krusecac948e2015-10-02 13:53:07 +00004013
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00004014 AccFuncSetType &AccList = scop->getOrCreateAccessFunctions(BB);
Michael Krusee2bccbb2015-09-18 19:59:43 +00004015 Value *BaseAddr = BaseAddress;
4016 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
4017
Tobias Grosserf4f68702015-12-14 15:05:37 +00004018 bool isKnownMustAccess = false;
4019
4020 // Accesses in single-basic block statements are always excuted.
4021 if (Stmt->isBlockStmt())
4022 isKnownMustAccess = true;
4023
4024 if (Stmt->isRegionStmt()) {
4025 // Accesses that dominate the exit block of a non-affine region are always
4026 // executed. In non-affine regions there may exist MK_Values that do not
4027 // dominate the exit. MK_Values will always dominate the exit and MK_PHIs
4028 // only if there is at most one PHI_WRITE in the non-affine region.
4029 if (DT->dominates(BB, Stmt->getRegion()->getExit()))
4030 isKnownMustAccess = true;
4031 }
4032
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004033 // Non-affine PHI writes do not "happen" at a particular instruction, but
4034 // after exiting the statement. Therefore they are guaranteed execute and
4035 // overwrite the old value.
4036 if (Kind == ScopArrayInfo::MK_PHI || Kind == ScopArrayInfo::MK_ExitPHI)
4037 isKnownMustAccess = true;
4038
Tobias Grosserf4f68702015-12-14 15:05:37 +00004039 if (!isKnownMustAccess && Type == MemoryAccess::MUST_WRITE)
Michael Krusecac948e2015-10-02 13:53:07 +00004040 Type = MemoryAccess::MAY_WRITE;
4041
Tobias Grosserf1bfd752015-11-05 20:15:37 +00004042 AccList.emplace_back(Stmt, Inst, Type, BaseAddress, ElemBytes, Affine,
Tobias Grossera535dff2015-12-13 19:59:01 +00004043 Subscripts, Sizes, AccessValue, Kind, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00004044 Stmt->addAccess(&AccList.back());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004045 return &AccList.back();
Michael Kruse7bf39442015-09-10 12:46:52 +00004046}
4047
Michael Kruse70131d32016-01-27 17:09:17 +00004048void ScopInfo::addArrayAccess(MemAccInst MemAccInst,
Tobias Grossera535dff2015-12-13 19:59:01 +00004049 MemoryAccess::AccessType Type, Value *BaseAddress,
4050 unsigned ElemBytes, bool IsAffine,
4051 ArrayRef<const SCEV *> Subscripts,
4052 ArrayRef<const SCEV *> Sizes,
4053 Value *AccessValue) {
Michael Kruse70131d32016-01-27 17:09:17 +00004054 assert(MemAccInst.isLoad() == (Type == MemoryAccess::READ));
4055 addMemoryAccess(MemAccInst.getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00004056 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00004057 ScopArrayInfo::MK_Array);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004058}
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004059void ScopInfo::ensureValueWrite(Instruction *Inst) {
4060 ScopStmt *Stmt = scop->getStmtForBasicBlock(Inst->getParent());
Michael Kruse436db622016-01-26 13:33:10 +00004061
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004062 // Inst not defined within this SCoP.
Michael Kruse436db622016-01-26 13:33:10 +00004063 if (!Stmt)
4064 return;
4065
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004066 // Do not process further if the instruction is already written.
4067 if (Stmt->lookupValueWriteOf(Inst))
Michael Kruse436db622016-01-26 13:33:10 +00004068 return;
4069
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004070 addMemoryAccess(Inst->getParent(), Inst, MemoryAccess::MUST_WRITE, Inst, 1,
4071 true, Inst, ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004072 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004073}
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004074void ScopInfo::ensureValueRead(Value *V, BasicBlock *UserBB) {
Michael Krusefd463082016-01-27 22:51:56 +00004075
Michael Kruse2e02d562016-02-06 09:19:40 +00004076 // There cannot be an "access" for literal constants. BasicBlock references
4077 // (jump destinations) also never change.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004078 if ((isa<Constant>(V) && !isa<GlobalVariable>(V)) || isa<BasicBlock>(V))
Michael Kruse2e02d562016-02-06 09:19:40 +00004079 return;
4080
Michael Krusefd463082016-01-27 22:51:56 +00004081 // If the instruction can be synthesized and the user is in the region we do
4082 // not need to add a value dependences.
4083 Region &ScopRegion = scop->getRegion();
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004084 if (canSynthesize(V, LI, SE, &ScopRegion))
Michael Krusefd463082016-01-27 22:51:56 +00004085 return;
4086
Michael Kruse2e02d562016-02-06 09:19:40 +00004087 // Do not build scalar dependences for required invariant loads as we will
4088 // hoist them later on anyway or drop the SCoP if we cannot.
4089 auto ScopRIL = SD->getRequiredInvariantLoads(&ScopRegion);
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004090 if (ScopRIL->count(dyn_cast<LoadInst>(V)))
Michael Kruse2e02d562016-02-06 09:19:40 +00004091 return;
4092
4093 // Determine the ScopStmt containing the value's definition and use. There is
4094 // no defining ScopStmt if the value is a function argument, a global value,
4095 // or defined outside the SCoP.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004096 Instruction *ValueInst = dyn_cast<Instruction>(V);
Michael Kruse2e02d562016-02-06 09:19:40 +00004097 ScopStmt *ValueStmt =
4098 ValueInst ? scop->getStmtForBasicBlock(ValueInst->getParent()) : nullptr;
4099
Michael Krusead28e5a2016-01-26 13:33:15 +00004100 ScopStmt *UserStmt = scop->getStmtForBasicBlock(UserBB);
4101
4102 // We do not model uses outside the scop.
4103 if (!UserStmt)
4104 return;
4105
Michael Kruse2e02d562016-02-06 09:19:40 +00004106 // Add MemoryAccess for invariant values only if requested.
4107 if (!ModelReadOnlyScalars && !ValueStmt)
4108 return;
4109
4110 // Ignore use-def chains within the same ScopStmt.
4111 if (ValueStmt == UserStmt)
4112 return;
4113
Michael Krusead28e5a2016-01-26 13:33:15 +00004114 // Do not create another MemoryAccess for reloading the value if one already
4115 // exists.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004116 if (UserStmt->lookupValueReadOf(V))
Michael Krusead28e5a2016-01-26 13:33:15 +00004117 return;
4118
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004119 addMemoryAccess(UserBB, nullptr, MemoryAccess::READ, V, 1, true, V,
Michael Kruse8d0b7342015-09-25 21:21:00 +00004120 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004121 ScopArrayInfo::MK_Value);
Michael Kruse2e02d562016-02-06 09:19:40 +00004122 if (ValueInst)
4123 ensureValueWrite(ValueInst);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004124}
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004125void ScopInfo::ensurePHIWrite(PHINode *PHI, BasicBlock *IncomingBlock,
4126 Value *IncomingValue, bool IsExitBlock) {
4127 ScopStmt *IncomingStmt = scop->getStmtForBasicBlock(IncomingBlock);
Michael Kruse2e02d562016-02-06 09:19:40 +00004128 if (!IncomingStmt)
4129 return;
4130
4131 // Take care for the incoming value being available in the incoming block.
4132 // This must be done before the check for multiple PHI writes because multiple
4133 // exiting edges from subregion each can be the effective written value of the
4134 // subregion. As such, all of them must be made available in the subregion
4135 // statement.
4136 ensureValueRead(IncomingValue, IncomingBlock);
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004137
4138 // Do not add more than one MemoryAccess per PHINode and ScopStmt.
4139 if (MemoryAccess *Acc = IncomingStmt->lookupPHIWriteOf(PHI)) {
4140 assert(Acc->getAccessInstruction() == PHI);
4141 Acc->addIncoming(IncomingBlock, IncomingValue);
4142 return;
4143 }
4144
4145 MemoryAccess *Acc = addMemoryAccess(
4146 IncomingStmt->isBlockStmt() ? IncomingBlock
4147 : IncomingStmt->getRegion()->getEntry(),
4148 PHI, MemoryAccess::MUST_WRITE, PHI, 1, true, PHI,
4149 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
4150 IsExitBlock ? ScopArrayInfo::MK_ExitPHI : ScopArrayInfo::MK_PHI);
4151 assert(Acc);
4152 Acc->addIncoming(IncomingBlock, IncomingValue);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004153}
4154void ScopInfo::addPHIReadAccess(PHINode *PHI) {
4155 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00004156 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004157 ScopArrayInfo::MK_PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004158}
4159
Michael Krusedaf66942015-12-13 22:10:37 +00004160void ScopInfo::buildScop(Region &R, AssumptionCache &AC) {
Michael Kruse9d080092015-09-11 21:41:48 +00004161 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004162 scop.reset(new Scop(R, *SE, MaxLoopDepth));
Michael Kruse7bf39442015-09-10 12:46:52 +00004163
Johannes Doerferta8781032016-02-02 14:14:40 +00004164 buildStmts(R, R);
Hongbin Zheng22623202016-02-15 00:20:58 +00004165 buildAccessFunctions(R, R, *SD->getInsnToMemAccMap(&R));
Michael Kruse7bf39442015-09-10 12:46:52 +00004166
4167 // In case the region does not have an exiting block we will later (during
4168 // code generation) split the exit block. This will move potential PHI nodes
4169 // from the current exit block into the new region exiting block. Hence, PHI
4170 // nodes that are at this point not part of the region will be.
4171 // To handle these PHI nodes later we will now model their operands as scalar
4172 // accesses. Note that we do not model anything in the exit block if we have
4173 // an exiting block in the region, as there will not be any splitting later.
4174 if (!R.getExitingBlock())
Hongbin Zheng22623202016-02-15 00:20:58 +00004175 buildAccessFunctions(R, *R.getExit(), *SD->getInsnToMemAccMap(&R), nullptr,
4176 /* IsExitBlock */ true);
Michael Kruse7bf39442015-09-10 12:46:52 +00004177
Hongbin Zheng192f69a2016-02-13 15:12:54 +00004178 scop->init(*AA, AC, *SD, *DT, *LI);
Michael Kruse7bf39442015-09-10 12:46:52 +00004179}
4180
Michael Krused868b5d2015-09-10 15:25:24 +00004181void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00004182 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00004183 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00004184 return;
4185 }
4186
Michael Kruse9d080092015-09-11 21:41:48 +00004187 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00004188}
4189
Hongbin Zhengfec32802016-02-13 15:13:02 +00004190void ScopInfo::clear() { scop.reset(); }
Michael Kruse7bf39442015-09-10 12:46:52 +00004191
4192//===----------------------------------------------------------------------===//
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004193ScopInfo::ScopInfo() : RegionPass(ID) {}
Tobias Grosserb76f38532011-08-20 11:11:25 +00004194
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004195ScopInfo::~ScopInfo() { clear(); }
Tobias Grosserb76f38532011-08-20 11:11:25 +00004196
Tobias Grosser75805372011-04-29 06:27:02 +00004197void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00004198 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00004199 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00004200 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00004201 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4202 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004203 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004204 AU.addRequired<AssumptionCacheTracker>();
Tobias Grosser75805372011-04-29 06:27:02 +00004205 AU.setPreservesAll();
4206}
4207
4208bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00004209 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00004210
Michael Krused868b5d2015-09-10 15:25:24 +00004211 if (!SD->isMaxRegionInScop(*R))
4212 return false;
4213
4214 Function *F = R->getEntry()->getParent();
4215 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4216 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4217 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Johannes Doerferta1f291e2016-02-02 14:15:13 +00004218 DL = &F->getParent()->getDataLayout();
Michael Krusedaf66942015-12-13 22:10:37 +00004219 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004220 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krused868b5d2015-09-10 15:25:24 +00004221
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004222 DebugLoc Beg, End;
4223 getDebugLocations(R, Beg, End);
4224 std::string Msg = "SCoP begins here.";
4225 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg);
4226
Michael Krusedaf66942015-12-13 22:10:37 +00004227 buildScop(*R, AC);
Tobias Grosser75805372011-04-29 06:27:02 +00004228
Tobias Grosserd6a50b32015-05-30 06:26:21 +00004229 DEBUG(scop->print(dbgs()));
4230
Michael Kruseafe06702015-10-02 16:33:27 +00004231 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004232 Msg = "SCoP ends here but was dismissed.";
Hongbin Zhengfec32802016-02-13 15:13:02 +00004233 scop.reset();
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004234 } else {
4235 Msg = "SCoP ends here.";
4236 ++ScopFound;
4237 if (scop->getMaxLoopDepth() > 0)
4238 ++RichScopFound;
Johannes Doerfert43788c52015-08-20 05:58:56 +00004239 }
4240
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004241 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg);
4242
Tobias Grosser75805372011-04-29 06:27:02 +00004243 return false;
4244}
4245
4246char ScopInfo::ID = 0;
4247
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004248Pass *polly::createScopInfoPass() { return new ScopInfo(); }
4249
Tobias Grosser73600b82011-10-08 00:30:40 +00004250INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
4251 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004252 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004253INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004254INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004255INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004256INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004257INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004258INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004259INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00004260INITIALIZE_PASS_END(ScopInfo, "polly-scops",
4261 "Polly - Create polyhedral description of Scops", false,
4262 false)