blob: 145258623368635cec06a760a789ecc28983fc26 [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) {
778
779 std::string IdName = "__polly_array_ref";
780 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
781}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000782
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000783void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000784 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000785 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000786}
787
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000788const std::string MemoryAccess::getReductionOperatorStr() const {
789 return MemoryAccess::getReductionOperatorStr(getReductionType());
790}
791
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000792__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
793
Johannes Doerfertf6183392014-07-01 20:52:51 +0000794raw_ostream &polly::operator<<(raw_ostream &OS,
795 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000796 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000797 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000798 else
799 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000800 return OS;
801}
802
Tobias Grosser75805372011-04-29 06:27:02 +0000803void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000804 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000805 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000806 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000807 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000808 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000809 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000810 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000811 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000812 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000813 break;
814 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000815 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000816 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000817 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000818 if (hasNewAccessRelation())
819 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000820}
821
Tobias Grosser74394f02013-01-14 22:40:23 +0000822void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000823
824// Create a map in the size of the provided set domain, that maps from the
825// one element of the provided set domain to another element of the provided
826// set domain.
827// The mapping is limited to all points that are equal in all but the last
828// dimension and for which the last dimension of the input is strict smaller
829// than the last dimension of the output.
830//
831// getEqualAndLarger(set[i0, i1, ..., iX]):
832//
833// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
834// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
835//
Tobias Grosserf5338802011-10-06 00:03:35 +0000836static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000837 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000838 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000839 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000840
841 // Set all but the last dimension to be equal for the input and output
842 //
843 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
844 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000845 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000846 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000847
848 // Set the last dimension of the input to be strict smaller than the
849 // last dimension of the output.
850 //
851 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000852 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
853 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000854 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000855}
856
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000857__isl_give isl_set *
858MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000859 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000860 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000861 isl_space *Space = isl_space_range(isl_map_get_space(S));
862 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000863
Sebastian Popa00a0292012-12-18 07:46:06 +0000864 S = isl_map_reverse(S);
865 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000866
Sebastian Popa00a0292012-12-18 07:46:06 +0000867 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
868 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
869 NextScatt = isl_map_apply_domain(NextScatt, S);
870 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000871
Sebastian Popa00a0292012-12-18 07:46:06 +0000872 isl_set *Deltas = isl_map_deltas(NextScatt);
873 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000874}
875
Sebastian Popa00a0292012-12-18 07:46:06 +0000876bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000877 int StrideWidth) const {
878 isl_set *Stride, *StrideX;
879 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000880
Sebastian Popa00a0292012-12-18 07:46:06 +0000881 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000882 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000883 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
884 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
885 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
886 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000887 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000888
Tobias Grosser28dd4862012-01-24 16:42:16 +0000889 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000890 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000891
Tobias Grosser28dd4862012-01-24 16:42:16 +0000892 return IsStrideX;
893}
894
Sebastian Popa00a0292012-12-18 07:46:06 +0000895bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
896 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000897}
898
Sebastian Popa00a0292012-12-18 07:46:06 +0000899bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
900 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000901}
902
Tobias Grosser166c4222015-09-05 07:46:40 +0000903void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
904 isl_map_free(NewAccessRelation);
905 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000906}
Tobias Grosser75805372011-04-29 06:27:02 +0000907
908//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000909
Tobias Grosser808cd692015-07-14 09:33:13 +0000910isl_map *ScopStmt::getSchedule() const {
911 isl_set *Domain = getDomain();
912 if (isl_set_is_empty(Domain)) {
913 isl_set_free(Domain);
914 return isl_map_from_aff(
915 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
916 }
917 auto *Schedule = getParent()->getSchedule();
918 Schedule = isl_union_map_intersect_domain(
919 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
920 if (isl_union_map_is_empty(Schedule)) {
921 isl_set_free(Domain);
922 isl_union_map_free(Schedule);
923 return isl_map_from_aff(
924 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
925 }
926 auto *M = isl_map_from_union_map(Schedule);
927 M = isl_map_coalesce(M);
928 M = isl_map_gist_domain(M, Domain);
929 M = isl_map_coalesce(M);
930 return M;
931}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000932
Johannes Doerfert574182d2015-08-12 10:19:50 +0000933__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000934 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
935 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000936}
937
Tobias Grosser37eb4222014-02-20 21:43:54 +0000938void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
939 assert(isl_set_is_subset(NewDomain, Domain) &&
940 "New domain is not a subset of old domain!");
941 isl_set_free(Domain);
942 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000943}
944
Michael Krusecac948e2015-10-02 13:53:07 +0000945void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000946 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +0000947 for (MemoryAccess *Access : MemAccs) {
948 Type *ElementType = Access->getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000949
Tobias Grossera535dff2015-12-13 19:59:01 +0000950 ScopArrayInfo::MemoryKind Ty;
951 if (Access->isPHIKind())
952 Ty = ScopArrayInfo::MK_PHI;
953 else if (Access->isExitPHIKind())
954 Ty = ScopArrayInfo::MK_ExitPHI;
955 else if (Access->isValueKind())
956 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000957 else
Tobias Grossera535dff2015-12-13 19:59:01 +0000958 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000959
Johannes Doerfertadeab372016-02-07 13:57:32 +0000960 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
961 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +0000962 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +0000963 }
964}
965
Michael Krusecac948e2015-10-02 13:53:07 +0000966void ScopStmt::addAccess(MemoryAccess *Access) {
967 Instruction *AccessInst = Access->getAccessInstruction();
968
Michael Kruse58fa3bb2015-12-22 23:25:11 +0000969 if (Access->isArrayKind()) {
970 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
971 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +0000972 } else if (Access->isValueKind() && Access->isWrite()) {
973 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
974 assert(Parent.getStmtForBasicBlock(AccessVal->getParent()) == this);
975 assert(!ValueWrites.lookup(AccessVal));
976
977 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +0000978 } else if (Access->isValueKind() && Access->isRead()) {
979 Value *AccessVal = Access->getAccessValue();
980 assert(!ValueReads.lookup(AccessVal));
981
982 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +0000983 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
984 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
985 assert(!PHIWrites.lookup(PHI));
986
987 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +0000988 }
989
990 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +0000991}
992
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000993void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000994 for (MemoryAccess *MA : *this)
995 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000996
997 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000998}
999
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001000/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
1001static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1002 void *User) {
1003 isl_set **BoundedParts = static_cast<isl_set **>(User);
1004 if (isl_basic_set_is_bounded(BSet))
1005 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1006 else
1007 isl_basic_set_free(BSet);
1008 return isl_stat_ok;
1009}
1010
1011/// @brief Return the bounded parts of @p S.
1012static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1013 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1014 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1015 isl_set_free(S);
1016 return BoundedParts;
1017}
1018
1019/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
1020///
1021/// @returns A separation of @p S into first an unbounded then a bounded subset,
1022/// both with regards to the dimension @p Dim.
1023static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1024partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1025
1026 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001027 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001028
1029 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001030 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001031
1032 // Remove dimensions that are greater than Dim as they are not interesting.
1033 assert(NumDimsS >= Dim + 1);
1034 OnlyDimS =
1035 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1036
1037 // Create artificial parametric upper bounds for dimensions smaller than Dim
1038 // as we are not interested in them.
1039 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1040 for (unsigned u = 0; u < Dim; u++) {
1041 isl_constraint *C = isl_inequality_alloc(
1042 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1043 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1044 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1045 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1046 }
1047
1048 // Collect all bounded parts of OnlyDimS.
1049 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1050
1051 // Create the dimensions greater than Dim again.
1052 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1053 NumDimsS - Dim - 1);
1054
1055 // Remove the artificial upper bound parameters again.
1056 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1057
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001058 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001059 return std::make_pair(UnboundedParts, BoundedParts);
1060}
1061
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001062/// @brief Set the dimension Ids from @p From in @p To.
1063static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1064 __isl_take isl_set *To) {
1065 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1066 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1067 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1068 }
1069 return To;
1070}
1071
1072/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001073static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001074 __isl_take isl_pw_aff *L,
1075 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001076 switch (Pred) {
1077 case ICmpInst::ICMP_EQ:
1078 return isl_pw_aff_eq_set(L, R);
1079 case ICmpInst::ICMP_NE:
1080 return isl_pw_aff_ne_set(L, R);
1081 case ICmpInst::ICMP_SLT:
1082 return isl_pw_aff_lt_set(L, R);
1083 case ICmpInst::ICMP_SLE:
1084 return isl_pw_aff_le_set(L, R);
1085 case ICmpInst::ICMP_SGT:
1086 return isl_pw_aff_gt_set(L, R);
1087 case ICmpInst::ICMP_SGE:
1088 return isl_pw_aff_ge_set(L, R);
1089 case ICmpInst::ICMP_ULT:
1090 return isl_pw_aff_lt_set(L, R);
1091 case ICmpInst::ICMP_UGT:
1092 return isl_pw_aff_gt_set(L, R);
1093 case ICmpInst::ICMP_ULE:
1094 return isl_pw_aff_le_set(L, R);
1095 case ICmpInst::ICMP_UGE:
1096 return isl_pw_aff_ge_set(L, R);
1097 default:
1098 llvm_unreachable("Non integer predicate not supported");
1099 }
1100}
1101
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001102/// @brief Create the conditions under which @p L @p Pred @p R is true.
1103///
1104/// Helper function that will make sure the dimensions of the result have the
1105/// same isl_id's as the @p Domain.
1106static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1107 __isl_take isl_pw_aff *L,
1108 __isl_take isl_pw_aff *R,
1109 __isl_keep isl_set *Domain) {
1110 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1111 return setDimensionIds(Domain, ConsequenceCondSet);
1112}
1113
1114/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001115///
1116/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001117/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1118/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001119static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001120buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001121 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1122
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001123 Value *Condition = getConditionFromTerminator(SI);
1124 assert(Condition && "No condition for switch");
1125
1126 ScalarEvolution &SE = *S.getSE();
1127 BasicBlock *BB = SI->getParent();
1128 isl_pw_aff *LHS, *RHS;
1129 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
1130
1131 unsigned NumSuccessors = SI->getNumSuccessors();
1132 ConditionSets.resize(NumSuccessors);
1133 for (auto &Case : SI->cases()) {
1134 unsigned Idx = Case.getSuccessorIndex();
1135 ConstantInt *CaseValue = Case.getCaseValue();
1136
1137 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
1138 isl_set *CaseConditionSet =
1139 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1140 ConditionSets[Idx] = isl_set_coalesce(
1141 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1142 }
1143
1144 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1145 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1146 for (unsigned u = 2; u < NumSuccessors; u++)
1147 ConditionSetUnion =
1148 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1149 ConditionSets[0] = setDimensionIds(
1150 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1151
1152 S.markAsOptimized();
1153 isl_pw_aff_free(LHS);
1154}
1155
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001156/// @brief Build the conditions sets for the branch condition @p Condition in
1157/// the @p Domain.
1158///
1159/// This will fill @p ConditionSets with the conditions under which control
1160/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001161/// have as many elements as @p TI has successors. If @p TI is nullptr the
1162/// context under which @p Condition is true/false will be returned as the
1163/// new elements of @p ConditionSets.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001164static void
1165buildConditionSets(Scop &S, Value *Condition, TerminatorInst *TI, Loop *L,
1166 __isl_keep isl_set *Domain,
1167 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1168
1169 isl_set *ConsequenceCondSet = nullptr;
1170 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1171 if (CCond->isZero())
1172 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1173 else
1174 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1175 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1176 auto Opcode = BinOp->getOpcode();
1177 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1178
1179 buildConditionSets(S, BinOp->getOperand(0), TI, L, Domain, ConditionSets);
1180 buildConditionSets(S, BinOp->getOperand(1), TI, L, Domain, ConditionSets);
1181
1182 isl_set_free(ConditionSets.pop_back_val());
1183 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1184 isl_set_free(ConditionSets.pop_back_val());
1185 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1186
1187 if (Opcode == Instruction::And)
1188 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1189 else
1190 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1191 } else {
1192 auto *ICond = dyn_cast<ICmpInst>(Condition);
1193 assert(ICond &&
1194 "Condition of exiting branch was neither constant nor ICmp!");
1195
1196 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001197 BasicBlock *BB = TI ? TI->getParent() : nullptr;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001198 isl_pw_aff *LHS, *RHS;
1199 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1200 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
1201 ConsequenceCondSet =
1202 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1203 }
1204
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001205 // If no terminator was given we are only looking for parameter constraints
1206 // under which @p Condition is true/false.
1207 if (!TI)
1208 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
1209
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001210 assert(ConsequenceCondSet);
1211 isl_set *AlternativeCondSet =
1212 isl_set_complement(isl_set_copy(ConsequenceCondSet));
1213
1214 ConditionSets.push_back(isl_set_coalesce(
1215 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
1216 ConditionSets.push_back(isl_set_coalesce(
1217 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
1218}
1219
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001220/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1221///
1222/// This will fill @p ConditionSets with the conditions under which control
1223/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1224/// have as many elements as @p TI has successors.
1225static void
1226buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1227 __isl_keep isl_set *Domain,
1228 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1229
1230 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1231 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1232
1233 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1234
1235 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001236 ConditionSets.push_back(isl_set_copy(Domain));
1237 return;
1238 }
1239
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001240 Value *Condition = getConditionFromTerminator(TI);
1241 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001242
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001243 return buildConditionSets(S, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001244}
1245
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001246void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +00001247 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +00001248
Tobias Grosser084d8f72012-05-29 09:29:44 +00001249 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1250
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001251 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001252 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001253}
1254
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001255void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP,
1256 ScopDetection &SD) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001257 isl_ctx *Ctx = Parent.getIslCtx();
1258 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1259 Type *Ty = GEP->getPointerOperandType();
1260 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001261
1262 // The set of loads that are required to be invariant.
1263 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001264
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001265 std::vector<const SCEV *> Subscripts;
1266 std::vector<int> Sizes;
1267
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001268 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001269
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001270 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001271 Ty = PtrTy->getElementType();
1272 }
1273
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001274 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001275
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001276 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001277
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001278 for (size_t i = 0; i < Sizes.size(); i++) {
1279 auto Expr = Subscripts[i + IndexOffset];
1280 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001281
Johannes Doerfert09e36972015-10-07 20:17:36 +00001282 InvariantLoadsSetTy AccessILS;
1283 if (!isAffineExpr(&Parent.getRegion(), Expr, SE, nullptr, &AccessILS))
1284 continue;
1285
1286 bool NonAffine = false;
1287 for (LoadInst *LInst : AccessILS)
1288 if (!ScopRIL.count(LInst))
1289 NonAffine = true;
1290
1291 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001292 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001293
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001294 isl_pw_aff *AccessOffset = getPwAff(Expr);
1295 AccessOffset =
1296 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001297
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001298 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1299 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001300
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001301 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1302 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1303 OutOfBound = isl_set_params(OutOfBound);
1304 isl_set *InBound = isl_set_complement(OutOfBound);
1305 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001306
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001307 // A => B == !A or B
1308 isl_set *InBoundIfExecuted =
1309 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001310
Roman Gareev10595a12016-01-08 14:01:59 +00001311 InBoundIfExecuted = isl_set_coalesce(InBoundIfExecuted);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001312 Parent.addAssumption(INBOUNDS, InBoundIfExecuted, GEP->getDebugLoc());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001313 }
1314
1315 isl_local_space_free(LSpace);
1316}
1317
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001318void ScopStmt::deriveAssumptions(BasicBlock *Block, ScopDetection &SD) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001319 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001320 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001321 deriveAssumptionsFromGEP(GEP, SD);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001322}
1323
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001324void ScopStmt::collectSurroundingLoops() {
1325 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1326 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1327 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1328 isl_id_free(DimId);
1329 }
1330}
1331
Michael Kruse9d080092015-09-11 21:41:48 +00001332ScopStmt::ScopStmt(Scop &parent, Region &R)
Michael Krusecac948e2015-10-02 13:53:07 +00001333 : Parent(parent), Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001334
Tobias Grosser16c44032015-07-09 07:31:45 +00001335 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001336}
1337
Michael Kruse9d080092015-09-11 21:41:48 +00001338ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Michael Krusecac948e2015-10-02 13:53:07 +00001339 : Parent(parent), Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001340
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001341 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001342}
1343
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001344void ScopStmt::init(ScopDetection &SD) {
Michael Krusecac948e2015-10-02 13:53:07 +00001345 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001346
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001347 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001348 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001349 buildAccessRelations();
1350
1351 if (BB) {
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001352 deriveAssumptions(BB, SD);
Michael Krusecac948e2015-10-02 13:53:07 +00001353 } else {
1354 for (BasicBlock *Block : R->blocks()) {
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001355 deriveAssumptions(Block, SD);
Michael Krusecac948e2015-10-02 13:53:07 +00001356 }
1357 }
1358
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001359 if (DetectReductions)
1360 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001361}
1362
Johannes Doerferte58a0122014-06-27 20:31:28 +00001363/// @brief Collect loads which might form a reduction chain with @p StoreMA
1364///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001365/// Check if the stored value for @p StoreMA is a binary operator with one or
1366/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001367/// used only once (by @p StoreMA) and its load operands are also used only
1368/// once, we have found a possible reduction chain. It starts at an operand
1369/// load and includes the binary operator and @p StoreMA.
1370///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001371/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001372/// escape this block or into any other store except @p StoreMA.
1373void ScopStmt::collectCandiateReductionLoads(
1374 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1375 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1376 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001377 return;
1378
1379 // Skip if there is not one binary operator between the load and the store
1380 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001381 if (!BinOp)
1382 return;
1383
1384 // Skip if the binary operators has multiple uses
1385 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001386 return;
1387
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001388 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001389 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1390 return;
1391
Johannes Doerfert9890a052014-07-01 00:32:29 +00001392 // Skip if the binary operator is outside the current SCoP
1393 if (BinOp->getParent() != Store->getParent())
1394 return;
1395
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001396 // Skip if it is a multiplicative reduction and we disabled them
1397 if (DisableMultiplicativeReductions &&
1398 (BinOp->getOpcode() == Instruction::Mul ||
1399 BinOp->getOpcode() == Instruction::FMul))
1400 return;
1401
Johannes Doerferte58a0122014-06-27 20:31:28 +00001402 // Check the binary operator operands for a candidate load
1403 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1404 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1405 if (!PossibleLoad0 && !PossibleLoad1)
1406 return;
1407
1408 // A load is only a candidate if it cannot escape (thus has only this use)
1409 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001410 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001411 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001412 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001413 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001414 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001415}
1416
1417/// @brief Check for reductions in this ScopStmt
1418///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001419/// Iterate over all store memory accesses and check for valid binary reduction
1420/// like chains. For all candidates we check if they have the same base address
1421/// and there are no other accesses which overlap with them. The base address
1422/// check rules out impossible reductions candidates early. The overlap check,
1423/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001424/// guarantees that none of the intermediate results will escape during
1425/// execution of the loop nest. We basically check here that no other memory
1426/// access can access the same memory as the potential reduction.
1427void ScopStmt::checkForReductions() {
1428 SmallVector<MemoryAccess *, 2> Loads;
1429 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1430
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001431 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001432 // stores and collecting possible reduction loads.
1433 for (MemoryAccess *StoreMA : MemAccs) {
1434 if (StoreMA->isRead())
1435 continue;
1436
1437 Loads.clear();
1438 collectCandiateReductionLoads(StoreMA, Loads);
1439 for (MemoryAccess *LoadMA : Loads)
1440 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1441 }
1442
1443 // Then check each possible candidate pair.
1444 for (const auto &CandidatePair : Candidates) {
1445 bool Valid = true;
1446 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1447 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1448
1449 // Skip those with obviously unequal base addresses.
1450 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1451 isl_map_free(LoadAccs);
1452 isl_map_free(StoreAccs);
1453 continue;
1454 }
1455
1456 // And check if the remaining for overlap with other memory accesses.
1457 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1458 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1459 isl_set *AllAccs = isl_map_range(AllAccsRel);
1460
1461 for (MemoryAccess *MA : MemAccs) {
1462 if (MA == CandidatePair.first || MA == CandidatePair.second)
1463 continue;
1464
1465 isl_map *AccRel =
1466 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1467 isl_set *Accs = isl_map_range(AccRel);
1468
1469 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1470 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1471 Valid = Valid && isl_set_is_empty(OverlapAccs);
1472 isl_set_free(OverlapAccs);
1473 }
1474 }
1475
1476 isl_set_free(AllAccs);
1477 if (!Valid)
1478 continue;
1479
Johannes Doerfertf6183392014-07-01 20:52:51 +00001480 const LoadInst *Load =
1481 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1482 MemoryAccess::ReductionType RT =
1483 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1484
Johannes Doerferte58a0122014-06-27 20:31:28 +00001485 // If no overlapping access was found we mark the load and store as
1486 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001487 CandidatePair.first->markAsReductionLike(RT);
1488 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001489 }
Tobias Grosser75805372011-04-29 06:27:02 +00001490}
1491
Tobias Grosser74394f02013-01-14 22:40:23 +00001492std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001493
Tobias Grosser54839312015-04-21 11:37:25 +00001494std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001495 auto *S = getSchedule();
1496 auto Str = stringFromIslObj(S);
1497 isl_map_free(S);
1498 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001499}
1500
Tobias Grosser74394f02013-01-14 22:40:23 +00001501unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001502
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001503unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001504
Tobias Grosser75805372011-04-29 06:27:02 +00001505const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1506
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001507const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001508 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001509}
1510
Tobias Grosser74394f02013-01-14 22:40:23 +00001511isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001512
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001513__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001514
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001515__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001516 return isl_set_get_space(Domain);
1517}
1518
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001519__isl_give isl_id *ScopStmt::getDomainId() const {
1520 return isl_set_get_tuple_id(Domain);
1521}
Tobias Grossercd95b772012-08-30 11:49:38 +00001522
Tobias Grosser10120182015-12-16 16:14:03 +00001523ScopStmt::~ScopStmt() { isl_set_free(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001524
1525void ScopStmt::print(raw_ostream &OS) const {
1526 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001527 OS.indent(12) << "Domain :=\n";
1528
1529 if (Domain) {
1530 OS.indent(16) << getDomainStr() << ";\n";
1531 } else
1532 OS.indent(16) << "n/a\n";
1533
Tobias Grosser54839312015-04-21 11:37:25 +00001534 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001535
1536 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001537 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001538 } else
1539 OS.indent(16) << "n/a\n";
1540
Tobias Grosser083d3d32014-06-28 08:59:45 +00001541 for (MemoryAccess *Access : MemAccs)
1542 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001543}
1544
1545void ScopStmt::dump() const { print(dbgs()); }
1546
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001547void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001548 // Remove all memory accesses in @p InvMAs from this statement
1549 // together with all scalar accesses that were caused by them.
Michael Krusead28e5a2016-01-26 13:33:15 +00001550 // MK_Value READs have no access instruction, hence would not be removed by
1551 // this function. However, it is only used for invariant LoadInst accesses,
1552 // its arguments are always affine, hence synthesizable, and therefore there
1553 // are no MK_Value READ accesses to be removed.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001554 for (MemoryAccess *MA : InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001555 auto Predicate = [&](MemoryAccess *Acc) {
Tobias Grosser3a6ac9f2015-11-30 21:13:43 +00001556 return Acc->getAccessInstruction() == MA->getAccessInstruction();
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001557 };
1558 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1559 MemAccs.end());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001560 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001561 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001562}
1563
Tobias Grosser75805372011-04-29 06:27:02 +00001564//===----------------------------------------------------------------------===//
1565/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001566
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001567void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001568 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1569 isl_set_free(Context);
1570 Context = NewContext;
1571}
1572
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001573/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1574struct SCEVSensitiveParameterRewriter
1575 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1576 ValueToValueMap &VMap;
1577 ScalarEvolution &SE;
1578
1579public:
1580 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1581 : VMap(VMap), SE(SE) {}
1582
1583 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1584 ValueToValueMap &VMap) {
1585 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1586 return SSPR.visit(E);
1587 }
1588
1589 const SCEV *visit(const SCEV *E) {
1590 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1591 }
1592
1593 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1594
1595 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1596 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1597 }
1598
1599 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1600 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1601 }
1602
1603 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1604 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1605 }
1606
1607 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1608 SmallVector<const SCEV *, 4> Operands;
1609 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1610 Operands.push_back(visit(E->getOperand(i)));
1611 return SE.getAddExpr(Operands);
1612 }
1613
1614 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1615 SmallVector<const SCEV *, 4> Operands;
1616 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1617 Operands.push_back(visit(E->getOperand(i)));
1618 return SE.getMulExpr(Operands);
1619 }
1620
1621 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1622 SmallVector<const SCEV *, 4> Operands;
1623 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1624 Operands.push_back(visit(E->getOperand(i)));
1625 return SE.getSMaxExpr(Operands);
1626 }
1627
1628 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1629 SmallVector<const SCEV *, 4> Operands;
1630 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1631 Operands.push_back(visit(E->getOperand(i)));
1632 return SE.getUMaxExpr(Operands);
1633 }
1634
1635 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1636 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1637 }
1638
1639 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1640 auto *Start = visit(E->getStart());
1641 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1642 visit(E->getStepRecurrence(SE)),
1643 E->getLoop(), SCEV::FlagAnyWrap);
1644 return SE.getAddExpr(Start, AddRec);
1645 }
1646
1647 const SCEV *visitUnknown(const SCEVUnknown *E) {
1648 if (auto *NewValue = VMap.lookup(E->getValue()))
1649 return SE.getUnknown(NewValue);
1650 return E;
1651 }
1652};
1653
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001654const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001655 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001656}
1657
Tobias Grosserabfbe632013-02-05 12:09:06 +00001658void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001659 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001660 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001661
1662 // Normalize the SCEV to get the representing element for an invariant load.
1663 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1664
Tobias Grosser60b54f12011-11-08 15:41:28 +00001665 if (ParameterIds.find(Parameter) != ParameterIds.end())
1666 continue;
1667
1668 int dimension = Parameters.size();
1669
1670 Parameters.push_back(Parameter);
1671 ParameterIds[Parameter] = dimension;
1672 }
1673}
1674
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001675__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001676 // Normalize the SCEV to get the representing element for an invariant load.
1677 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1678
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001679 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001680
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001681 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001682 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001683
Tobias Grosser8f99c162011-11-15 11:38:55 +00001684 std::string ParameterName;
1685
Craig Topper7fb6e472016-01-31 20:36:20 +00001686 ParameterName = "p_" + utostr(IdIter->second);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001687
Tobias Grosser8f99c162011-11-15 11:38:55 +00001688 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1689 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001690
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001691 // If this parameter references a specific Value and this value has a name
1692 // we use this name as it is likely to be unique and more useful than just
1693 // a number.
1694 if (Val->hasName())
1695 ParameterName = Val->getName();
1696 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
1697 auto LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
1698 if (LoadOrigin->hasName()) {
1699 ParameterName += "_loaded_from_";
1700 ParameterName +=
1701 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1702 }
1703 }
1704 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001705
Tobias Grosser20532b82014-04-11 17:56:49 +00001706 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1707 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001708}
Tobias Grosser75805372011-04-29 06:27:02 +00001709
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001710isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1711 isl_set *DomainContext = isl_union_set_params(getDomains());
1712 return isl_set_intersect_params(C, DomainContext);
1713}
1714
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001715void Scop::buildBoundaryContext() {
Tobias Grosser4927c8e2015-11-24 12:50:02 +00001716 if (IgnoreIntegerWrapping) {
1717 BoundaryContext = isl_set_universe(getParamSpace());
1718 return;
1719 }
1720
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001721 BoundaryContext = Affinator.getWrappingContext();
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001722
1723 // The isl_set_complement operation used to create the boundary context
1724 // can possibly become very expensive. We bound the compile time of
1725 // this operation by setting a compute out.
1726 //
1727 // TODO: We can probably get around using isl_set_complement and directly
1728 // AST generate BoundaryContext.
1729 long MaxOpsOld = isl_ctx_get_max_operations(getIslCtx());
Tobias Grosserf920fb12015-11-13 16:56:13 +00001730 isl_ctx_reset_operations(getIslCtx());
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001731 isl_ctx_set_max_operations(getIslCtx(), 300000);
1732 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_CONTINUE);
1733
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001734 BoundaryContext = isl_set_complement(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001735
Tobias Grossera52b4da2015-11-11 17:59:53 +00001736 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
1737 isl_set_free(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001738 BoundaryContext = isl_set_empty(getParamSpace());
Tobias Grossera52b4da2015-11-11 17:59:53 +00001739 }
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001740
1741 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
1742 isl_ctx_reset_operations(getIslCtx());
1743 isl_ctx_set_max_operations(getIslCtx(), MaxOpsOld);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001744 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001745 trackAssumption(WRAPPING, BoundaryContext, DebugLoc());
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001746}
1747
Hongbin Zheng192f69a2016-02-13 15:12:54 +00001748void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
1749 LoopInfo &LI) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001750 auto *R = &getRegion();
1751 auto &F = *R->getEntry()->getParent();
1752 for (auto &Assumption : AC.assumptions()) {
1753 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1754 if (!CI || CI->getNumArgOperands() != 1)
1755 continue;
1756 if (!DT.dominates(CI->getParent(), R->getEntry()))
1757 continue;
1758
1759 auto *Val = CI->getArgOperand(0);
1760 std::vector<const SCEV *> Params;
1761 if (!isAffineParamConstraint(Val, R, *SE, Params)) {
1762 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1763 CI->getDebugLoc(),
1764 "Non-affine user assumption ignored.");
1765 continue;
1766 }
1767
1768 addParams(Params);
1769
1770 auto *L = LI.getLoopFor(CI->getParent());
1771 SmallVector<isl_set *, 2> ConditionSets;
1772 buildConditionSets(*this, Val, nullptr, L, Context, ConditionSets);
1773 assert(ConditionSets.size() == 2);
1774 isl_set_free(ConditionSets[1]);
1775
1776 auto *AssumptionCtx = ConditionSets[0];
1777 emitOptimizationRemarkAnalysis(
1778 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1779 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1780 Context = isl_set_intersect(Context, AssumptionCtx);
1781 }
1782}
1783
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001784void Scop::addUserContext() {
1785 if (UserContextStr.empty())
1786 return;
1787
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001788 isl_set *UserContext =
1789 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001790 isl_space *Space = getParamSpace();
1791 if (isl_space_dim(Space, isl_dim_param) !=
1792 isl_set_dim(UserContext, isl_dim_param)) {
1793 auto SpaceStr = isl_space_to_str(Space);
1794 errs() << "Error: the context provided in -polly-context has not the same "
1795 << "number of dimensions than the computed context. Due to this "
1796 << "mismatch, the -polly-context option is ignored. Please provide "
1797 << "the context in the parameter space: " << SpaceStr << ".\n";
1798 free(SpaceStr);
1799 isl_set_free(UserContext);
1800 isl_space_free(Space);
1801 return;
1802 }
1803
1804 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1805 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1806 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1807
1808 if (strcmp(NameContext, NameUserContext) != 0) {
1809 auto SpaceStr = isl_space_to_str(Space);
1810 errs() << "Error: the name of dimension " << i
1811 << " provided in -polly-context "
1812 << "is '" << NameUserContext << "', but the name in the computed "
1813 << "context is '" << NameContext
1814 << "'. Due to this name mismatch, "
1815 << "the -polly-context option is ignored. Please provide "
1816 << "the context in the parameter space: " << SpaceStr << ".\n";
1817 free(SpaceStr);
1818 isl_set_free(UserContext);
1819 isl_space_free(Space);
1820 return;
1821 }
1822
1823 UserContext =
1824 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1825 isl_space_get_dim_id(Space, isl_dim_param, i));
1826 }
1827
1828 Context = isl_set_intersect(Context, UserContext);
1829 isl_space_free(Space);
1830}
1831
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001832void Scop::buildInvariantEquivalenceClasses(ScopDetection &SD) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00001833 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001834
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001835 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001836 for (LoadInst *LInst : RIL) {
1837 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1838
Johannes Doerfert96e54712016-02-07 17:30:13 +00001839 Type *Ty = LInst->getType();
1840 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001841 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001842 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001843 continue;
1844 }
1845
1846 ClassRep = LInst;
Johannes Doerfert96e54712016-02-07 17:30:13 +00001847 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(), nullptr,
1848 Ty);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001849 }
1850}
1851
Tobias Grosser6be480c2011-11-08 15:41:13 +00001852void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001853 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001854 Context = isl_set_universe(isl_space_copy(Space));
1855 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001856}
1857
Tobias Grosser18daaca2012-05-22 10:47:27 +00001858void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001859 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001860 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001861
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001862 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001863
Johannes Doerferte7044942015-02-24 11:58:30 +00001864 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001865 }
1866}
1867
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001868void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001869 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001870 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001871
Tobias Grosser083d3d32014-06-28 08:59:45 +00001872 for (const auto &ParamID : ParameterIds) {
1873 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001874 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001875 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001876 }
1877
1878 // Align the parameters of all data structures to the model.
1879 Context = isl_set_align_params(Context, Space);
1880
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001881 for (ScopStmt &Stmt : *this)
1882 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001883}
1884
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001885static __isl_give isl_set *
1886simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1887 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001888 // If we modelt all blocks in the SCoP that have side effects we can simplify
1889 // the context with the constraints that are needed for anything to be
1890 // executed at all. However, if we have error blocks in the SCoP we already
1891 // assumed some parameter combinations cannot occure and removed them from the
1892 // domains, thus we cannot use the remaining domain to simplify the
1893 // assumptions.
1894 if (!S.hasErrorBlock()) {
1895 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1896 AssumptionContext =
1897 isl_set_gist_params(AssumptionContext, DomainParameters);
1898 }
1899
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001900 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1901 return AssumptionContext;
1902}
1903
1904void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001905 // The parameter constraints of the iteration domains give us a set of
1906 // constraints that need to hold for all cases where at least a single
1907 // statement iteration is executed in the whole scop. We now simplify the
1908 // assumed context under the assumption that such constraints hold and at
1909 // least a single statement iteration is executed. For cases where no
1910 // statement instances are executed, the assumptions we have taken about
1911 // the executed code do not matter and can be changed.
1912 //
1913 // WARNING: This only holds if the assumptions we have taken do not reduce
1914 // the set of statement instances that are executed. Otherwise we
1915 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001916 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001917 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001918 // performed. In such a case, modifying the run-time conditions and
1919 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001920 // to not be executed.
1921 //
1922 // Example:
1923 //
1924 // When delinearizing the following code:
1925 //
1926 // for (long i = 0; i < 100; i++)
1927 // for (long j = 0; j < m; j++)
1928 // A[i+p][j] = 1.0;
1929 //
1930 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001931 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001932 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001933 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1934 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001935}
1936
Johannes Doerfertb164c792014-09-18 11:17:17 +00001937/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001938static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001939 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1940 isl_pw_multi_aff *MinPMA, *MaxPMA;
1941 isl_pw_aff *LastDimAff;
1942 isl_aff *OneAff;
1943 unsigned Pos;
1944
Johannes Doerfert9143d672014-09-27 11:02:39 +00001945 // Restrict the number of parameters involved in the access as the lexmin/
1946 // lexmax computation will take too long if this number is high.
1947 //
1948 // Experiments with a simple test case using an i7 4800MQ:
1949 //
1950 // #Parameters involved | Time (in sec)
1951 // 6 | 0.01
1952 // 7 | 0.04
1953 // 8 | 0.12
1954 // 9 | 0.40
1955 // 10 | 1.54
1956 // 11 | 6.78
1957 // 12 | 30.38
1958 //
1959 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1960 unsigned InvolvedParams = 0;
1961 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1962 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1963 InvolvedParams++;
1964
1965 if (InvolvedParams > RunTimeChecksMaxParameters) {
1966 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001967 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001968 }
1969 }
1970
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001971 Set = isl_set_remove_divs(Set);
1972
Johannes Doerfertb164c792014-09-18 11:17:17 +00001973 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1974 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1975
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001976 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1977 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1978
Johannes Doerfertb164c792014-09-18 11:17:17 +00001979 // Adjust the last dimension of the maximal access by one as we want to
1980 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1981 // we test during code generation might now point after the end of the
1982 // allocated array but we will never dereference it anyway.
1983 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1984 "Assumed at least one output dimension");
1985 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1986 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1987 OneAff = isl_aff_zero_on_domain(
1988 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1989 OneAff = isl_aff_add_constant_si(OneAff, 1);
1990 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1991 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1992
1993 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1994
1995 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001996 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001997}
1998
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001999static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2000 isl_set *Domain = MA->getStatement()->getDomain();
2001 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2002 return isl_set_reset_tuple_id(Domain);
2003}
2004
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002005/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
2006static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00002007 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002008 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002009
2010 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2011 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002012 Locations = isl_union_set_coalesce(Locations);
2013 Locations = isl_union_set_detect_equalities(Locations);
2014 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002015 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002016 isl_union_set_free(Locations);
2017 return Valid;
2018}
2019
Johannes Doerfert96425c22015-08-30 21:13:53 +00002020/// @brief Helper to treat non-affine regions and basic blocks the same.
2021///
2022///{
2023
2024/// @brief Return the block that is the representing block for @p RN.
2025static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2026 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2027 : RN->getNodeAs<BasicBlock>();
2028}
2029
2030/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002031static inline BasicBlock *
2032getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002033 if (RN->isSubRegion()) {
2034 assert(idx == 0);
2035 return RN->getNodeAs<Region>()->getExit();
2036 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002037 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002038}
2039
2040/// @brief Return the smallest loop surrounding @p RN.
2041static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2042 if (!RN->isSubRegion())
2043 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2044
2045 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2046 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2047 while (L && NonAffineSubRegion->contains(L))
2048 L = L->getParentLoop();
2049 return L;
2050}
2051
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002052static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2053 if (!RN->isSubRegion())
2054 return 1;
2055
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002056 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002057 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002058}
2059
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002060static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2061 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002062 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002063 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002064 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002065 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002066 return true;
2067 return false;
2068}
2069
Johannes Doerfert96425c22015-08-30 21:13:53 +00002070///}
2071
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002072static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2073 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002074 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002075 isl_id *DimId =
2076 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2077 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2078}
2079
Johannes Doerfert96425c22015-08-30 21:13:53 +00002080isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
2081 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
2082 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002083 return getDomainConditions(BB);
2084}
2085
2086isl_set *Scop::getDomainConditions(BasicBlock *BB) {
2087 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002088 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002089}
2090
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002091void Scop::removeErrorBlockDomains(ScopDetection &SD, DominatorTree &DT,
2092 LoopInfo &LI) {
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002093 auto removeDomains = [this, &DT](BasicBlock *Start) {
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002094 auto BBNode = DT.getNode(Start);
2095 for (auto ErrorChild : depth_first(BBNode)) {
2096 auto ErrorChildBlock = ErrorChild->getBlock();
2097 auto CurrentDomain = DomainMap[ErrorChildBlock];
2098 auto Empty = isl_set_empty(isl_set_get_space(CurrentDomain));
2099 DomainMap[ErrorChildBlock] = Empty;
2100 isl_set_free(CurrentDomain);
2101 }
2102 };
2103
Tobias Grosser5ef2bc32015-11-23 10:18:23 +00002104 SmallVector<Region *, 4> Todo = {&R};
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002105
2106 while (!Todo.empty()) {
2107 auto SubRegion = Todo.back();
2108 Todo.pop_back();
2109
2110 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
2111 for (auto &Child : *SubRegion)
2112 Todo.push_back(Child.get());
2113 continue;
2114 }
2115 if (containsErrorBlock(SubRegion->getNode(), getRegion(), LI, DT))
2116 removeDomains(SubRegion->getEntry());
2117 }
2118
2119 for (auto BB : R.blocks())
2120 if (isErrorBlock(*BB, R, LI, DT))
2121 removeDomains(BB);
2122}
2123
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002124void Scop::buildDomains(Region *R, ScopDetection &SD, DominatorTree &DT,
2125 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002126
Johannes Doerfert432658d2016-01-26 11:01:41 +00002127 bool IsOnlyNonAffineRegion = SD.isNonAffineSubRegion(R, R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002128 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002129 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2130 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002131 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002132
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002133 while (LD-- >= 0) {
2134 S = addDomainDimId(S, LD + 1, L);
2135 L = L->getParentLoop();
2136 }
2137
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002138 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002139
Johannes Doerfert432658d2016-01-26 11:01:41 +00002140 if (IsOnlyNonAffineRegion)
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002141 return;
2142
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002143 buildDomainsWithBranchConstraints(R, SD, DT, LI);
2144 propagateDomainConstraints(R, SD, DT, LI);
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002145
2146 // Error blocks and blocks dominated by them have been assumed to never be
2147 // executed. Representing them in the Scop does not add any value. In fact,
2148 // it is likely to cause issues during construction of the ScopStmts. The
2149 // contents of error blocks have not been verfied to be expressible and
2150 // will cause problems when building up a ScopStmt for them.
2151 // Furthermore, basic blocks dominated by error blocks may reference
2152 // instructions in the error block which, if the error block is not modeled,
2153 // can themselves not be constructed properly.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002154 removeErrorBlockDomains(SD, DT, LI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002155}
2156
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002157void Scop::buildDomainsWithBranchConstraints(Region *R, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002158 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert6f50c292016-01-26 11:03:25 +00002159 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002160
2161 // To create the domain for each block in R we iterate over all blocks and
2162 // subregions in R and propagate the conditions under which the current region
2163 // element is executed. To this end we iterate in reverse post order over R as
2164 // it ensures that we first visit all predecessors of a region node (either a
2165 // basic block or a subregion) before we visit the region node itself.
2166 // Initially, only the domain for the SCoP region entry block is set and from
2167 // there we propagate the current domain to all successors, however we add the
2168 // condition that the successor is actually executed next.
2169 // As we are only interested in non-loop carried constraints here we can
2170 // simply skip loop back edges.
2171
2172 ReversePostOrderTraversal<Region *> RTraversal(R);
2173 for (auto *RN : RTraversal) {
2174
2175 // Recurse for affine subregions but go on for basic blocks and non-affine
2176 // subregions.
2177 if (RN->isSubRegion()) {
2178 Region *SubRegion = RN->getNodeAs<Region>();
2179 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002180 buildDomainsWithBranchConstraints(SubRegion, SD, DT, LI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002181 continue;
2182 }
2183 }
2184
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002185 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002186 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002187
Johannes Doerfert96425c22015-08-30 21:13:53 +00002188 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002189 TerminatorInst *TI = BB->getTerminator();
2190
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002191 if (isa<UnreachableInst>(TI))
2192 continue;
2193
Johannes Doerfertf5673802015-10-01 23:48:18 +00002194 isl_set *Domain = DomainMap.lookup(BB);
2195 if (!Domain) {
2196 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2197 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002198 continue;
2199 }
2200
Johannes Doerfert96425c22015-08-30 21:13:53 +00002201 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002202
2203 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2204 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2205
2206 // Build the condition sets for the successor nodes of the current region
2207 // node. If it is a non-affine subregion we will always execute the single
2208 // exit node, hence the single entry node domain is the condition set. For
2209 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002210 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002211 if (RN->isSubRegion())
2212 ConditionSets.push_back(isl_set_copy(Domain));
2213 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002214 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002215
2216 // Now iterate over the successors and set their initial domain based on
2217 // their condition set. We skip back edges here and have to be careful when
2218 // we leave a loop not to keep constraints over a dimension that doesn't
2219 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002220 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002221 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002222 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002223 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002224
2225 // Skip back edges.
2226 if (DT.dominates(SuccBB, BB)) {
2227 isl_set_free(CondSet);
2228 continue;
2229 }
2230
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002231 // Do not adjust the number of dimensions if we enter a boxed loop or are
2232 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002233 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfert6f50c292016-01-26 11:03:25 +00002234 while (BoxedLoops.count(SuccBBLoop))
2235 SuccBBLoop = SuccBBLoop->getParentLoop();
Johannes Doerfert634909c2015-10-04 14:57:41 +00002236
2237 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002238
2239 // Check if the edge to SuccBB is a loop entry or exit edge. If so
2240 // adjust the dimensionality accordingly. Lastly, if we leave a loop
2241 // and enter a new one we need to drop the old constraints.
2242 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002243 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002244 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002245 CondSet = isl_set_project_out(CondSet, isl_dim_set,
2246 isl_set_n_dim(CondSet) - LoopDepthDiff,
2247 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002248 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002249 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002250 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002251 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002252 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002253 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002254 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
2255 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002256 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002257 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002258 }
2259
2260 // Set the domain for the successor or merge it with an existing domain in
2261 // case there are multiple paths (without loop back edges) to the
2262 // successor block.
2263 isl_set *&SuccDomain = DomainMap[SuccBB];
2264 if (!SuccDomain)
2265 SuccDomain = CondSet;
2266 else
2267 SuccDomain = isl_set_union(SuccDomain, CondSet);
2268
2269 SuccDomain = isl_set_coalesce(SuccDomain);
Tobias Grosser75dc40c2015-12-20 13:31:48 +00002270 if (isl_set_n_basic_set(SuccDomain) > MaxConjunctsInDomain) {
2271 auto *Empty = isl_set_empty(isl_set_get_space(SuccDomain));
2272 isl_set_free(SuccDomain);
2273 SuccDomain = Empty;
2274 invalidate(ERROR_DOMAINCONJUNCTS, DebugLoc());
2275 }
Johannes Doerfert634909c2015-10-04 14:57:41 +00002276 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
2277 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002278 }
2279 }
2280}
2281
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002282/// @brief Return the domain for @p BB wrt @p DomainMap.
2283///
2284/// This helper function will lookup @p BB in @p DomainMap but also handle the
2285/// case where @p BB is contained in a non-affine subregion using the region
2286/// tree obtained by @p RI.
2287static __isl_give isl_set *
2288getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
2289 RegionInfo &RI) {
2290 auto DIt = DomainMap.find(BB);
2291 if (DIt != DomainMap.end())
2292 return isl_set_copy(DIt->getSecond());
2293
2294 Region *R = RI.getRegionFor(BB);
2295 while (R->getEntry() == BB)
2296 R = R->getParent();
2297 return getDomainForBlock(R->getEntry(), DomainMap, RI);
2298}
2299
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002300void Scop::propagateDomainConstraints(Region *R, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002301 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002302 // Iterate over the region R and propagate the domain constrains from the
2303 // predecessors to the current node. In contrast to the
2304 // buildDomainsWithBranchConstraints function, this one will pull the domain
2305 // information from the predecessors instead of pushing it to the successors.
2306 // Additionally, we assume the domains to be already present in the domain
2307 // map here. However, we iterate again in reverse post order so we know all
2308 // predecessors have been visited before a block or non-affine subregion is
2309 // visited.
2310
2311 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2312 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2313
2314 ReversePostOrderTraversal<Region *> RTraversal(R);
2315 for (auto *RN : RTraversal) {
2316
2317 // Recurse for affine subregions but go on for basic blocks and non-affine
2318 // subregions.
2319 if (RN->isSubRegion()) {
2320 Region *SubRegion = RN->getNodeAs<Region>();
2321 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002322 propagateDomainConstraints(SubRegion, SD, DT, LI);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002323 continue;
2324 }
2325 }
2326
Johannes Doerfertf5673802015-10-01 23:48:18 +00002327 // Get the domain for the current block and check if it was initialized or
2328 // not. The only way it was not is if this block is only reachable via error
2329 // blocks, thus will not be executed under the assumptions we make. Such
2330 // blocks have to be skipped as their predecessors might not have domains
2331 // either. It would not benefit us to compute the domain anyway, only the
2332 // domains of the error blocks that are reachable from non-error blocks
2333 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002334 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002335 isl_set *&Domain = DomainMap[BB];
2336 if (!Domain) {
2337 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2338 << ", it is only reachable from error blocks.\n");
2339 DomainMap.erase(BB);
2340 continue;
2341 }
2342 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
2343
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002344 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2345 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2346
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002347 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2348 for (auto *PredBB : predecessors(BB)) {
2349
2350 // Skip backedges
2351 if (DT.dominates(BB, PredBB))
2352 continue;
2353
2354 isl_set *PredBBDom = nullptr;
2355
2356 // Handle the SCoP entry block with its outside predecessors.
2357 if (!getRegion().contains(PredBB))
2358 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
2359
2360 if (!PredBBDom) {
2361 // Determine the loop depth of the predecessor and adjust its domain to
2362 // the domain of the current block. This can mean we have to:
2363 // o) Drop a dimension if this block is the exit of a loop, not the
2364 // header of a new loop and the predecessor was part of the loop.
2365 // o) Add an unconstrainted new dimension if this block is the header
2366 // of a loop and the predecessor is not part of it.
2367 // o) Drop the information about the innermost loop dimension when the
2368 // predecessor and the current block are surrounded by different
2369 // loops in the same depth.
2370 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2371 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2372 while (BoxedLoops.count(PredBBLoop))
2373 PredBBLoop = PredBBLoop->getParentLoop();
2374
2375 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002376 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002377 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002378 PredBBDom = isl_set_project_out(
2379 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2380 LoopDepthDiff);
2381 else if (PredBBLoopDepth < BBLoopDepth) {
2382 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002383 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002384 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2385 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002386 PredBBDom = isl_set_drop_constraints_involving_dims(
2387 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002388 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002389 }
2390
2391 PredDom = isl_set_union(PredDom, PredBBDom);
2392 }
2393
2394 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002395 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002396
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002397 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002398 addLoopBoundsToHeaderDomain(BBLoop, LI);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002399
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002400 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002401 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002402 IsOptimized = true;
2403 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002404 addAssumption(ERRORBLOCK, isl_set_complement(DomPar),
2405 BB->getTerminator()->getDebugLoc());
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002406 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002407 }
2408}
2409
2410/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2411/// is incremented by one and all other dimensions are equal, e.g.,
2412/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2413/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2414static __isl_give isl_map *
2415createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2416 auto *MapSpace = isl_space_map_from_set(SetSpace);
2417 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2418 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2419 if (u != Dim)
2420 NextIterationMap =
2421 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2422 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2423 C = isl_constraint_set_constant_si(C, 1);
2424 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2425 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2426 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2427 return NextIterationMap;
2428}
2429
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002430void Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002431 int LoopDepth = getRelativeLoopDepth(L);
2432 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002433
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002434 BasicBlock *HeaderBB = L->getHeader();
2435 assert(DomainMap.count(HeaderBB));
2436 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002437
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002438 isl_map *NextIterationMap =
2439 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002440
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002441 isl_set *UnionBackedgeCondition =
2442 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002443
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002444 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2445 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002446
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002447 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002448
2449 // If the latch is only reachable via error statements we skip it.
2450 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2451 if (!LatchBBDom)
2452 continue;
2453
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002454 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002455
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002456 TerminatorInst *TI = LatchBB->getTerminator();
2457 BranchInst *BI = dyn_cast<BranchInst>(TI);
2458 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002459 BackedgeCondition = isl_set_copy(LatchBBDom);
2460 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002461 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002462 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002463 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002464
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002465 // Free the non back edge condition set as we do not need it.
2466 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002467
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002468 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002469 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002470
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002471 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2472 assert(LatchLoopDepth >= LoopDepth);
2473 BackedgeCondition =
2474 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2475 LatchLoopDepth - LoopDepth);
2476 UnionBackedgeCondition =
2477 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002478 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002479
2480 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2481 for (int i = 0; i < LoopDepth; i++)
2482 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2483
2484 isl_set *UnionBackedgeConditionComplement =
2485 isl_set_complement(UnionBackedgeCondition);
2486 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2487 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2488 UnionBackedgeConditionComplement =
2489 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2490 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2491 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2492
2493 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2494 HeaderBBDom = Parts.second;
2495
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002496 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2497 // the bounded assumptions to the context as they are already implied by the
2498 // <nsw> tag.
2499 if (Affinator.hasNSWAddRecForLoop(L)) {
2500 isl_set_free(Parts.first);
2501 return;
2502 }
2503
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002504 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2505 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002506 addAssumption(INFINITELOOP, BoundedCtx,
2507 HeaderBB->getTerminator()->getDebugLoc());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002508}
2509
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002510void Scop::buildAliasChecks(AliasAnalysis &AA) {
2511 if (!PollyUseRuntimeAliasChecks)
2512 return;
2513
2514 if (buildAliasGroups(AA))
2515 return;
2516
2517 // If a problem occurs while building the alias groups we need to delete
2518 // this SCoP and pretend it wasn't valid in the first place. To this end
2519 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002520 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002521
2522 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2523 << " could not be created as the number of parameters involved "
2524 "is too high. The SCoP will be "
2525 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2526 "the maximal number of parameters but be advised that the "
2527 "compile time might increase exponentially.\n\n");
2528}
2529
Johannes Doerfert9143d672014-09-27 11:02:39 +00002530bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002531 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002532 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002533 // for all memory accesses inside the SCoP.
2534 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002535 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002536 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002537 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002538 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002539 // if their access domains intersect, otherwise they are in different
2540 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002541 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002542 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002543 // and maximal accesses to each array of a group in read only and non
2544 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002545 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2546
2547 AliasSetTracker AST(AA);
2548
2549 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002550 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002551 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002552
2553 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002554 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002555 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2556 isl_set_free(StmtDomain);
2557 if (StmtDomainEmpty)
2558 continue;
2559
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002560 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002561 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002562 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002563 if (!MA->isRead())
2564 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002565 MemAccInst Acc(MA->getAccessInstruction());
2566 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002567 AST.add(Acc);
2568 }
2569 }
2570
2571 SmallVector<AliasGroupTy, 4> AliasGroups;
2572 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002573 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002574 continue;
2575 AliasGroupTy AG;
2576 for (auto PR : AS)
2577 AG.push_back(PtrToAcc[PR.getValue()]);
2578 assert(AG.size() > 1 &&
2579 "Alias groups should contain at least two accesses");
2580 AliasGroups.push_back(std::move(AG));
2581 }
2582
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002583 // Split the alias groups based on their domain.
2584 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2585 AliasGroupTy NewAG;
2586 AliasGroupTy &AG = AliasGroups[u];
2587 AliasGroupTy::iterator AGI = AG.begin();
2588 isl_set *AGDomain = getAccessDomain(*AGI);
2589 while (AGI != AG.end()) {
2590 MemoryAccess *MA = *AGI;
2591 isl_set *MADomain = getAccessDomain(MA);
2592 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2593 NewAG.push_back(MA);
2594 AGI = AG.erase(AGI);
2595 isl_set_free(MADomain);
2596 } else {
2597 AGDomain = isl_set_union(AGDomain, MADomain);
2598 AGI++;
2599 }
2600 }
2601 if (NewAG.size() > 1)
2602 AliasGroups.push_back(std::move(NewAG));
2603 isl_set_free(AGDomain);
2604 }
2605
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002606 auto &F = *getRegion().getEntry()->getParent();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002607 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002608 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2609 for (AliasGroupTy &AG : AliasGroups) {
2610 NonReadOnlyBaseValues.clear();
2611 ReadOnlyPairs.clear();
2612
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002613 if (AG.size() < 2) {
2614 AG.clear();
2615 continue;
2616 }
2617
Johannes Doerfert13771732014-10-01 12:40:46 +00002618 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002619 emitOptimizationRemarkAnalysis(
2620 F.getContext(), DEBUG_TYPE, F,
2621 (*II)->getAccessInstruction()->getDebugLoc(),
2622 "Possibly aliasing pointer, use restrict keyword.");
2623
Johannes Doerfert13771732014-10-01 12:40:46 +00002624 Value *BaseAddr = (*II)->getBaseAddr();
2625 if (HasWriteAccess.count(BaseAddr)) {
2626 NonReadOnlyBaseValues.insert(BaseAddr);
2627 II++;
2628 } else {
2629 ReadOnlyPairs[BaseAddr].insert(*II);
2630 II = AG.erase(II);
2631 }
2632 }
2633
2634 // If we don't have read only pointers check if there are at least two
2635 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002636 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002637 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002638 continue;
2639 }
2640
2641 // If we don't have non read only pointers clear the alias group.
2642 if (NonReadOnlyBaseValues.empty()) {
2643 AG.clear();
2644 continue;
2645 }
2646
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002647 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002648 MinMaxAliasGroups.emplace_back();
2649 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2650 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2651 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2652 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002653
2654 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002655
2656 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002657 for (MemoryAccess *MA : AG)
2658 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002659
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002660 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2661 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002662
2663 // Bail out if the number of values we need to compare is too large.
2664 // This is important as the number of comparisions grows quadratically with
2665 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002666 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2667 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002668 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002669
2670 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002671 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002672 Accesses = isl_union_map_empty(getParamSpace());
2673
2674 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2675 for (MemoryAccess *MA : ReadOnlyPair.second)
2676 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2677
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002678 Valid =
2679 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002680
2681 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002682 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002683 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002684
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002685 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002686}
2687
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002688/// @brief Get the smallest loop that contains @p R but is not in @p R.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002689static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002690 // Start with the smallest loop containing the entry and expand that
2691 // loop until it contains all blocks in the region. If there is a loop
2692 // containing all blocks in the region check if it is itself contained
2693 // and if so take the parent loop as it will be the smallest containing
2694 // the region but not contained by it.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002695 Loop *L = LI.getLoopFor(R.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002696 while (L) {
2697 bool AllContained = true;
2698 for (auto *BB : R.blocks())
2699 AllContained &= L->contains(BB);
2700 if (AllContained)
2701 break;
2702 L = L->getParentLoop();
2703 }
2704
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002705 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2706}
2707
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002708static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2709 ScopDetection &SD) {
2710
2711 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2712
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002713 unsigned MinLD = INT_MAX, MaxLD = 0;
2714 for (BasicBlock *BB : R.blocks()) {
2715 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002716 if (!R.contains(L))
2717 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002718 if (BoxedLoops && BoxedLoops->count(L))
2719 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002720 unsigned LD = L->getLoopDepth();
2721 MinLD = std::min(MinLD, LD);
2722 MaxLD = std::max(MaxLD, LD);
2723 }
2724 }
2725
2726 // Handle the case that there is no loop in the SCoP first.
2727 if (MaxLD == 0)
2728 return 1;
2729
2730 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2731 assert(MaxLD >= MinLD &&
2732 "Maximal loop depth was smaller than mininaml loop depth?");
2733 return MaxLD - MinLD + 1;
2734}
2735
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002736Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, unsigned MaxLoopDepth)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00002737 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002738 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002739 MaxLoopDepth(MaxLoopDepth), IslCtx(isl_ctx_alloc(), isl_ctx_free),
2740 Context(nullptr), Affinator(this), AssumedContext(nullptr),
2741 BoundaryContext(nullptr), Schedule(nullptr) {
2742 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00002743 buildContext();
2744}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002745
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002746void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002747 DominatorTree &DT, LoopInfo &LI) {
2748 addUserAssumptions(AC, DT, LI);
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002749 buildInvariantEquivalenceClasses(SD);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002750
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002751 buildDomains(&R, SD, DT, LI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002752
Michael Krusecac948e2015-10-02 13:53:07 +00002753 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002754 // Exit early in case there are no executable statements left in this scop.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002755 simplifySCoP(true, DT, LI);
Michael Kruseafe06702015-10-02 16:33:27 +00002756 if (Stmts.empty())
2757 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002758
Michael Krusecac948e2015-10-02 13:53:07 +00002759 // The ScopStmts now have enough information to initialize themselves.
2760 for (ScopStmt &Stmt : Stmts)
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002761 Stmt.init(SD);
Michael Krusecac948e2015-10-02 13:53:07 +00002762
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002763 buildSchedule(SD, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00002764
Tobias Grosser8286b832015-11-02 11:29:32 +00002765 if (isl_set_is_empty(AssumedContext))
2766 return;
2767
2768 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002769 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002770 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002771 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002772 buildBoundaryContext();
2773 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002774 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002775
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002776 hoistInvariantLoads(SD);
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002777 simplifySCoP(false, DT, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00002778}
2779
2780Scop::~Scop() {
2781 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002782 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002783 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002784 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002785
Johannes Doerfert96425c22015-08-30 21:13:53 +00002786 for (auto It : DomainMap)
2787 isl_set_free(It.second);
2788
Johannes Doerfertb164c792014-09-18 11:17:17 +00002789 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002790 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002791 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002792 isl_pw_multi_aff_free(MMA.first);
2793 isl_pw_multi_aff_free(MMA.second);
2794 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002795 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002796 isl_pw_multi_aff_free(MMA.first);
2797 isl_pw_multi_aff_free(MMA.second);
2798 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002799 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002800
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002801 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002802 isl_set_free(std::get<2>(IAClass));
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002803
2804 // Explicitly release all Scop objects and the underlying isl objects before
2805 // we relase the isl context.
2806 Stmts.clear();
2807 ScopArrayInfoMap.clear();
2808 AccFuncMap.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00002809}
2810
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002811void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00002812 // Check all array accesses for each base pointer and find a (virtual) element
2813 // size for the base pointer that divides all access functions.
2814 for (auto &Stmt : *this)
2815 for (auto *Access : Stmt) {
2816 if (!Access->isArrayKind())
2817 continue;
2818 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(),
2819 ScopArrayInfo::MK_Array)];
2820 if (SAI->getNumberOfDimensions() != 1)
2821 continue;
2822 unsigned DivisibleSize = SAI->getElemSizeInBytes();
2823 auto *Subscript = Access->getSubscript(0);
2824 while (!isDivisible(Subscript, DivisibleSize, *SE))
2825 DivisibleSize /= 2;
2826 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
2827 SAI->updateElementType(Ty);
2828 }
2829
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002830 for (auto &Stmt : *this)
2831 for (auto &Access : Stmt)
2832 Access->updateDimensionality();
2833}
2834
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002835void Scop::simplifySCoP(bool RemoveIgnoredStmts, DominatorTree &DT,
2836 LoopInfo &LI) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002837 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2838 ScopStmt &Stmt = *StmtIt;
Michael Krusecac948e2015-10-02 13:53:07 +00002839 RegionNode *RN = Stmt.isRegionStmt()
2840 ? Stmt.getRegion()->getNode()
2841 : getRegion().getBBNode(Stmt.getBasicBlock());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002842
Johannes Doerferteca9e892015-11-03 16:54:49 +00002843 bool RemoveStmt = StmtIt->isEmpty();
2844 if (!RemoveStmt)
2845 RemoveStmt = isl_set_is_empty(DomainMap[getRegionNodeBasicBlock(RN)]);
2846 if (!RemoveStmt)
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002847 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN, DT, LI));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002848
Johannes Doerferteca9e892015-11-03 16:54:49 +00002849 // Remove read only statements only after invariant loop hoisting.
2850 if (!RemoveStmt && !RemoveIgnoredStmts) {
2851 bool OnlyRead = true;
2852 for (MemoryAccess *MA : Stmt) {
2853 if (MA->isRead())
2854 continue;
2855
2856 OnlyRead = false;
2857 break;
2858 }
2859
2860 RemoveStmt = OnlyRead;
2861 }
2862
2863 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00002864 // Remove the statement because it is unnecessary.
2865 if (Stmt.isRegionStmt())
2866 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2867 StmtMap.erase(BB);
2868 else
2869 StmtMap.erase(Stmt.getBasicBlock());
2870
2871 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002872 continue;
2873 }
2874
Michael Krusecac948e2015-10-02 13:53:07 +00002875 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002876 }
2877}
2878
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002879const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2880 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2881 if (!LInst)
2882 return nullptr;
2883
2884 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2885 LInst = cast<LoadInst>(Rep);
2886
Johannes Doerfert96e54712016-02-07 17:30:13 +00002887 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002888 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2889 for (auto &IAClass : InvariantEquivClasses)
Johannes Doerfert96e54712016-02-07 17:30:13 +00002890 if (PointerSCEV == std::get<0>(IAClass) && Ty == std::get<3>(IAClass))
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002891 return &IAClass;
2892
2893 return nullptr;
2894}
2895
2896void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2897
2898 // Get the context under which the statement is executed.
2899 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2900 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2901 DomainCtx = isl_set_detect_equalities(DomainCtx);
2902 DomainCtx = isl_set_coalesce(DomainCtx);
2903
2904 // Project out all parameters that relate to loads in the statement. Otherwise
2905 // we could have cyclic dependences on the constraints under which the
2906 // hoisted loads are executed and we could not determine an order in which to
2907 // pre-load them. This happens because not only lower bounds are part of the
2908 // domain but also upper bounds.
2909 for (MemoryAccess *MA : InvMAs) {
2910 Instruction *AccInst = MA->getAccessInstruction();
2911 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00002912 SetVector<Value *> Values;
2913 for (const SCEV *Parameter : Parameters) {
2914 Values.clear();
2915 findValues(Parameter, Values);
2916 if (!Values.count(AccInst))
2917 continue;
2918
2919 if (isl_id *ParamId = getIdForParam(Parameter)) {
2920 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2921 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2922 isl_id_free(ParamId);
2923 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002924 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002925 }
2926 }
2927
2928 for (MemoryAccess *MA : InvMAs) {
2929 // Check for another invariant access that accesses the same location as
2930 // MA and if found consolidate them. Otherwise create a new equivalence
2931 // class at the end of InvariantEquivClasses.
2932 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00002933 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002934 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2935
2936 bool Consolidated = false;
2937 for (auto &IAClass : InvariantEquivClasses) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002938 if (PointerSCEV != std::get<0>(IAClass) || Ty != std::get<3>(IAClass))
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002939 continue;
2940
2941 Consolidated = true;
2942
2943 // Add MA to the list of accesses that are in this class.
2944 auto &MAs = std::get<1>(IAClass);
2945 MAs.push_front(MA);
2946
2947 // Unify the execution context of the class and this statement.
2948 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002949 if (IAClassDomainCtx)
2950 IAClassDomainCtx = isl_set_coalesce(
2951 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
2952 else
2953 IAClassDomainCtx = isl_set_copy(DomainCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002954 break;
2955 }
2956
2957 if (Consolidated)
2958 continue;
2959
2960 // If we did not consolidate MA, thus did not find an equivalence class
2961 // for it, we create a new one.
2962 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
Johannes Doerfert96e54712016-02-07 17:30:13 +00002963 isl_set_copy(DomainCtx), Ty);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002964 }
2965
2966 isl_set_free(DomainCtx);
2967}
2968
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002969bool Scop::isHoistableAccess(MemoryAccess *Access,
2970 __isl_keep isl_union_map *Writes) {
2971 // TODO: Loads that are not loop carried, hence are in a statement with
2972 // zero iterators, are by construction invariant, though we
2973 // currently "hoist" them anyway. This is necessary because we allow
2974 // them to be treated as parameters (e.g., in conditions) and our code
2975 // generation would otherwise use the old value.
2976
2977 auto &Stmt = *Access->getStatement();
2978 BasicBlock *BB =
2979 Stmt.isBlockStmt() ? Stmt.getBasicBlock() : Stmt.getRegion()->getEntry();
2980
2981 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
2982 return false;
2983
2984 // Skip accesses that have an invariant base pointer which is defined but
2985 // not loaded inside the SCoP. This can happened e.g., if a readnone call
2986 // returns a pointer that is used as a base address. However, as we want
2987 // to hoist indirect pointers, we allow the base pointer to be defined in
2988 // the region if it is also a memory access. Each ScopArrayInfo object
2989 // that has a base pointer origin has a base pointer that is loaded and
2990 // that it is invariant, thus it will be hoisted too. However, if there is
2991 // no base pointer origin we check that the base pointer is defined
2992 // outside the region.
2993 const ScopArrayInfo *SAI = Access->getScopArrayInfo();
Johannes Doerfert4cf15802016-02-15 12:42:05 +00002994 auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr());
2995 if (SAI->getBasePtrOriginSAI()) {
2996 assert(BasePtrInst && R.contains(BasePtrInst));
2997 if (!isa<LoadInst>(BasePtrInst))
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002998 return false;
Johannes Doerfert4cf15802016-02-15 12:42:05 +00002999 auto *BasePtrStmt = getStmtForBasicBlock(BasePtrInst->getParent());
3000 assert(BasePtrStmt);
3001 auto *BasePtrMA = BasePtrStmt->getArrayAccessOrNULLFor(BasePtrInst);
3002 if (BasePtrMA && !isHoistableAccess(BasePtrMA, Writes))
3003 return false;
3004 } else if (BasePtrInst && R.contains(BasePtrInst))
3005 return false;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003006
3007 // Skip accesses in non-affine subregions as they might not be executed
3008 // under the same condition as the entry of the non-affine subregion.
3009 if (BB != Access->getAccessInstruction()->getParent())
3010 return false;
3011
3012 isl_map *AccessRelation = Access->getAccessRelation();
3013
3014 // Skip accesses that have an empty access relation. These can be caused
3015 // by multiple offsets with a type cast in-between that cause the overall
3016 // byte offset to be not divisible by the new types sizes.
3017 if (isl_map_is_empty(AccessRelation)) {
3018 isl_map_free(AccessRelation);
3019 return false;
3020 }
3021
3022 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3023 Stmt.getNumIterators())) {
3024 isl_map_free(AccessRelation);
3025 return false;
3026 }
3027
3028 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3029 isl_set *AccessRange = isl_map_range(AccessRelation);
3030
3031 isl_union_map *Written = isl_union_map_intersect_range(
3032 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
3033 bool IsWritten = !isl_union_map_is_empty(Written);
3034 isl_union_map_free(Written);
3035
3036 if (IsWritten)
3037 return false;
3038
3039 return true;
3040}
3041
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003042void Scop::verifyInvariantLoads(ScopDetection &SD) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003043 auto &RIL = *SD.getRequiredInvariantLoads(&getRegion());
3044 for (LoadInst *LI : RIL) {
3045 assert(LI && getRegion().contains(LI));
3046 ScopStmt *Stmt = getStmtForBasicBlock(LI->getParent());
Tobias Grosser949e8c62015-12-21 07:10:39 +00003047 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003048 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3049 return;
3050 }
3051 }
3052}
3053
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003054void Scop::hoistInvariantLoads(ScopDetection &SD) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003055 isl_union_map *Writes = getWrites();
3056 for (ScopStmt &Stmt : *this) {
3057
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003058 MemoryAccessList InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003059
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003060 for (MemoryAccess *Access : Stmt)
3061 if (isHoistableAccess(Access, Writes))
3062 InvariantAccesses.push_front(Access);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003063
3064 // We inserted invariant accesses always in the front but need them to be
3065 // sorted in a "natural order". The statements are already sorted in reverse
3066 // post order and that suffices for the accesses too. The reason we require
3067 // an order in the first place is the dependences between invariant loads
3068 // that can be caused by indirect loads.
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003069 InvariantAccesses.reverse();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003070
3071 // Transfer the memory access from the statement to the SCoP.
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003072 Stmt.removeMemoryAccesses(InvariantAccesses);
3073 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003074 }
3075 isl_union_map_free(Writes);
3076
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003077 verifyInvariantLoads(SD);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003078}
3079
Johannes Doerfert80ef1102014-11-07 08:31:31 +00003080const ScopArrayInfo *
Tobias Grossercc779502016-02-02 13:22:54 +00003081Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003082 ArrayRef<const SCEV *> Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00003083 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003084 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003085 if (!SAI) {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003086 auto &DL = getRegion().getEntry()->getModule()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003087 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003088 DL, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003089 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003090 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003091 // In case of mismatching array sizes, we bail out by setting the run-time
3092 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003093 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003094 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003095 }
Tobias Grosserab671442015-05-23 05:58:27 +00003096 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003097}
3098
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003099const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00003100 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003101 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003102 assert(SAI && "No ScopArrayInfo available for this base pointer");
3103 return SAI;
3104}
3105
Tobias Grosser74394f02013-01-14 22:40:23 +00003106std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003107std::string Scop::getAssumedContextStr() const {
3108 return stringFromIslObj(AssumedContext);
3109}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003110std::string Scop::getBoundaryContextStr() const {
3111 return stringFromIslObj(BoundaryContext);
3112}
Tobias Grosser75805372011-04-29 06:27:02 +00003113
3114std::string Scop::getNameStr() const {
3115 std::string ExitName, EntryName;
3116 raw_string_ostream ExitStr(ExitName);
3117 raw_string_ostream EntryStr(EntryName);
3118
Tobias Grosserf240b482014-01-09 10:42:15 +00003119 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003120 EntryStr.str();
3121
3122 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003123 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003124 ExitStr.str();
3125 } else
3126 ExitName = "FunctionExit";
3127
3128 return EntryName + "---" + ExitName;
3129}
3130
Tobias Grosser74394f02013-01-14 22:40:23 +00003131__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003132__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003133 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003134}
3135
Tobias Grossere86109f2013-10-29 21:05:49 +00003136__isl_give isl_set *Scop::getAssumedContext() const {
3137 return isl_set_copy(AssumedContext);
3138}
3139
Johannes Doerfert43788c52015-08-20 05:58:56 +00003140__isl_give isl_set *Scop::getRuntimeCheckContext() const {
3141 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003142 RuntimeCheckContext =
3143 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
3144 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00003145 return RuntimeCheckContext;
3146}
3147
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003148bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003149 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003150 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00003151 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
3152 isl_set_free(RuntimeCheckContext);
3153 return IsFeasible;
3154}
3155
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003156static std::string toString(AssumptionKind Kind) {
3157 switch (Kind) {
3158 case ALIASING:
3159 return "No-aliasing";
3160 case INBOUNDS:
3161 return "Inbounds";
3162 case WRAPPING:
3163 return "No-overflows";
3164 case ERRORBLOCK:
3165 return "No-error";
3166 case INFINITELOOP:
3167 return "Finite loop";
3168 case INVARIANTLOAD:
3169 return "Invariant load";
3170 case DELINEARIZATION:
3171 return "Delinearization";
Tobias Grosser75dc40c2015-12-20 13:31:48 +00003172 case ERROR_DOMAINCONJUNCTS:
3173 return "Low number of domain conjuncts";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003174 }
3175 llvm_unreachable("Unknown AssumptionKind!");
3176}
3177
3178void Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3179 DebugLoc Loc) {
3180 if (isl_set_is_subset(Context, Set))
3181 return;
3182
3183 if (isl_set_is_subset(AssumedContext, Set))
3184 return;
3185
3186 auto &F = *getRegion().getEntry()->getParent();
3187 std::string Msg = toString(Kind) + " assumption:\t" + stringFromIslObj(Set);
3188 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
3189}
3190
3191void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
3192 DebugLoc Loc) {
3193 trackAssumption(Kind, Set, Loc);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003194 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003195
Johannes Doerfert9d7899e2015-11-11 20:01:31 +00003196 int NSets = isl_set_n_basic_set(AssumedContext);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003197 if (NSets >= MaxDisjunctsAssumed) {
3198 isl_space *Space = isl_set_get_space(AssumedContext);
3199 isl_set_free(AssumedContext);
Tobias Grossere19fca42015-11-11 20:21:39 +00003200 AssumedContext = isl_set_empty(Space);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003201 }
3202
Tobias Grosser7b50bee2014-11-25 10:51:12 +00003203 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003204}
3205
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003206void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
3207 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc);
3208}
3209
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003210__isl_give isl_set *Scop::getBoundaryContext() const {
3211 return isl_set_copy(BoundaryContext);
3212}
3213
Tobias Grosser75805372011-04-29 06:27:02 +00003214void Scop::printContext(raw_ostream &OS) const {
3215 OS << "Context:\n";
3216
3217 if (!Context) {
3218 OS.indent(4) << "n/a\n\n";
3219 return;
3220 }
3221
3222 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003223
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003224 OS.indent(4) << "Assumed Context:\n";
3225 if (!AssumedContext) {
3226 OS.indent(4) << "n/a\n\n";
3227 return;
3228 }
3229
3230 OS.indent(4) << getAssumedContextStr() << "\n";
3231
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003232 OS.indent(4) << "Boundary Context:\n";
3233 if (!BoundaryContext) {
3234 OS.indent(4) << "n/a\n\n";
3235 return;
3236 }
3237
3238 OS.indent(4) << getBoundaryContextStr() << "\n";
3239
Tobias Grosser083d3d32014-06-28 08:59:45 +00003240 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00003241 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00003242 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
3243 }
Tobias Grosser75805372011-04-29 06:27:02 +00003244}
3245
Johannes Doerfertb164c792014-09-18 11:17:17 +00003246void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003247 int noOfGroups = 0;
3248 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003249 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003250 noOfGroups += 1;
3251 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003252 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003253 }
3254
Tobias Grosserbb853c22015-07-25 12:31:03 +00003255 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003256 if (MinMaxAliasGroups.empty()) {
3257 OS.indent(8) << "n/a\n";
3258 return;
3259 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003260
Tobias Grosserbb853c22015-07-25 12:31:03 +00003261 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003262
3263 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003264 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003265 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003266 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003267 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3268 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003269 }
3270 OS << " ]]\n";
3271 }
3272
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003273 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003274 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003275 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003276 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003277 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3278 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003279 }
3280 OS << " ]]\n";
3281 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003282 }
3283}
3284
Tobias Grosser75805372011-04-29 06:27:02 +00003285void Scop::printStatements(raw_ostream &OS) const {
3286 OS << "Statements {\n";
3287
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003288 for (const ScopStmt &Stmt : *this)
3289 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003290
3291 OS.indent(4) << "}\n";
3292}
3293
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003294void Scop::printArrayInfo(raw_ostream &OS) const {
3295 OS << "Arrays {\n";
3296
Tobias Grosserab671442015-05-23 05:58:27 +00003297 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003298 Array.second->print(OS);
3299
3300 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003301
3302 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3303
3304 for (auto &Array : arrays())
3305 Array.second->print(OS, /* SizeAsPwAff */ true);
3306
3307 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003308}
3309
Tobias Grosser75805372011-04-29 06:27:02 +00003310void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00003311 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
3312 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003313 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003314 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003315 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003316 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003317 const auto &MAs = std::get<1>(IAClass);
3318 if (MAs.empty()) {
3319 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003320 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003321 MAs.front()->print(OS);
3322 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003323 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003324 }
3325 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003326 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003327 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003328 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003329 printStatements(OS.indent(4));
3330}
3331
3332void Scop::dump() const { print(dbgs()); }
3333
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003334isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00003335
Johannes Doerfertcef616f2015-09-15 22:49:04 +00003336__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
3337 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003338}
3339
Tobias Grosser808cd692015-07-14 09:33:13 +00003340__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003341 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003342
Tobias Grosser808cd692015-07-14 09:33:13 +00003343 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003344 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003345
3346 return Domain;
3347}
3348
Tobias Grossere5a35142015-11-12 14:07:09 +00003349__isl_give isl_union_map *
3350Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3351 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003352
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003353 for (ScopStmt &Stmt : *this) {
3354 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003355 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003356 continue;
3357
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003358 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003359 isl_map *AccessDomain = MA->getAccessRelation();
3360 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003361 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003362 }
3363 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003364 return isl_union_map_coalesce(Accesses);
3365}
3366
3367__isl_give isl_union_map *Scop::getMustWrites() {
3368 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003369}
3370
3371__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003372 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003373}
3374
Tobias Grosser37eb4222014-02-20 21:43:54 +00003375__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003376 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003377}
3378
3379__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003380 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003381}
3382
Tobias Grosser2ac23382015-11-12 14:07:13 +00003383__isl_give isl_union_map *Scop::getAccesses() {
3384 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3385}
3386
Tobias Grosser808cd692015-07-14 09:33:13 +00003387__isl_give isl_union_map *Scop::getSchedule() const {
3388 auto Tree = getScheduleTree();
3389 auto S = isl_schedule_get_map(Tree);
3390 isl_schedule_free(Tree);
3391 return S;
3392}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003393
Tobias Grosser808cd692015-07-14 09:33:13 +00003394__isl_give isl_schedule *Scop::getScheduleTree() const {
3395 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3396 getDomains());
3397}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003398
Tobias Grosser808cd692015-07-14 09:33:13 +00003399void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3400 auto *S = isl_schedule_from_domain(getDomains());
3401 S = isl_schedule_insert_partial_schedule(
3402 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3403 isl_schedule_free(Schedule);
3404 Schedule = S;
3405}
3406
3407void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3408 isl_schedule_free(Schedule);
3409 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003410}
3411
3412bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3413 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003414 for (ScopStmt &Stmt : *this) {
3415 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003416 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3417 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3418
3419 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3420 isl_union_set_free(StmtDomain);
3421 isl_union_set_free(NewStmtDomain);
3422 continue;
3423 }
3424
3425 Changed = true;
3426
3427 isl_union_set_free(StmtDomain);
3428 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3429
3430 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003431 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003432 isl_union_set_free(NewStmtDomain);
3433 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003434 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003435 }
3436 isl_union_set_free(Domain);
3437 return Changed;
3438}
3439
Tobias Grosser75805372011-04-29 06:27:02 +00003440ScalarEvolution *Scop::getSE() const { return SE; }
3441
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003442bool Scop::isIgnored(RegionNode *RN, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003443 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Michael Krusea902ba62015-12-13 19:21:45 +00003444 ScopStmt *Stmt = getStmtForRegionNode(RN);
3445
3446 // If there is no stmt, then it already has been removed.
3447 if (!Stmt)
3448 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00003449
Johannes Doerfertf5673802015-10-01 23:48:18 +00003450 // Check if there are accesses contained.
Michael Krusea902ba62015-12-13 19:21:45 +00003451 if (Stmt->isEmpty())
Johannes Doerfertf5673802015-10-01 23:48:18 +00003452 return true;
3453
3454 // Check for reachability via non-error blocks.
3455 if (!DomainMap.count(BB))
3456 return true;
3457
3458 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003459 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003460 return true;
3461
3462 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003463}
3464
Tobias Grosser808cd692015-07-14 09:33:13 +00003465struct MapToDimensionDataTy {
3466 int N;
3467 isl_union_pw_multi_aff *Res;
3468};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003469
Tobias Grosser808cd692015-07-14 09:33:13 +00003470// @brief Create a function that maps the elements of 'Set' to its N-th
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003471// dimension and add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00003472//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003473// @param Set The input set.
3474// @param User->N The dimension to map to.
3475// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00003476//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003477// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00003478static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3479 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3480 int Dim;
3481 isl_space *Space;
3482 isl_pw_multi_aff *PMA;
3483
3484 Dim = isl_set_dim(Set, isl_dim_set);
3485 Space = isl_set_get_space(Set);
3486 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3487 Dim - Data->N);
3488 if (Data->N > 1)
3489 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3490 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3491
3492 isl_set_free(Set);
3493
3494 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003495}
3496
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003497// @brief Create an isl_multi_union_aff that defines an identity mapping
3498// from the elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003499//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003500// # Example:
3501//
3502// Domain: { A[i,j]; B[i,j,k] }
3503// N: 1
3504//
3505// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
3506//
3507// @param USet A union set describing the elements for which to generate a
3508// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00003509// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003510// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003511static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003512mapToDimension(__isl_take isl_union_set *USet, int N) {
3513 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00003514 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003515 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003516
Tobias Grosser808cd692015-07-14 09:33:13 +00003517 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00003518
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003519 auto *Space = isl_union_set_get_space(USet);
3520 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00003521
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003522 Data = {N, PwAff};
3523
3524 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
3525
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00003526 (void)Res;
3527
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003528 assert(Res == isl_stat_ok);
3529
3530 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00003531 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3532}
3533
Tobias Grosser316b5b22015-11-11 19:28:14 +00003534void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003535 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003536 Stmts.emplace_back(*this, *BB);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003537 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003538 StmtMap[BB] = Stmt;
3539 } else {
3540 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003541 Stmts.emplace_back(*this, *R);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003542 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003543 for (BasicBlock *BB : R->blocks())
3544 StmtMap[BB] = Stmt;
3545 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003546}
3547
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003548void Scop::buildSchedule(ScopDetection &SD, LoopInfo &LI) {
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003549 Loop *L = getLoopSurroundingRegion(getRegion(), LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003550 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003551 buildSchedule(getRegion().getNode(), LoopStack, SD, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003552 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
3553 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003554}
3555
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003556/// To generate a schedule for the elements in a Region we traverse the Region
3557/// in reverse-post-order and add the contained RegionNodes in traversal order
3558/// to the schedule of the loop that is currently at the top of the LoopStack.
3559/// For loop-free codes, this results in a correct sequential ordering.
3560///
3561/// Example:
3562/// bb1(0)
3563/// / \.
3564/// bb2(1) bb3(2)
3565/// \ / \.
3566/// bb4(3) bb5(4)
3567/// \ /
3568/// bb6(5)
3569///
3570/// Including loops requires additional processing. Whenever a loop header is
3571/// encountered, the corresponding loop is added to the @p LoopStack. Starting
3572/// from an empty schedule, we first process all RegionNodes that are within
3573/// this loop and complete the sequential schedule at this loop-level before
3574/// processing about any other nodes. To implement this
3575/// loop-nodes-first-processing, the reverse post-order traversal is
3576/// insufficient. Hence, we additionally check if the traversal yields
3577/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
3578/// These region-nodes are then queue and only traverse after the all nodes
3579/// within the current loop have been processed.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003580void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, ScopDetection &SD,
3581 LoopInfo &LI) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003582 Loop *OuterScopLoop = getLoopSurroundingRegion(getRegion(), LI);
3583
3584 ReversePostOrderTraversal<Region *> RTraversal(R);
3585 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
3586 std::deque<RegionNode *> DelayList;
3587 bool LastRNWaiting = false;
3588
3589 // Iterate over the region @p R in reverse post-order but queue
3590 // sub-regions/blocks iff they are not part of the last encountered but not
3591 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
3592 // that we queued the last sub-region/block from the reverse post-order
3593 // iterator. If it is set we have to explore the next sub-region/block from
3594 // the iterator (if any) to guarantee progress. If it is not set we first try
3595 // the next queued sub-region/blocks.
3596 while (!WorkList.empty() || !DelayList.empty()) {
3597 RegionNode *RN;
3598
3599 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
3600 RN = WorkList.front();
3601 WorkList.pop_front();
3602 LastRNWaiting = false;
3603 } else {
3604 RN = DelayList.front();
3605 DelayList.pop_front();
3606 }
3607
3608 Loop *L = getRegionNodeLoop(RN, LI);
3609 if (!getRegion().contains(L))
3610 L = OuterScopLoop;
3611
3612 Loop *LastLoop = LoopStack.back().L;
3613 if (LastLoop != L) {
3614 if (!LastLoop->contains(L)) {
3615 LastRNWaiting = true;
3616 DelayList.push_back(RN);
3617 continue;
3618 }
3619 LoopStack.push_back({L, nullptr, 0});
3620 }
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003621 buildSchedule(RN, LoopStack, SD, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003622 }
3623
3624 return;
3625}
3626
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003627void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003628 ScopDetection &SD, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00003629
Tobias Grosser8362c262016-01-06 15:30:06 +00003630 if (RN->isSubRegion()) {
3631 auto *LocalRegion = RN->getNodeAs<Region>();
3632 if (!SD.isNonAffineSubRegion(LocalRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003633 buildSchedule(LocalRegion, LoopStack, SD, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00003634 return;
3635 }
3636 }
Michael Kruse046dde42015-08-10 13:01:57 +00003637
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003638 auto &LoopData = LoopStack.back();
3639 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00003640
Tobias Grosserc9abde82016-01-23 20:23:06 +00003641 if (auto *Stmt = getStmtForRegionNode(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00003642 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3643 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003644 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00003645 }
3646
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003647 // Check if we just processed the last node in this loop. If we did, finalize
3648 // the loop by:
3649 //
3650 // - adding new schedule dimensions
3651 // - folding the resulting schedule into the parent loop schedule
3652 // - dropping the loop schedule from the LoopStack.
3653 //
3654 // Then continue to check surrounding loops, which might also have been
3655 // completed by this node.
3656 while (LoopData.L &&
3657 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
3658 auto Schedule = LoopData.Schedule;
3659 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00003660
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003661 LoopStack.pop_back();
3662 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00003663
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003664 if (Schedule) {
3665 auto *Domain = isl_schedule_get_domain(Schedule);
3666 auto *MUPA = mapToDimension(Domain, LoopStack.size());
3667 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
3668 NextLoopData.Schedule =
3669 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003670 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003671
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003672 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
3673 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00003674 }
Tobias Grosser75805372011-04-29 06:27:02 +00003675}
3676
Johannes Doerfert7c494212014-10-31 23:13:39 +00003677ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003678 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003679 if (StmtMapIt == StmtMap.end())
3680 return nullptr;
3681 return StmtMapIt->second;
3682}
3683
Michael Krusea902ba62015-12-13 19:21:45 +00003684ScopStmt *Scop::getStmtForRegionNode(RegionNode *RN) const {
3685 return getStmtForBasicBlock(getRegionNodeBasicBlock(RN));
3686}
3687
Johannes Doerfert96425c22015-08-30 21:13:53 +00003688int Scop::getRelativeLoopDepth(const Loop *L) const {
3689 Loop *OuterLoop =
3690 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3691 if (!OuterLoop)
3692 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003693 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3694}
3695
Michael Krused868b5d2015-09-10 15:25:24 +00003696void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003697 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003698
3699 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3700 // true, are not modeled as ordinary PHI nodes as they are not part of the
3701 // region. However, we model the operands in the predecessor blocks that are
3702 // part of the region as regular scalar accesses.
3703
3704 // If we can synthesize a PHI we can skip it, however only if it is in
3705 // the region. If it is not it can only be in the exit block of the region.
3706 // In this case we model the operands but not the PHI itself.
3707 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3708 return;
3709
3710 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3711 // detection. Hence, the PHI is a load of a new memory location in which the
3712 // incoming value was written at the end of the incoming basic block.
3713 bool OnlyNonAffineSubRegionOperands = true;
3714 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3715 Value *Op = PHI->getIncomingValue(u);
3716 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3717
3718 // Do not build scalar dependences inside a non-affine subregion.
3719 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3720 continue;
3721
3722 OnlyNonAffineSubRegionOperands = false;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00003723 ensurePHIWrite(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003724 }
3725
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003726 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3727 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003728 }
3729}
3730
Michael Kruse2e02d562016-02-06 09:19:40 +00003731void ScopInfo::buildScalarDependences(Instruction *Inst) {
3732 assert(!isa<PHINode>(Inst));
Michael Kruse7bf39442015-09-10 12:46:52 +00003733
Michael Kruse2e02d562016-02-06 09:19:40 +00003734 // Pull-in required operands.
3735 for (Use &Op : Inst->operands())
3736 ensureValueRead(Op.get(), Inst->getParent());
3737}
Michael Kruse7bf39442015-09-10 12:46:52 +00003738
Michael Kruse2e02d562016-02-06 09:19:40 +00003739void ScopInfo::buildEscapingDependences(Instruction *Inst) {
3740 Region *R = &scop->getRegion();
Michael Kruse7bf39442015-09-10 12:46:52 +00003741
Michael Kruse2e02d562016-02-06 09:19:40 +00003742 // Check for uses of this instruction outside the scop. Because we do not
3743 // iterate over such instructions and therefore did not "ensure" the existence
3744 // of a write, we must determine such use here.
3745 for (Use &U : Inst->uses()) {
3746 Instruction *UI = dyn_cast<Instruction>(U.getUser());
3747 if (!UI)
Michael Kruse7bf39442015-09-10 12:46:52 +00003748 continue;
3749
Michael Kruse2e02d562016-02-06 09:19:40 +00003750 BasicBlock *UseParent = getUseBlock(U);
3751 BasicBlock *UserParent = UI->getParent();
Michael Kruse7bf39442015-09-10 12:46:52 +00003752
Michael Kruse2e02d562016-02-06 09:19:40 +00003753 // An escaping value is either used by an instruction not within the scop,
3754 // or (when the scop region's exit needs to be simplified) by a PHI in the
3755 // scop's exit block. This is because region simplification before code
3756 // generation inserts new basic blocks before the PHI such that its incoming
3757 // blocks are not in the scop anymore.
3758 if (!R->contains(UseParent) ||
3759 (isa<PHINode>(UI) && UserParent == R->getExit() &&
3760 R->getExitingBlock())) {
3761 // At least one escaping use found.
3762 ensureValueWrite(Inst);
3763 break;
Michael Kruse7bf39442015-09-10 12:46:52 +00003764 }
3765 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003766}
3767
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003768bool ScopInfo::buildAccessMultiDimFixed(
Michael Kruse70131d32016-01-27 17:09:17 +00003769 MemAccInst Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003770 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3771 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse70131d32016-01-27 17:09:17 +00003772 Value *Val = Inst.getValueOperand();
3773 Type *SizeType = Val->getType();
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003774 unsigned ElementSize = DL->getTypeAllocSize(SizeType);
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003775 Value *Address = Inst.getPointerOperand();
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003776 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003777 const SCEVUnknown *BasePointer =
3778 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003779 enum MemoryAccess::AccessType Type =
3780 Inst.isLoad() ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003781
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003782 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3783 auto NewAddress = Address;
3784 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3785 auto Src = BitCast->getOperand(0);
3786 auto SrcTy = Src->getType();
3787 auto DstTy = BitCast->getType();
3788 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3789 NewAddress = Src;
3790 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003791
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003792 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3793 std::vector<const SCEV *> Subscripts;
3794 std::vector<int> Sizes;
3795 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3796 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003797
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003798 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003799
Johannes Doerfert09e36972015-10-07 20:17:36 +00003800 for (auto Subscript : Subscripts) {
3801 InvariantLoadsSetTy AccessILS;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003802 if (!isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS))
3803 return false;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003804
3805 for (LoadInst *LInst : AccessILS)
3806 if (!ScopRIL.count(LInst))
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003807 return false;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003808 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003809
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003810 if (Sizes.size() > 0) {
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003811 for (auto V : Sizes)
3812 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3813 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003814
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003815 addArrayAccess(Inst, Type, BasePointer->getValue(), ElementSize, true,
Tobias Grossera535dff2015-12-13 19:59:01 +00003816 Subscripts, SizesSCEV, Val);
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003817 return true;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003818 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003819 }
3820 }
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003821 return false;
3822}
3823
3824bool ScopInfo::buildAccessMultiDimParam(
3825 MemAccInst Inst, Loop *L, Region *R,
3826 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
Hongbin Zheng22623202016-02-15 00:20:58 +00003827 const InvariantLoadsSetTy &ScopRIL, const MapInsnToMemAcc &InsnToMemAcc) {
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003828 Value *Address = Inst.getPointerOperand();
3829 Value *Val = Inst.getValueOperand();
3830 Type *SizeType = Val->getType();
3831 unsigned ElementSize = DL->getTypeAllocSize(SizeType);
3832 enum MemoryAccess::AccessType Type =
3833 Inst.isLoad() ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
3834
3835 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
3836 const SCEVUnknown *BasePointer =
3837 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3838
3839 assert(BasePointer && "Could not find base pointer");
3840 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003841
Michael Kruse7bf39442015-09-10 12:46:52 +00003842 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003843 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003844 std::vector<const SCEV *> Sizes(
3845 AccItr->second.Shape->DelinearizedSizes.begin(),
3846 AccItr->second.Shape->DelinearizedSizes.end());
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003847 // Remove the element size. This information is already provided by the
Tobias Grosserd840fc72016-02-04 13:18:42 +00003848 // ElementSize parameter. In case the element size of this access and the
3849 // element size used for delinearization differs the delinearization is
3850 // incorrect. Hence, we invalidate the scop.
3851 //
3852 // TODO: Handle delinearization with differing element sizes.
3853 auto DelinearizedSize =
3854 cast<SCEVConstant>(Sizes.back())->getAPInt().getSExtValue();
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003855 Sizes.pop_back();
Tobias Grosserd840fc72016-02-04 13:18:42 +00003856 if (ElementSize != DelinearizedSize)
3857 scop->invalidate(DELINEARIZATION, Inst.getDebugLoc());
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003858
3859 addArrayAccess(Inst, Type, BasePointer->getValue(), ElementSize, true,
3860 AccItr->second.DelinearizedSubscripts, Sizes, Val);
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003861 return true;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003862 }
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003863 return false;
3864}
3865
3866void ScopInfo::buildAccessSingleDim(
3867 MemAccInst Inst, Loop *L, Region *R,
3868 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3869 const InvariantLoadsSetTy &ScopRIL) {
3870 Value *Address = Inst.getPointerOperand();
3871 Value *Val = Inst.getValueOperand();
3872 Type *SizeType = Val->getType();
3873 unsigned ElementSize = DL->getTypeAllocSize(SizeType);
3874 enum MemoryAccess::AccessType Type =
3875 Inst.isLoad() ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
3876
3877 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
3878 const SCEVUnknown *BasePointer =
3879 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3880
3881 assert(BasePointer && "Could not find base pointer");
3882 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
Michael Kruse7bf39442015-09-10 12:46:52 +00003883
3884 // Check if the access depends on a loop contained in a non-affine subregion.
3885 bool isVariantInNonAffineLoop = false;
3886 if (BoxedLoops) {
3887 SetVector<const Loop *> Loops;
3888 findLoops(AccessFunction, Loops);
3889 for (const Loop *L : Loops)
3890 if (BoxedLoops->count(L))
3891 isVariantInNonAffineLoop = true;
3892 }
3893
Johannes Doerfert09e36972015-10-07 20:17:36 +00003894 InvariantLoadsSetTy AccessILS;
3895 bool IsAffine =
3896 !isVariantInNonAffineLoop &&
3897 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3898
3899 for (LoadInst *LInst : AccessILS)
3900 if (!ScopRIL.count(LInst))
3901 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003902
Michael Krusee2bccbb2015-09-18 19:59:43 +00003903 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3904 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003905
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003906 addArrayAccess(Inst, Type, BasePointer->getValue(), ElementSize, IsAffine,
3907 {AccessFunction}, {}, Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003908}
3909
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003910void ScopInfo::buildMemoryAccess(
3911 MemAccInst Inst, Loop *L, Region *R,
3912 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
Hongbin Zheng22623202016-02-15 00:20:58 +00003913 const InvariantLoadsSetTy &ScopRIL, const MapInsnToMemAcc &InsnToMemAcc) {
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003914
3915 if (buildAccessMultiDimFixed(Inst, L, R, BoxedLoops, ScopRIL))
3916 return;
3917
Hongbin Zheng22623202016-02-15 00:20:58 +00003918 if (buildAccessMultiDimParam(Inst, L, R, BoxedLoops, ScopRIL, InsnToMemAcc))
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003919 return;
3920
3921 buildAccessSingleDim(Inst, L, R, BoxedLoops, ScopRIL);
3922}
3923
Hongbin Zheng22623202016-02-15 00:20:58 +00003924void ScopInfo::buildAccessFunctions(Region &R, Region &SR,
3925 const MapInsnToMemAcc &InsnToMemAcc) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003926
3927 if (SD->isNonAffineSubRegion(&SR, &R)) {
3928 for (BasicBlock *BB : SR.blocks())
Hongbin Zheng22623202016-02-15 00:20:58 +00003929 buildAccessFunctions(R, *BB, InsnToMemAcc, &SR);
Michael Kruse7bf39442015-09-10 12:46:52 +00003930 return;
3931 }
3932
3933 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3934 if (I->isSubRegion())
Hongbin Zheng22623202016-02-15 00:20:58 +00003935 buildAccessFunctions(R, *I->getNodeAs<Region>(), InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00003936 else
Hongbin Zheng22623202016-02-15 00:20:58 +00003937 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>(), InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00003938}
3939
Johannes Doerferta8781032016-02-02 14:14:40 +00003940void ScopInfo::buildStmts(Region &R, Region &SR) {
Michael Krusecac948e2015-10-02 13:53:07 +00003941
Johannes Doerferta8781032016-02-02 14:14:40 +00003942 if (SD->isNonAffineSubRegion(&SR, &R)) {
Michael Krusecac948e2015-10-02 13:53:07 +00003943 scop->addScopStmt(nullptr, &SR);
3944 return;
3945 }
3946
3947 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3948 if (I->isSubRegion())
Johannes Doerferta8781032016-02-02 14:14:40 +00003949 buildStmts(R, *I->getNodeAs<Region>());
Michael Krusecac948e2015-10-02 13:53:07 +00003950 else
3951 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
3952}
3953
Michael Krused868b5d2015-09-10 15:25:24 +00003954void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
Hongbin Zheng22623202016-02-15 00:20:58 +00003955 const MapInsnToMemAcc &InsnToMemAcc,
Michael Krused868b5d2015-09-10 15:25:24 +00003956 Region *NonAffineSubRegion,
3957 bool IsExitBlock) {
Tobias Grosser910cf262015-11-11 20:15:49 +00003958 // We do not build access functions for error blocks, as they may contain
3959 // instructions we can not model.
Johannes Doerfertc36d39b2016-02-02 14:14:20 +00003960 if (isErrorBlock(BB, R, *LI, *DT) && !IsExitBlock)
Tobias Grosser910cf262015-11-11 20:15:49 +00003961 return;
3962
Michael Kruse7bf39442015-09-10 12:46:52 +00003963 Loop *L = LI->getLoopFor(&BB);
3964
3965 // The set of loops contained in non-affine subregions that are part of R.
3966 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3967
Johannes Doerfert09e36972015-10-07 20:17:36 +00003968 // The set of loads that are required to be invariant.
3969 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
3970
Michael Kruse2e02d562016-02-06 09:19:40 +00003971 for (Instruction &Inst : BB) {
3972 PHINode *PHI = dyn_cast<PHINode>(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003973 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003974 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003975
3976 // For the exit block we stop modeling after the last PHI node.
3977 if (!PHI && IsExitBlock)
3978 break;
3979
Johannes Doerfert09e36972015-10-07 20:17:36 +00003980 // TODO: At this point we only know that elements of ScopRIL have to be
3981 // invariant and will be hoisted for the SCoP to be processed. Though,
3982 // there might be other invariant accesses that will be hoisted and
3983 // that would allow to make a non-affine access affine.
Michael Kruse70131d32016-01-27 17:09:17 +00003984 if (auto MemInst = MemAccInst::dyn_cast(Inst))
Hongbin Zheng22623202016-02-15 00:20:58 +00003985 buildMemoryAccess(MemInst, L, &R, BoxedLoops, ScopRIL, InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00003986
Michael Kruse2e02d562016-02-06 09:19:40 +00003987 if (isIgnoredIntrinsic(&Inst))
Michael Kruse7bf39442015-09-10 12:46:52 +00003988 continue;
3989
Michael Kruse2e02d562016-02-06 09:19:40 +00003990 if (!PHI)
3991 buildScalarDependences(&Inst);
3992 if (!IsExitBlock)
3993 buildEscapingDependences(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003994 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003995}
Michael Kruse7bf39442015-09-10 12:46:52 +00003996
Michael Kruseee6a4fc2016-01-26 13:33:27 +00003997MemoryAccess *ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3998 MemoryAccess::AccessType Type,
3999 Value *BaseAddress, unsigned ElemBytes,
4000 bool Affine, Value *AccessValue,
4001 ArrayRef<const SCEV *> Subscripts,
4002 ArrayRef<const SCEV *> Sizes,
4003 ScopArrayInfo::MemoryKind Kind) {
Michael Krusecac948e2015-10-02 13:53:07 +00004004 ScopStmt *Stmt = scop->getStmtForBasicBlock(BB);
4005
4006 // Do not create a memory access for anything not in the SCoP. It would be
4007 // ignored anyway.
4008 if (!Stmt)
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004009 return nullptr;
Michael Krusecac948e2015-10-02 13:53:07 +00004010
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00004011 AccFuncSetType &AccList = scop->getOrCreateAccessFunctions(BB);
Michael Krusee2bccbb2015-09-18 19:59:43 +00004012 Value *BaseAddr = BaseAddress;
4013 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
4014
Tobias Grosserf4f68702015-12-14 15:05:37 +00004015 bool isKnownMustAccess = false;
4016
4017 // Accesses in single-basic block statements are always excuted.
4018 if (Stmt->isBlockStmt())
4019 isKnownMustAccess = true;
4020
4021 if (Stmt->isRegionStmt()) {
4022 // Accesses that dominate the exit block of a non-affine region are always
4023 // executed. In non-affine regions there may exist MK_Values that do not
4024 // dominate the exit. MK_Values will always dominate the exit and MK_PHIs
4025 // only if there is at most one PHI_WRITE in the non-affine region.
4026 if (DT->dominates(BB, Stmt->getRegion()->getExit()))
4027 isKnownMustAccess = true;
4028 }
4029
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004030 // Non-affine PHI writes do not "happen" at a particular instruction, but
4031 // after exiting the statement. Therefore they are guaranteed execute and
4032 // overwrite the old value.
4033 if (Kind == ScopArrayInfo::MK_PHI || Kind == ScopArrayInfo::MK_ExitPHI)
4034 isKnownMustAccess = true;
4035
Tobias Grosserf4f68702015-12-14 15:05:37 +00004036 if (!isKnownMustAccess && Type == MemoryAccess::MUST_WRITE)
Michael Krusecac948e2015-10-02 13:53:07 +00004037 Type = MemoryAccess::MAY_WRITE;
4038
Tobias Grosserf1bfd752015-11-05 20:15:37 +00004039 AccList.emplace_back(Stmt, Inst, Type, BaseAddress, ElemBytes, Affine,
Tobias Grossera535dff2015-12-13 19:59:01 +00004040 Subscripts, Sizes, AccessValue, Kind, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00004041 Stmt->addAccess(&AccList.back());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004042 return &AccList.back();
Michael Kruse7bf39442015-09-10 12:46:52 +00004043}
4044
Michael Kruse70131d32016-01-27 17:09:17 +00004045void ScopInfo::addArrayAccess(MemAccInst MemAccInst,
Tobias Grossera535dff2015-12-13 19:59:01 +00004046 MemoryAccess::AccessType Type, Value *BaseAddress,
4047 unsigned ElemBytes, bool IsAffine,
4048 ArrayRef<const SCEV *> Subscripts,
4049 ArrayRef<const SCEV *> Sizes,
4050 Value *AccessValue) {
Michael Kruse70131d32016-01-27 17:09:17 +00004051 assert(MemAccInst.isLoad() == (Type == MemoryAccess::READ));
4052 addMemoryAccess(MemAccInst.getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00004053 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00004054 ScopArrayInfo::MK_Array);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004055}
Michael Kruse436db622016-01-26 13:33:10 +00004056void ScopInfo::ensureValueWrite(Instruction *Value) {
4057 ScopStmt *Stmt = scop->getStmtForBasicBlock(Value->getParent());
4058
4059 // Value not defined within this SCoP.
4060 if (!Stmt)
4061 return;
4062
4063 // Do not process further if the value is already written.
4064 if (Stmt->lookupValueWriteOf(Value))
4065 return;
4066
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004067 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
4068 true, Value, ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004069 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004070}
Michael Krusead28e5a2016-01-26 13:33:15 +00004071void ScopInfo::ensureValueRead(Value *Value, BasicBlock *UserBB) {
Michael Krusefd463082016-01-27 22:51:56 +00004072
Michael Kruse2e02d562016-02-06 09:19:40 +00004073 // There cannot be an "access" for literal constants. BasicBlock references
4074 // (jump destinations) also never change.
4075 if ((isa<Constant>(Value) && !isa<GlobalVariable>(Value)) ||
4076 isa<BasicBlock>(Value))
4077 return;
4078
Michael Krusefd463082016-01-27 22:51:56 +00004079 // If the instruction can be synthesized and the user is in the region we do
4080 // not need to add a value dependences.
4081 Region &ScopRegion = scop->getRegion();
4082 if (canSynthesize(Value, LI, SE, &ScopRegion))
4083 return;
4084
Michael Kruse2e02d562016-02-06 09:19:40 +00004085 // Do not build scalar dependences for required invariant loads as we will
4086 // hoist them later on anyway or drop the SCoP if we cannot.
4087 auto ScopRIL = SD->getRequiredInvariantLoads(&ScopRegion);
4088 if (ScopRIL->count(dyn_cast<LoadInst>(Value)))
4089 return;
4090
4091 // Determine the ScopStmt containing the value's definition and use. There is
4092 // no defining ScopStmt if the value is a function argument, a global value,
4093 // or defined outside the SCoP.
4094 Instruction *ValueInst = dyn_cast<Instruction>(Value);
4095 ScopStmt *ValueStmt =
4096 ValueInst ? scop->getStmtForBasicBlock(ValueInst->getParent()) : nullptr;
4097
Michael Krusead28e5a2016-01-26 13:33:15 +00004098 ScopStmt *UserStmt = scop->getStmtForBasicBlock(UserBB);
4099
4100 // We do not model uses outside the scop.
4101 if (!UserStmt)
4102 return;
4103
Michael Kruse2e02d562016-02-06 09:19:40 +00004104 // Add MemoryAccess for invariant values only if requested.
4105 if (!ModelReadOnlyScalars && !ValueStmt)
4106 return;
4107
4108 // Ignore use-def chains within the same ScopStmt.
4109 if (ValueStmt == UserStmt)
4110 return;
4111
Michael Krusead28e5a2016-01-26 13:33:15 +00004112 // Do not create another MemoryAccess for reloading the value if one already
4113 // exists.
4114 if (UserStmt->lookupValueReadOf(Value))
4115 return;
4116
4117 addMemoryAccess(UserBB, nullptr, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00004118 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004119 ScopArrayInfo::MK_Value);
Michael Kruse2e02d562016-02-06 09:19:40 +00004120 if (ValueInst)
4121 ensureValueWrite(ValueInst);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004122}
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004123void ScopInfo::ensurePHIWrite(PHINode *PHI, BasicBlock *IncomingBlock,
4124 Value *IncomingValue, bool IsExitBlock) {
4125 ScopStmt *IncomingStmt = scop->getStmtForBasicBlock(IncomingBlock);
Michael Kruse2e02d562016-02-06 09:19:40 +00004126 if (!IncomingStmt)
4127 return;
4128
4129 // Take care for the incoming value being available in the incoming block.
4130 // This must be done before the check for multiple PHI writes because multiple
4131 // exiting edges from subregion each can be the effective written value of the
4132 // subregion. As such, all of them must be made available in the subregion
4133 // statement.
4134 ensureValueRead(IncomingValue, IncomingBlock);
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004135
4136 // Do not add more than one MemoryAccess per PHINode and ScopStmt.
4137 if (MemoryAccess *Acc = IncomingStmt->lookupPHIWriteOf(PHI)) {
4138 assert(Acc->getAccessInstruction() == PHI);
4139 Acc->addIncoming(IncomingBlock, IncomingValue);
4140 return;
4141 }
4142
4143 MemoryAccess *Acc = addMemoryAccess(
4144 IncomingStmt->isBlockStmt() ? IncomingBlock
4145 : IncomingStmt->getRegion()->getEntry(),
4146 PHI, MemoryAccess::MUST_WRITE, PHI, 1, true, PHI,
4147 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
4148 IsExitBlock ? ScopArrayInfo::MK_ExitPHI : ScopArrayInfo::MK_PHI);
4149 assert(Acc);
4150 Acc->addIncoming(IncomingBlock, IncomingValue);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004151}
4152void ScopInfo::addPHIReadAccess(PHINode *PHI) {
4153 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00004154 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004155 ScopArrayInfo::MK_PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004156}
4157
Michael Krusedaf66942015-12-13 22:10:37 +00004158void ScopInfo::buildScop(Region &R, AssumptionCache &AC) {
Michael Kruse9d080092015-09-11 21:41:48 +00004159 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004160 scop.reset(new Scop(R, *SE, MaxLoopDepth));
Michael Kruse7bf39442015-09-10 12:46:52 +00004161
Johannes Doerferta8781032016-02-02 14:14:40 +00004162 buildStmts(R, R);
Hongbin Zheng22623202016-02-15 00:20:58 +00004163 buildAccessFunctions(R, R, *SD->getInsnToMemAccMap(&R));
Michael Kruse7bf39442015-09-10 12:46:52 +00004164
4165 // In case the region does not have an exiting block we will later (during
4166 // code generation) split the exit block. This will move potential PHI nodes
4167 // from the current exit block into the new region exiting block. Hence, PHI
4168 // nodes that are at this point not part of the region will be.
4169 // To handle these PHI nodes later we will now model their operands as scalar
4170 // accesses. Note that we do not model anything in the exit block if we have
4171 // an exiting block in the region, as there will not be any splitting later.
4172 if (!R.getExitingBlock())
Hongbin Zheng22623202016-02-15 00:20:58 +00004173 buildAccessFunctions(R, *R.getExit(), *SD->getInsnToMemAccMap(&R), nullptr,
4174 /* IsExitBlock */ true);
Michael Kruse7bf39442015-09-10 12:46:52 +00004175
Hongbin Zheng192f69a2016-02-13 15:12:54 +00004176 scop->init(*AA, AC, *SD, *DT, *LI);
Michael Kruse7bf39442015-09-10 12:46:52 +00004177}
4178
Michael Krused868b5d2015-09-10 15:25:24 +00004179void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00004180 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00004181 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00004182 return;
4183 }
4184
Michael Kruse9d080092015-09-11 21:41:48 +00004185 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00004186}
4187
Hongbin Zhengfec32802016-02-13 15:13:02 +00004188void ScopInfo::clear() { scop.reset(); }
Michael Kruse7bf39442015-09-10 12:46:52 +00004189
4190//===----------------------------------------------------------------------===//
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004191ScopInfo::ScopInfo() : RegionPass(ID) {}
Tobias Grosserb76f38532011-08-20 11:11:25 +00004192
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004193ScopInfo::~ScopInfo() { clear(); }
Tobias Grosserb76f38532011-08-20 11:11:25 +00004194
Tobias Grosser75805372011-04-29 06:27:02 +00004195void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00004196 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00004197 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00004198 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00004199 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4200 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004201 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004202 AU.addRequired<AssumptionCacheTracker>();
Tobias Grosser75805372011-04-29 06:27:02 +00004203 AU.setPreservesAll();
4204}
4205
4206bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00004207 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00004208
Michael Krused868b5d2015-09-10 15:25:24 +00004209 if (!SD->isMaxRegionInScop(*R))
4210 return false;
4211
4212 Function *F = R->getEntry()->getParent();
4213 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4214 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4215 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Johannes Doerferta1f291e2016-02-02 14:15:13 +00004216 DL = &F->getParent()->getDataLayout();
Michael Krusedaf66942015-12-13 22:10:37 +00004217 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004218 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krused868b5d2015-09-10 15:25:24 +00004219
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004220 DebugLoc Beg, End;
4221 getDebugLocations(R, Beg, End);
4222 std::string Msg = "SCoP begins here.";
4223 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg);
4224
Michael Krusedaf66942015-12-13 22:10:37 +00004225 buildScop(*R, AC);
Tobias Grosser75805372011-04-29 06:27:02 +00004226
Tobias Grosserd6a50b32015-05-30 06:26:21 +00004227 DEBUG(scop->print(dbgs()));
4228
Michael Kruseafe06702015-10-02 16:33:27 +00004229 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004230 Msg = "SCoP ends here but was dismissed.";
Hongbin Zhengfec32802016-02-13 15:13:02 +00004231 scop.reset();
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004232 } else {
4233 Msg = "SCoP ends here.";
4234 ++ScopFound;
4235 if (scop->getMaxLoopDepth() > 0)
4236 ++RichScopFound;
Johannes Doerfert43788c52015-08-20 05:58:56 +00004237 }
4238
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004239 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg);
4240
Tobias Grosser75805372011-04-29 06:27:02 +00004241 return false;
4242}
4243
4244char ScopInfo::ID = 0;
4245
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004246Pass *polly::createScopInfoPass() { return new ScopInfo(); }
4247
Tobias Grosser73600b82011-10-08 00:30:40 +00004248INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
4249 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004250 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004251INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004252INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004253INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004254INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004255INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004256INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004257INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00004258INITIALIZE_PASS_END(ScopInfo, "polly-scops",
4259 "Polly - Create polyhedral description of Scops", false,
4260 false)