blob: 2c05b10bffd27c8e75683db04e8158700a9f4a4e [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() {
297 auto ArraySpace = getScopArrayInfo()->getSpace();
298 auto AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
299
300 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
301 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
302 auto DimsMissing = DimsArray - DimsAccess;
303
Tobias Grosserd840fc72016-02-04 13:18:42 +0000304 auto Map = isl_map_from_domain_and_range(
305 isl_set_universe(AccessSpace),
306 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000307
308 for (unsigned i = 0; i < DimsMissing; i++)
309 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
310
311 for (unsigned i = DimsMissing; i < DimsArray; i++)
312 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
313
314 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000315
Tobias Grosserd840fc72016-02-04 13:18:42 +0000316 // Introduce multi-element accesses in case the type loaded by this memory
317 // access is larger than the canonical element type of the array.
318 //
319 // An access ((float *)A)[i] to an array char *A is modeled as
320 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
321 unsigned ArrayElemSize = getScopArrayInfo()->getElemSizeInBytes();
322 if (ElemBytes > ArrayElemSize) {
323 assert(ElemBytes % ArrayElemSize == 0 &&
324 "Loaded element size should be multiple of canonical element size");
325 auto Map = isl_map_from_domain_and_range(
326 isl_set_universe(isl_space_copy(ArraySpace)),
327 isl_set_universe(isl_space_copy(ArraySpace)));
328 for (unsigned i = 0; i < DimsArray - 1; i++)
329 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
330
331 isl_ctx *Ctx;
332 isl_constraint *C;
333 isl_local_space *LS;
334
335 LS = isl_local_space_from_space(isl_map_get_space(Map));
336 Ctx = isl_map_get_ctx(Map);
337 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
338
339 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
340 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
341 C = isl_constraint_set_coefficient_si(C, isl_dim_in,
342 DimsArray - 1 - DimsMissing, Num);
343 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
344 Map = isl_map_add_constraint(Map, C);
345
346 C = isl_constraint_alloc_inequality(LS);
347 C = isl_constraint_set_coefficient_si(C, isl_dim_in,
348 DimsArray - 1 - DimsMissing, -Num);
349 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
350 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
351 Map = isl_map_add_constraint(Map, C);
352 AccessRelation = isl_map_apply_range(AccessRelation, Map);
353 }
354
355 isl_space_free(ArraySpace);
356
Roman Gareev10595a12016-01-08 14:01:59 +0000357 assumeNoOutOfBound();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000358}
359
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000360const std::string
361MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
362 switch (RT) {
363 case MemoryAccess::RT_NONE:
364 llvm_unreachable("Requested a reduction operator string for a memory "
365 "access which isn't a reduction");
366 case MemoryAccess::RT_ADD:
367 return "+";
368 case MemoryAccess::RT_MUL:
369 return "*";
370 case MemoryAccess::RT_BOR:
371 return "|";
372 case MemoryAccess::RT_BXOR:
373 return "^";
374 case MemoryAccess::RT_BAND:
375 return "&";
376 }
377 llvm_unreachable("Unknown reduction type");
378 return "";
379}
380
Johannes Doerfertf6183392014-07-01 20:52:51 +0000381/// @brief Return the reduction type for a given binary operator
382static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
383 const Instruction *Load) {
384 if (!BinOp)
385 return MemoryAccess::RT_NONE;
386 switch (BinOp->getOpcode()) {
387 case Instruction::FAdd:
388 if (!BinOp->hasUnsafeAlgebra())
389 return MemoryAccess::RT_NONE;
390 // Fall through
391 case Instruction::Add:
392 return MemoryAccess::RT_ADD;
393 case Instruction::Or:
394 return MemoryAccess::RT_BOR;
395 case Instruction::Xor:
396 return MemoryAccess::RT_BXOR;
397 case Instruction::And:
398 return MemoryAccess::RT_BAND;
399 case Instruction::FMul:
400 if (!BinOp->hasUnsafeAlgebra())
401 return MemoryAccess::RT_NONE;
402 // Fall through
403 case Instruction::Mul:
404 if (DisableMultiplicativeReductions)
405 return MemoryAccess::RT_NONE;
406 return MemoryAccess::RT_MUL;
407 default:
408 return MemoryAccess::RT_NONE;
409 }
410}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000411
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000412/// @brief Derive the individual index expressions from a GEP instruction
413///
414/// This function optimistically assumes the GEP references into a fixed size
415/// array. If this is actually true, this function returns a list of array
416/// subscript expressions as SCEV as well as a list of integers describing
417/// the size of the individual array dimensions. Both lists have either equal
418/// length of the size list is one element shorter in case there is no known
419/// size available for the outermost array dimension.
420///
421/// @param GEP The GetElementPtr instruction to analyze.
422///
423/// @return A tuple with the subscript expressions and the dimension sizes.
424static std::tuple<std::vector<const SCEV *>, std::vector<int>>
425getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
426 std::vector<const SCEV *> Subscripts;
427 std::vector<int> Sizes;
428
429 Type *Ty = GEP->getPointerOperandType();
430
431 bool DroppedFirstDim = false;
432
Michael Kruse26ed65e2015-09-24 17:32:49 +0000433 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000434
435 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
436
437 if (i == 1) {
438 if (auto PtrTy = dyn_cast<PointerType>(Ty)) {
439 Ty = PtrTy->getElementType();
440 } else if (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
441 Ty = ArrayTy->getElementType();
442 } else {
443 Subscripts.clear();
444 Sizes.clear();
445 break;
446 }
447 if (auto Const = dyn_cast<SCEVConstant>(Expr))
448 if (Const->getValue()->isZero()) {
449 DroppedFirstDim = true;
450 continue;
451 }
452 Subscripts.push_back(Expr);
453 continue;
454 }
455
456 auto ArrayTy = dyn_cast<ArrayType>(Ty);
457 if (!ArrayTy) {
458 Subscripts.clear();
459 Sizes.clear();
460 break;
461 }
462
463 Subscripts.push_back(Expr);
464 if (!(DroppedFirstDim && i == 2))
465 Sizes.push_back(ArrayTy->getNumElements());
466
467 Ty = ArrayTy->getElementType();
468 }
469
470 return std::make_tuple(Subscripts, Sizes);
471}
472
Tobias Grosser75805372011-04-29 06:27:02 +0000473MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000474 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000475 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000476 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000477}
478
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000479const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
480 isl_id *ArrayId = getArrayId();
481 void *User = isl_id_get_user(ArrayId);
482 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
483 isl_id_free(ArrayId);
484 return SAI;
485}
486
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000487__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000488 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
489}
490
Tobias Grosserd840fc72016-02-04 13:18:42 +0000491__isl_give isl_map *MemoryAccess::getAddressFunction() const {
492 return isl_map_lexmin(getAccessRelation());
493}
494
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000495__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
496 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000497 isl_map *Schedule, *ScheduledAccRel;
498 isl_union_set *UDomain;
499
500 UDomain = isl_union_set_from_set(getStatement()->getDomain());
501 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
502 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000503 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000504 return isl_pw_multi_aff_from_map(ScheduledAccRel);
505}
506
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000507__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000508 return isl_map_copy(AccessRelation);
509}
510
Johannes Doerferta99130f2014-10-13 12:58:03 +0000511std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000512 return stringFromIslObj(AccessRelation);
513}
514
Johannes Doerferta99130f2014-10-13 12:58:03 +0000515__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000516 return isl_map_get_space(AccessRelation);
517}
518
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000519__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000520 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000521}
522
Tobias Grosser6f730082015-09-05 07:46:47 +0000523std::string MemoryAccess::getNewAccessRelationStr() const {
524 return stringFromIslObj(NewAccessRelation);
525}
526
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000527__isl_give isl_basic_map *
528MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000529 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000530 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000531
Tobias Grosser084d8f72012-05-29 09:29:44 +0000532 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000533 isl_basic_set_universe(Statement->getDomainSpace()),
534 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000535}
536
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000537// Formalize no out-of-bound access assumption
538//
539// When delinearizing array accesses we optimistically assume that the
540// delinearized accesses do not access out of bound locations (the subscript
541// expression of each array evaluates for each statement instance that is
542// executed to a value that is larger than zero and strictly smaller than the
543// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000544// dimension for which we do not need to assume any upper bound. At this point
545// we formalize this assumption to ensure that at code generation time the
546// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000547//
548// To find the set of constraints necessary to avoid out of bound accesses, we
549// first build the set of data locations that are not within array bounds. We
550// then apply the reverse access relation to obtain the set of iterations that
551// may contain invalid accesses and reduce this set of iterations to the ones
552// that are actually executed by intersecting them with the domain of the
553// statement. If we now project out all loop dimensions, we obtain a set of
554// parameters that may cause statement instances to be executed that may
555// possibly yield out of bound memory accesses. The complement of these
556// constraints is the set of constraints that needs to be assumed to ensure such
557// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000558void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000559 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000560 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000561 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000562 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000563 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
564 isl_pw_aff *Var =
565 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
566 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
567
568 isl_set *DimOutside;
569
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000570 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000571 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000572 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
573 isl_space_dim(Space, isl_dim_set));
574 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
575 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000576
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000577 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000578
579 Outside = isl_set_union(Outside, DimOutside);
580 }
581
582 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
583 Outside = isl_set_intersect(Outside, Statement->getDomain());
584 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000585
586 // Remove divs to avoid the construction of overly complicated assumptions.
587 // Doing so increases the set of parameter combinations that are assumed to
588 // not appear. This is always save, but may make the resulting run-time check
589 // bail out more often than strictly necessary.
590 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000591 Outside = isl_set_complement(Outside);
Michael Krusead28e5a2016-01-26 13:33:15 +0000592 Statement->getParent()->addAssumption(
593 INBOUNDS, Outside,
594 getAccessInstruction() ? getAccessInstruction()->getDebugLoc() : nullptr);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000595 isl_space_free(Space);
596}
597
Johannes Doerferte7044942015-02-24 11:58:30 +0000598void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
599 ScalarEvolution *SE = Statement->getParent()->getSE();
600
Michael Kruse70131d32016-01-27 17:09:17 +0000601 Value *Ptr = MemAccInst(getAccessInstruction()).getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000602 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
603 return;
604
605 auto *PtrSCEV = SE->getSCEV(Ptr);
606 if (isa<SCEVCouldNotCompute>(PtrSCEV))
607 return;
608
609 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
610 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
611 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
612
613 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
614 if (Range.isFullSet())
615 return;
616
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000617 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000618 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000619 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000620 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000621 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000622
623 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000624 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000625
626 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
627 AccessRange =
628 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
629 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
630}
631
Michael Krusee2bccbb2015-09-18 19:59:43 +0000632__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000633 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000634 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000635
636 for (int i = Size - 2; i >= 0; --i) {
637 isl_space *Space;
638 isl_map *MapOne, *MapTwo;
Michael Krusee2bccbb2015-09-18 19:59:43 +0000639 isl_pw_aff *DimSize = Statement->getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000640
641 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
642 isl_pw_aff_free(DimSize);
643 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
644
645 Space = isl_map_get_space(AccessRelation);
646 Space = isl_space_map_from_set(isl_space_range(Space));
647 Space = isl_space_align_params(Space, SpaceSize);
648
649 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
650 isl_id_free(ParamId);
651
652 MapOne = isl_map_universe(isl_space_copy(Space));
653 for (int j = 0; j < Size; ++j)
654 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
655 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
656
657 MapTwo = isl_map_universe(isl_space_copy(Space));
658 for (int j = 0; j < Size; ++j)
659 if (j < i || j > i + 1)
660 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
661
662 isl_local_space *LS = isl_local_space_from_space(Space);
663 isl_constraint *C;
664 C = isl_equality_alloc(isl_local_space_copy(LS));
665 C = isl_constraint_set_constant_si(C, -1);
666 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
667 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
668 MapTwo = isl_map_add_constraint(MapTwo, C);
669 C = isl_equality_alloc(LS);
670 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
671 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
672 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
673 MapTwo = isl_map_add_constraint(MapTwo, C);
674 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
675
676 MapOne = isl_map_union(MapOne, MapTwo);
677 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
678 }
679 return AccessRelation;
680}
681
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000682/// @brief Check if @p Expr is divisible by @p Size.
683static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
684
685 // Only one factor needs to be divisible.
686 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
687 for (auto *FactorExpr : MulExpr->operands())
688 if (isDivisible(FactorExpr, Size, SE))
689 return true;
690 return false;
691 }
692
693 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
694 // to be divisble.
695 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
696 for (auto *OpExpr : NAryExpr->operands())
697 if (!isDivisible(OpExpr, Size, SE))
698 return false;
699 return true;
700 }
701
702 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
703 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
704 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
705 return MulSCEV == Expr;
706}
707
Michael Krusee2bccbb2015-09-18 19:59:43 +0000708void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
709 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000710
Michael Krusee2bccbb2015-09-18 19:59:43 +0000711 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000712 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000713
Michael Krusee2bccbb2015-09-18 19:59:43 +0000714 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000715 // We overapproximate non-affine accesses with a possible access to the
716 // whole array. For read accesses it does not make a difference, if an
717 // access must or may happen. However, for write accesses it is important to
718 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000719 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000720 AccessRelation =
721 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000722
Michael Krusee2bccbb2015-09-18 19:59:43 +0000723 computeBoundsOnAccessRelation(getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000724 return;
725 }
726
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000727 Scop &S = *getStatement()->getParent();
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000728 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000729 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000730
Michael Krusee2bccbb2015-09-18 19:59:43 +0000731 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
732 isl_pw_aff *Affine = Statement->getPwAff(Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000733
Sebastian Pop422e33f2014-06-03 18:16:31 +0000734 if (Size == 1) {
735 // For the non delinearized arrays, divide the access function of the last
736 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000737 //
738 // A stride one array access in C expressed as A[i] is expressed in
739 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
740 // two subsequent values of 'i' index two values that are stored next to
741 // each other in memory. By this division we make this characteristic
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000742 // obvious again. However, if the index is not divisible by the element
743 // size we will bail out.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000744 isl_val *v = isl_val_int_from_si(Ctx, getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000745 Affine = isl_pw_aff_scale_down_val(Affine, v);
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000746
747 if (!isDivisible(Subscripts[0], getElemSizeInBytes(), *S.getSE()))
Tobias Grosser8d4f6262015-12-12 09:52:26 +0000748 S.invalidate(ALIGNMENT, AccessInstruction->getDebugLoc());
Sebastian Pop18016682014-04-08 21:20:44 +0000749 }
750
751 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
752
Tobias Grosser79baa212014-04-10 08:38:02 +0000753 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000754 }
755
Tobias Grosser5d51afe2016-02-02 16:46:45 +0000756 if (Sizes.size() >= 1 && !isa<SCEVConstant>(Sizes[0]))
Michael Krusee2bccbb2015-09-18 19:59:43 +0000757 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000758
Tobias Grosser79baa212014-04-10 08:38:02 +0000759 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000760 AccessRelation = isl_map_set_tuple_id(
761 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000762 AccessRelation =
763 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
764
Tobias Grosseraa660a92015-03-30 00:07:50 +0000765 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000766 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000767}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000768
Michael Krusecac948e2015-10-02 13:53:07 +0000769MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000770 AccessType Type, Value *BaseAddress,
771 unsigned ElemBytes, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000772 ArrayRef<const SCEV *> Subscripts,
773 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000774 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
775 : Kind(Kind), AccType(Type), RedType(RT_NONE), Statement(Stmt),
Michael Krusecac948e2015-10-02 13:53:07 +0000776 BaseAddr(BaseAddress), BaseName(BaseName), ElemBytes(ElemBytes),
777 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
778 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000779 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000780 NewAccessRelation(nullptr) {
781
782 std::string IdName = "__polly_array_ref";
783 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
784}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000785
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000786void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000787 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000788 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000789}
790
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000791const std::string MemoryAccess::getReductionOperatorStr() const {
792 return MemoryAccess::getReductionOperatorStr(getReductionType());
793}
794
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000795__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
796
Johannes Doerfertf6183392014-07-01 20:52:51 +0000797raw_ostream &polly::operator<<(raw_ostream &OS,
798 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000799 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000800 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000801 else
802 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000803 return OS;
804}
805
Tobias Grosser75805372011-04-29 06:27:02 +0000806void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000807 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000808 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000809 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000810 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000811 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000812 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000813 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000814 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000815 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000816 break;
817 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000818 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000819 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000820 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000821 if (hasNewAccessRelation())
822 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000823}
824
Tobias Grosser74394f02013-01-14 22:40:23 +0000825void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000826
827// Create a map in the size of the provided set domain, that maps from the
828// one element of the provided set domain to another element of the provided
829// set domain.
830// The mapping is limited to all points that are equal in all but the last
831// dimension and for which the last dimension of the input is strict smaller
832// than the last dimension of the output.
833//
834// getEqualAndLarger(set[i0, i1, ..., iX]):
835//
836// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
837// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
838//
Tobias Grosserf5338802011-10-06 00:03:35 +0000839static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000840 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000841 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000842 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000843
844 // Set all but the last dimension to be equal for the input and output
845 //
846 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
847 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000848 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000849 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000850
851 // Set the last dimension of the input to be strict smaller than the
852 // last dimension of the output.
853 //
854 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000855 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
856 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000857 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000858}
859
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000860__isl_give isl_set *
861MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000862 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000863 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000864 isl_space *Space = isl_space_range(isl_map_get_space(S));
865 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000866
Sebastian Popa00a0292012-12-18 07:46:06 +0000867 S = isl_map_reverse(S);
868 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000869
Sebastian Popa00a0292012-12-18 07:46:06 +0000870 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
871 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
872 NextScatt = isl_map_apply_domain(NextScatt, S);
873 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000874
Sebastian Popa00a0292012-12-18 07:46:06 +0000875 isl_set *Deltas = isl_map_deltas(NextScatt);
876 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000877}
878
Sebastian Popa00a0292012-12-18 07:46:06 +0000879bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000880 int StrideWidth) const {
881 isl_set *Stride, *StrideX;
882 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000883
Sebastian Popa00a0292012-12-18 07:46:06 +0000884 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000885 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000886 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
887 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
888 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
889 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000890 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000891
Tobias Grosser28dd4862012-01-24 16:42:16 +0000892 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000893 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000894
Tobias Grosser28dd4862012-01-24 16:42:16 +0000895 return IsStrideX;
896}
897
Sebastian Popa00a0292012-12-18 07:46:06 +0000898bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
899 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000900}
901
Sebastian Popa00a0292012-12-18 07:46:06 +0000902bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
903 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000904}
905
Tobias Grosser166c4222015-09-05 07:46:40 +0000906void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
907 isl_map_free(NewAccessRelation);
908 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000909}
Tobias Grosser75805372011-04-29 06:27:02 +0000910
911//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000912
Tobias Grosser808cd692015-07-14 09:33:13 +0000913isl_map *ScopStmt::getSchedule() const {
914 isl_set *Domain = getDomain();
915 if (isl_set_is_empty(Domain)) {
916 isl_set_free(Domain);
917 return isl_map_from_aff(
918 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
919 }
920 auto *Schedule = getParent()->getSchedule();
921 Schedule = isl_union_map_intersect_domain(
922 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
923 if (isl_union_map_is_empty(Schedule)) {
924 isl_set_free(Domain);
925 isl_union_map_free(Schedule);
926 return isl_map_from_aff(
927 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
928 }
929 auto *M = isl_map_from_union_map(Schedule);
930 M = isl_map_coalesce(M);
931 M = isl_map_gist_domain(M, Domain);
932 M = isl_map_coalesce(M);
933 return M;
934}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000935
Johannes Doerfert574182d2015-08-12 10:19:50 +0000936__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000937 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
938 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000939}
940
Tobias Grosser37eb4222014-02-20 21:43:54 +0000941void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
942 assert(isl_set_is_subset(NewDomain, Domain) &&
943 "New domain is not a subset of old domain!");
944 isl_set_free(Domain);
945 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000946}
947
Michael Krusecac948e2015-10-02 13:53:07 +0000948void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000949 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +0000950 for (MemoryAccess *Access : MemAccs) {
951 Type *ElementType = Access->getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000952
Tobias Grossera535dff2015-12-13 19:59:01 +0000953 ScopArrayInfo::MemoryKind Ty;
954 if (Access->isPHIKind())
955 Ty = ScopArrayInfo::MK_PHI;
956 else if (Access->isExitPHIKind())
957 Ty = ScopArrayInfo::MK_ExitPHI;
958 else if (Access->isValueKind())
959 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000960 else
Tobias Grossera535dff2015-12-13 19:59:01 +0000961 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000962
Johannes Doerfertadeab372016-02-07 13:57:32 +0000963 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
964 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +0000965 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +0000966 }
967}
968
Michael Krusecac948e2015-10-02 13:53:07 +0000969void ScopStmt::addAccess(MemoryAccess *Access) {
970 Instruction *AccessInst = Access->getAccessInstruction();
971
Michael Kruse58fa3bb2015-12-22 23:25:11 +0000972 if (Access->isArrayKind()) {
973 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
974 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +0000975 } else if (Access->isValueKind() && Access->isWrite()) {
976 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
977 assert(Parent.getStmtForBasicBlock(AccessVal->getParent()) == this);
978 assert(!ValueWrites.lookup(AccessVal));
979
980 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +0000981 } else if (Access->isValueKind() && Access->isRead()) {
982 Value *AccessVal = Access->getAccessValue();
983 assert(!ValueReads.lookup(AccessVal));
984
985 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +0000986 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
987 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
988 assert(!PHIWrites.lookup(PHI));
989
990 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +0000991 }
992
993 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +0000994}
995
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000996void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000997 for (MemoryAccess *MA : *this)
998 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000999
1000 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001001}
1002
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001003/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
1004static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1005 void *User) {
1006 isl_set **BoundedParts = static_cast<isl_set **>(User);
1007 if (isl_basic_set_is_bounded(BSet))
1008 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1009 else
1010 isl_basic_set_free(BSet);
1011 return isl_stat_ok;
1012}
1013
1014/// @brief Return the bounded parts of @p S.
1015static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1016 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1017 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1018 isl_set_free(S);
1019 return BoundedParts;
1020}
1021
1022/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
1023///
1024/// @returns A separation of @p S into first an unbounded then a bounded subset,
1025/// both with regards to the dimension @p Dim.
1026static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1027partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1028
1029 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001030 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001031
1032 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001033 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001034
1035 // Remove dimensions that are greater than Dim as they are not interesting.
1036 assert(NumDimsS >= Dim + 1);
1037 OnlyDimS =
1038 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1039
1040 // Create artificial parametric upper bounds for dimensions smaller than Dim
1041 // as we are not interested in them.
1042 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1043 for (unsigned u = 0; u < Dim; u++) {
1044 isl_constraint *C = isl_inequality_alloc(
1045 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1046 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1047 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1048 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1049 }
1050
1051 // Collect all bounded parts of OnlyDimS.
1052 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1053
1054 // Create the dimensions greater than Dim again.
1055 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1056 NumDimsS - Dim - 1);
1057
1058 // Remove the artificial upper bound parameters again.
1059 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1060
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001061 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001062 return std::make_pair(UnboundedParts, BoundedParts);
1063}
1064
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001065/// @brief Set the dimension Ids from @p From in @p To.
1066static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1067 __isl_take isl_set *To) {
1068 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1069 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1070 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1071 }
1072 return To;
1073}
1074
1075/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001076static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001077 __isl_take isl_pw_aff *L,
1078 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001079 switch (Pred) {
1080 case ICmpInst::ICMP_EQ:
1081 return isl_pw_aff_eq_set(L, R);
1082 case ICmpInst::ICMP_NE:
1083 return isl_pw_aff_ne_set(L, R);
1084 case ICmpInst::ICMP_SLT:
1085 return isl_pw_aff_lt_set(L, R);
1086 case ICmpInst::ICMP_SLE:
1087 return isl_pw_aff_le_set(L, R);
1088 case ICmpInst::ICMP_SGT:
1089 return isl_pw_aff_gt_set(L, R);
1090 case ICmpInst::ICMP_SGE:
1091 return isl_pw_aff_ge_set(L, R);
1092 case ICmpInst::ICMP_ULT:
1093 return isl_pw_aff_lt_set(L, R);
1094 case ICmpInst::ICMP_UGT:
1095 return isl_pw_aff_gt_set(L, R);
1096 case ICmpInst::ICMP_ULE:
1097 return isl_pw_aff_le_set(L, R);
1098 case ICmpInst::ICMP_UGE:
1099 return isl_pw_aff_ge_set(L, R);
1100 default:
1101 llvm_unreachable("Non integer predicate not supported");
1102 }
1103}
1104
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001105/// @brief Create the conditions under which @p L @p Pred @p R is true.
1106///
1107/// Helper function that will make sure the dimensions of the result have the
1108/// same isl_id's as the @p Domain.
1109static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1110 __isl_take isl_pw_aff *L,
1111 __isl_take isl_pw_aff *R,
1112 __isl_keep isl_set *Domain) {
1113 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1114 return setDimensionIds(Domain, ConsequenceCondSet);
1115}
1116
1117/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001118///
1119/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001120/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1121/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001122static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001123buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001124 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1125
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001126 Value *Condition = getConditionFromTerminator(SI);
1127 assert(Condition && "No condition for switch");
1128
1129 ScalarEvolution &SE = *S.getSE();
1130 BasicBlock *BB = SI->getParent();
1131 isl_pw_aff *LHS, *RHS;
1132 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
1133
1134 unsigned NumSuccessors = SI->getNumSuccessors();
1135 ConditionSets.resize(NumSuccessors);
1136 for (auto &Case : SI->cases()) {
1137 unsigned Idx = Case.getSuccessorIndex();
1138 ConstantInt *CaseValue = Case.getCaseValue();
1139
1140 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
1141 isl_set *CaseConditionSet =
1142 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1143 ConditionSets[Idx] = isl_set_coalesce(
1144 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1145 }
1146
1147 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1148 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1149 for (unsigned u = 2; u < NumSuccessors; u++)
1150 ConditionSetUnion =
1151 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1152 ConditionSets[0] = setDimensionIds(
1153 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1154
1155 S.markAsOptimized();
1156 isl_pw_aff_free(LHS);
1157}
1158
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001159/// @brief Build the conditions sets for the branch condition @p Condition in
1160/// the @p Domain.
1161///
1162/// This will fill @p ConditionSets with the conditions under which control
1163/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001164/// have as many elements as @p TI has successors. If @p TI is nullptr the
1165/// context under which @p Condition is true/false will be returned as the
1166/// new elements of @p ConditionSets.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001167static void
1168buildConditionSets(Scop &S, Value *Condition, TerminatorInst *TI, Loop *L,
1169 __isl_keep isl_set *Domain,
1170 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1171
1172 isl_set *ConsequenceCondSet = nullptr;
1173 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1174 if (CCond->isZero())
1175 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1176 else
1177 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1178 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1179 auto Opcode = BinOp->getOpcode();
1180 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1181
1182 buildConditionSets(S, BinOp->getOperand(0), TI, L, Domain, ConditionSets);
1183 buildConditionSets(S, BinOp->getOperand(1), TI, L, Domain, ConditionSets);
1184
1185 isl_set_free(ConditionSets.pop_back_val());
1186 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1187 isl_set_free(ConditionSets.pop_back_val());
1188 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1189
1190 if (Opcode == Instruction::And)
1191 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1192 else
1193 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1194 } else {
1195 auto *ICond = dyn_cast<ICmpInst>(Condition);
1196 assert(ICond &&
1197 "Condition of exiting branch was neither constant nor ICmp!");
1198
1199 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001200 BasicBlock *BB = TI ? TI->getParent() : nullptr;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001201 isl_pw_aff *LHS, *RHS;
1202 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1203 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
1204 ConsequenceCondSet =
1205 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1206 }
1207
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001208 // If no terminator was given we are only looking for parameter constraints
1209 // under which @p Condition is true/false.
1210 if (!TI)
1211 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
1212
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001213 assert(ConsequenceCondSet);
1214 isl_set *AlternativeCondSet =
1215 isl_set_complement(isl_set_copy(ConsequenceCondSet));
1216
1217 ConditionSets.push_back(isl_set_coalesce(
1218 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
1219 ConditionSets.push_back(isl_set_coalesce(
1220 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
1221}
1222
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001223/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1224///
1225/// This will fill @p ConditionSets with the conditions under which control
1226/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1227/// have as many elements as @p TI has successors.
1228static void
1229buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1230 __isl_keep isl_set *Domain,
1231 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1232
1233 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1234 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1235
1236 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1237
1238 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001239 ConditionSets.push_back(isl_set_copy(Domain));
1240 return;
1241 }
1242
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001243 Value *Condition = getConditionFromTerminator(TI);
1244 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001245
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001246 return buildConditionSets(S, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001247}
1248
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001249void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +00001250 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +00001251
Tobias Grosser084d8f72012-05-29 09:29:44 +00001252 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1253
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001254 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001255 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001256}
1257
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001258void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP,
1259 ScopDetection &SD) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001260 isl_ctx *Ctx = Parent.getIslCtx();
1261 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1262 Type *Ty = GEP->getPointerOperandType();
1263 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001264
1265 // The set of loads that are required to be invariant.
1266 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001267
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001268 std::vector<const SCEV *> Subscripts;
1269 std::vector<int> Sizes;
1270
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001271 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001272
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001273 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001274 Ty = PtrTy->getElementType();
1275 }
1276
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001277 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001278
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001279 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001280
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001281 for (size_t i = 0; i < Sizes.size(); i++) {
1282 auto Expr = Subscripts[i + IndexOffset];
1283 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001284
Johannes Doerfert09e36972015-10-07 20:17:36 +00001285 InvariantLoadsSetTy AccessILS;
1286 if (!isAffineExpr(&Parent.getRegion(), Expr, SE, nullptr, &AccessILS))
1287 continue;
1288
1289 bool NonAffine = false;
1290 for (LoadInst *LInst : AccessILS)
1291 if (!ScopRIL.count(LInst))
1292 NonAffine = true;
1293
1294 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001295 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001296
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001297 isl_pw_aff *AccessOffset = getPwAff(Expr);
1298 AccessOffset =
1299 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001300
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001301 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1302 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001303
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001304 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1305 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1306 OutOfBound = isl_set_params(OutOfBound);
1307 isl_set *InBound = isl_set_complement(OutOfBound);
1308 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001309
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001310 // A => B == !A or B
1311 isl_set *InBoundIfExecuted =
1312 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001313
Roman Gareev10595a12016-01-08 14:01:59 +00001314 InBoundIfExecuted = isl_set_coalesce(InBoundIfExecuted);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001315 Parent.addAssumption(INBOUNDS, InBoundIfExecuted, GEP->getDebugLoc());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001316 }
1317
1318 isl_local_space_free(LSpace);
1319}
1320
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001321void ScopStmt::deriveAssumptions(BasicBlock *Block, ScopDetection &SD) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001322 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001323 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001324 deriveAssumptionsFromGEP(GEP, SD);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001325}
1326
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001327void ScopStmt::collectSurroundingLoops() {
1328 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1329 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1330 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1331 isl_id_free(DimId);
1332 }
1333}
1334
Michael Kruse9d080092015-09-11 21:41:48 +00001335ScopStmt::ScopStmt(Scop &parent, Region &R)
Michael Krusecac948e2015-10-02 13:53:07 +00001336 : Parent(parent), Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001337
Tobias Grosser16c44032015-07-09 07:31:45 +00001338 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001339}
1340
Michael Kruse9d080092015-09-11 21:41:48 +00001341ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Michael Krusecac948e2015-10-02 13:53:07 +00001342 : Parent(parent), Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001343
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001344 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001345}
1346
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001347void ScopStmt::init(ScopDetection &SD) {
Michael Krusecac948e2015-10-02 13:53:07 +00001348 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001349
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001350 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001351 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001352 buildAccessRelations();
1353
1354 if (BB) {
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001355 deriveAssumptions(BB, SD);
Michael Krusecac948e2015-10-02 13:53:07 +00001356 } else {
1357 for (BasicBlock *Block : R->blocks()) {
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001358 deriveAssumptions(Block, SD);
Michael Krusecac948e2015-10-02 13:53:07 +00001359 }
1360 }
1361
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001362 if (DetectReductions)
1363 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001364}
1365
Johannes Doerferte58a0122014-06-27 20:31:28 +00001366/// @brief Collect loads which might form a reduction chain with @p StoreMA
1367///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001368/// Check if the stored value for @p StoreMA is a binary operator with one or
1369/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001370/// used only once (by @p StoreMA) and its load operands are also used only
1371/// once, we have found a possible reduction chain. It starts at an operand
1372/// load and includes the binary operator and @p StoreMA.
1373///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001374/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001375/// escape this block or into any other store except @p StoreMA.
1376void ScopStmt::collectCandiateReductionLoads(
1377 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1378 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1379 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001380 return;
1381
1382 // Skip if there is not one binary operator between the load and the store
1383 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001384 if (!BinOp)
1385 return;
1386
1387 // Skip if the binary operators has multiple uses
1388 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001389 return;
1390
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001391 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001392 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1393 return;
1394
Johannes Doerfert9890a052014-07-01 00:32:29 +00001395 // Skip if the binary operator is outside the current SCoP
1396 if (BinOp->getParent() != Store->getParent())
1397 return;
1398
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001399 // Skip if it is a multiplicative reduction and we disabled them
1400 if (DisableMultiplicativeReductions &&
1401 (BinOp->getOpcode() == Instruction::Mul ||
1402 BinOp->getOpcode() == Instruction::FMul))
1403 return;
1404
Johannes Doerferte58a0122014-06-27 20:31:28 +00001405 // Check the binary operator operands for a candidate load
1406 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1407 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1408 if (!PossibleLoad0 && !PossibleLoad1)
1409 return;
1410
1411 // A load is only a candidate if it cannot escape (thus has only this use)
1412 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001413 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001414 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001415 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001416 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001417 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001418}
1419
1420/// @brief Check for reductions in this ScopStmt
1421///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001422/// Iterate over all store memory accesses and check for valid binary reduction
1423/// like chains. For all candidates we check if they have the same base address
1424/// and there are no other accesses which overlap with them. The base address
1425/// check rules out impossible reductions candidates early. The overlap check,
1426/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001427/// guarantees that none of the intermediate results will escape during
1428/// execution of the loop nest. We basically check here that no other memory
1429/// access can access the same memory as the potential reduction.
1430void ScopStmt::checkForReductions() {
1431 SmallVector<MemoryAccess *, 2> Loads;
1432 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1433
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001434 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001435 // stores and collecting possible reduction loads.
1436 for (MemoryAccess *StoreMA : MemAccs) {
1437 if (StoreMA->isRead())
1438 continue;
1439
1440 Loads.clear();
1441 collectCandiateReductionLoads(StoreMA, Loads);
1442 for (MemoryAccess *LoadMA : Loads)
1443 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1444 }
1445
1446 // Then check each possible candidate pair.
1447 for (const auto &CandidatePair : Candidates) {
1448 bool Valid = true;
1449 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1450 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1451
1452 // Skip those with obviously unequal base addresses.
1453 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1454 isl_map_free(LoadAccs);
1455 isl_map_free(StoreAccs);
1456 continue;
1457 }
1458
1459 // And check if the remaining for overlap with other memory accesses.
1460 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1461 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1462 isl_set *AllAccs = isl_map_range(AllAccsRel);
1463
1464 for (MemoryAccess *MA : MemAccs) {
1465 if (MA == CandidatePair.first || MA == CandidatePair.second)
1466 continue;
1467
1468 isl_map *AccRel =
1469 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1470 isl_set *Accs = isl_map_range(AccRel);
1471
1472 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1473 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1474 Valid = Valid && isl_set_is_empty(OverlapAccs);
1475 isl_set_free(OverlapAccs);
1476 }
1477 }
1478
1479 isl_set_free(AllAccs);
1480 if (!Valid)
1481 continue;
1482
Johannes Doerfertf6183392014-07-01 20:52:51 +00001483 const LoadInst *Load =
1484 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1485 MemoryAccess::ReductionType RT =
1486 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1487
Johannes Doerferte58a0122014-06-27 20:31:28 +00001488 // If no overlapping access was found we mark the load and store as
1489 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001490 CandidatePair.first->markAsReductionLike(RT);
1491 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001492 }
Tobias Grosser75805372011-04-29 06:27:02 +00001493}
1494
Tobias Grosser74394f02013-01-14 22:40:23 +00001495std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001496
Tobias Grosser54839312015-04-21 11:37:25 +00001497std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001498 auto *S = getSchedule();
1499 auto Str = stringFromIslObj(S);
1500 isl_map_free(S);
1501 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001502}
1503
Tobias Grosser74394f02013-01-14 22:40:23 +00001504unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001505
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001506unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001507
Tobias Grosser75805372011-04-29 06:27:02 +00001508const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1509
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001510const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001511 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001512}
1513
Tobias Grosser74394f02013-01-14 22:40:23 +00001514isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001515
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001516__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001517
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001518__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001519 return isl_set_get_space(Domain);
1520}
1521
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001522__isl_give isl_id *ScopStmt::getDomainId() const {
1523 return isl_set_get_tuple_id(Domain);
1524}
Tobias Grossercd95b772012-08-30 11:49:38 +00001525
Tobias Grosser10120182015-12-16 16:14:03 +00001526ScopStmt::~ScopStmt() { isl_set_free(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001527
1528void ScopStmt::print(raw_ostream &OS) const {
1529 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001530 OS.indent(12) << "Domain :=\n";
1531
1532 if (Domain) {
1533 OS.indent(16) << getDomainStr() << ";\n";
1534 } else
1535 OS.indent(16) << "n/a\n";
1536
Tobias Grosser54839312015-04-21 11:37:25 +00001537 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001538
1539 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001540 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001541 } else
1542 OS.indent(16) << "n/a\n";
1543
Tobias Grosser083d3d32014-06-28 08:59:45 +00001544 for (MemoryAccess *Access : MemAccs)
1545 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001546}
1547
1548void ScopStmt::dump() const { print(dbgs()); }
1549
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001550void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001551 // Remove all memory accesses in @p InvMAs from this statement
1552 // together with all scalar accesses that were caused by them.
Michael Krusead28e5a2016-01-26 13:33:15 +00001553 // MK_Value READs have no access instruction, hence would not be removed by
1554 // this function. However, it is only used for invariant LoadInst accesses,
1555 // its arguments are always affine, hence synthesizable, and therefore there
1556 // are no MK_Value READ accesses to be removed.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001557 for (MemoryAccess *MA : InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001558 auto Predicate = [&](MemoryAccess *Acc) {
Tobias Grosser3a6ac9f2015-11-30 21:13:43 +00001559 return Acc->getAccessInstruction() == MA->getAccessInstruction();
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001560 };
1561 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1562 MemAccs.end());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001563 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001564 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001565}
1566
Tobias Grosser75805372011-04-29 06:27:02 +00001567//===----------------------------------------------------------------------===//
1568/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001569
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001570void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001571 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1572 isl_set_free(Context);
1573 Context = NewContext;
1574}
1575
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001576/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1577struct SCEVSensitiveParameterRewriter
1578 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1579 ValueToValueMap &VMap;
1580 ScalarEvolution &SE;
1581
1582public:
1583 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1584 : VMap(VMap), SE(SE) {}
1585
1586 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1587 ValueToValueMap &VMap) {
1588 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1589 return SSPR.visit(E);
1590 }
1591
1592 const SCEV *visit(const SCEV *E) {
1593 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1594 }
1595
1596 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1597
1598 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1599 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1600 }
1601
1602 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1603 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1604 }
1605
1606 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1607 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1608 }
1609
1610 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1611 SmallVector<const SCEV *, 4> Operands;
1612 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1613 Operands.push_back(visit(E->getOperand(i)));
1614 return SE.getAddExpr(Operands);
1615 }
1616
1617 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1618 SmallVector<const SCEV *, 4> Operands;
1619 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1620 Operands.push_back(visit(E->getOperand(i)));
1621 return SE.getMulExpr(Operands);
1622 }
1623
1624 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1625 SmallVector<const SCEV *, 4> Operands;
1626 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1627 Operands.push_back(visit(E->getOperand(i)));
1628 return SE.getSMaxExpr(Operands);
1629 }
1630
1631 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1632 SmallVector<const SCEV *, 4> Operands;
1633 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1634 Operands.push_back(visit(E->getOperand(i)));
1635 return SE.getUMaxExpr(Operands);
1636 }
1637
1638 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1639 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1640 }
1641
1642 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1643 auto *Start = visit(E->getStart());
1644 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1645 visit(E->getStepRecurrence(SE)),
1646 E->getLoop(), SCEV::FlagAnyWrap);
1647 return SE.getAddExpr(Start, AddRec);
1648 }
1649
1650 const SCEV *visitUnknown(const SCEVUnknown *E) {
1651 if (auto *NewValue = VMap.lookup(E->getValue()))
1652 return SE.getUnknown(NewValue);
1653 return E;
1654 }
1655};
1656
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001657const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001658 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001659}
1660
Tobias Grosserabfbe632013-02-05 12:09:06 +00001661void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001662 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001663 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001664
1665 // Normalize the SCEV to get the representing element for an invariant load.
1666 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1667
Tobias Grosser60b54f12011-11-08 15:41:28 +00001668 if (ParameterIds.find(Parameter) != ParameterIds.end())
1669 continue;
1670
1671 int dimension = Parameters.size();
1672
1673 Parameters.push_back(Parameter);
1674 ParameterIds[Parameter] = dimension;
1675 }
1676}
1677
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001678__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001679 // Normalize the SCEV to get the representing element for an invariant load.
1680 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1681
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001682 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001683
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001684 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001685 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001686
Tobias Grosser8f99c162011-11-15 11:38:55 +00001687 std::string ParameterName;
1688
Craig Topper7fb6e472016-01-31 20:36:20 +00001689 ParameterName = "p_" + utostr(IdIter->second);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001690
Tobias Grosser8f99c162011-11-15 11:38:55 +00001691 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1692 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001693
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001694 // If this parameter references a specific Value and this value has a name
1695 // we use this name as it is likely to be unique and more useful than just
1696 // a number.
1697 if (Val->hasName())
1698 ParameterName = Val->getName();
1699 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
1700 auto LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
1701 if (LoadOrigin->hasName()) {
1702 ParameterName += "_loaded_from_";
1703 ParameterName +=
1704 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1705 }
1706 }
1707 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001708
Tobias Grosser20532b82014-04-11 17:56:49 +00001709 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1710 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001711}
Tobias Grosser75805372011-04-29 06:27:02 +00001712
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001713isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1714 isl_set *DomainContext = isl_union_set_params(getDomains());
1715 return isl_set_intersect_params(C, DomainContext);
1716}
1717
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001718void Scop::buildBoundaryContext() {
Tobias Grosser4927c8e2015-11-24 12:50:02 +00001719 if (IgnoreIntegerWrapping) {
1720 BoundaryContext = isl_set_universe(getParamSpace());
1721 return;
1722 }
1723
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001724 BoundaryContext = Affinator.getWrappingContext();
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001725
1726 // The isl_set_complement operation used to create the boundary context
1727 // can possibly become very expensive. We bound the compile time of
1728 // this operation by setting a compute out.
1729 //
1730 // TODO: We can probably get around using isl_set_complement and directly
1731 // AST generate BoundaryContext.
1732 long MaxOpsOld = isl_ctx_get_max_operations(getIslCtx());
Tobias Grosserf920fb12015-11-13 16:56:13 +00001733 isl_ctx_reset_operations(getIslCtx());
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001734 isl_ctx_set_max_operations(getIslCtx(), 300000);
1735 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_CONTINUE);
1736
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001737 BoundaryContext = isl_set_complement(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001738
Tobias Grossera52b4da2015-11-11 17:59:53 +00001739 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
1740 isl_set_free(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001741 BoundaryContext = isl_set_empty(getParamSpace());
Tobias Grossera52b4da2015-11-11 17:59:53 +00001742 }
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001743
1744 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
1745 isl_ctx_reset_operations(getIslCtx());
1746 isl_ctx_set_max_operations(getIslCtx(), MaxOpsOld);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001747 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001748 trackAssumption(WRAPPING, BoundaryContext, DebugLoc());
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001749}
1750
Hongbin Zheng192f69a2016-02-13 15:12:54 +00001751void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
1752 LoopInfo &LI) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001753 auto *R = &getRegion();
1754 auto &F = *R->getEntry()->getParent();
1755 for (auto &Assumption : AC.assumptions()) {
1756 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1757 if (!CI || CI->getNumArgOperands() != 1)
1758 continue;
1759 if (!DT.dominates(CI->getParent(), R->getEntry()))
1760 continue;
1761
1762 auto *Val = CI->getArgOperand(0);
1763 std::vector<const SCEV *> Params;
1764 if (!isAffineParamConstraint(Val, R, *SE, Params)) {
1765 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1766 CI->getDebugLoc(),
1767 "Non-affine user assumption ignored.");
1768 continue;
1769 }
1770
1771 addParams(Params);
1772
1773 auto *L = LI.getLoopFor(CI->getParent());
1774 SmallVector<isl_set *, 2> ConditionSets;
1775 buildConditionSets(*this, Val, nullptr, L, Context, ConditionSets);
1776 assert(ConditionSets.size() == 2);
1777 isl_set_free(ConditionSets[1]);
1778
1779 auto *AssumptionCtx = ConditionSets[0];
1780 emitOptimizationRemarkAnalysis(
1781 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1782 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1783 Context = isl_set_intersect(Context, AssumptionCtx);
1784 }
1785}
1786
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001787void Scop::addUserContext() {
1788 if (UserContextStr.empty())
1789 return;
1790
1791 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1792 isl_space *Space = getParamSpace();
1793 if (isl_space_dim(Space, isl_dim_param) !=
1794 isl_set_dim(UserContext, isl_dim_param)) {
1795 auto SpaceStr = isl_space_to_str(Space);
1796 errs() << "Error: the context provided in -polly-context has not the same "
1797 << "number of dimensions than the computed context. Due to this "
1798 << "mismatch, the -polly-context option is ignored. Please provide "
1799 << "the context in the parameter space: " << SpaceStr << ".\n";
1800 free(SpaceStr);
1801 isl_set_free(UserContext);
1802 isl_space_free(Space);
1803 return;
1804 }
1805
1806 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1807 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1808 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1809
1810 if (strcmp(NameContext, NameUserContext) != 0) {
1811 auto SpaceStr = isl_space_to_str(Space);
1812 errs() << "Error: the name of dimension " << i
1813 << " provided in -polly-context "
1814 << "is '" << NameUserContext << "', but the name in the computed "
1815 << "context is '" << NameContext
1816 << "'. Due to this name mismatch, "
1817 << "the -polly-context option is ignored. Please provide "
1818 << "the context in the parameter space: " << SpaceStr << ".\n";
1819 free(SpaceStr);
1820 isl_set_free(UserContext);
1821 isl_space_free(Space);
1822 return;
1823 }
1824
1825 UserContext =
1826 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1827 isl_space_get_dim_id(Space, isl_dim_param, i));
1828 }
1829
1830 Context = isl_set_intersect(Context, UserContext);
1831 isl_space_free(Space);
1832}
1833
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001834void Scop::buildInvariantEquivalenceClasses(ScopDetection &SD) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00001835 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001836
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001837 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001838 for (LoadInst *LInst : RIL) {
1839 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1840
Johannes Doerfert96e54712016-02-07 17:30:13 +00001841 Type *Ty = LInst->getType();
1842 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001843 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001844 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001845 continue;
1846 }
1847
1848 ClassRep = LInst;
Johannes Doerfert96e54712016-02-07 17:30:13 +00001849 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(), nullptr,
1850 Ty);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001851 }
1852}
1853
Tobias Grosser6be480c2011-11-08 15:41:13 +00001854void Scop::buildContext() {
1855 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001856 Context = isl_set_universe(isl_space_copy(Space));
1857 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001858}
1859
Tobias Grosser18daaca2012-05-22 10:47:27 +00001860void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001861 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001862 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001863
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001864 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001865
Johannes Doerferte7044942015-02-24 11:58:30 +00001866 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001867 }
1868}
1869
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001870void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001871 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001872 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001873
Tobias Grosser083d3d32014-06-28 08:59:45 +00001874 for (const auto &ParamID : ParameterIds) {
1875 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001876 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001877 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001878 }
1879
1880 // Align the parameters of all data structures to the model.
1881 Context = isl_set_align_params(Context, Space);
1882
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001883 for (ScopStmt &Stmt : *this)
1884 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001885}
1886
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001887static __isl_give isl_set *
1888simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1889 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001890 // If we modelt all blocks in the SCoP that have side effects we can simplify
1891 // the context with the constraints that are needed for anything to be
1892 // executed at all. However, if we have error blocks in the SCoP we already
1893 // assumed some parameter combinations cannot occure and removed them from the
1894 // domains, thus we cannot use the remaining domain to simplify the
1895 // assumptions.
1896 if (!S.hasErrorBlock()) {
1897 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1898 AssumptionContext =
1899 isl_set_gist_params(AssumptionContext, DomainParameters);
1900 }
1901
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001902 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1903 return AssumptionContext;
1904}
1905
1906void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001907 // The parameter constraints of the iteration domains give us a set of
1908 // constraints that need to hold for all cases where at least a single
1909 // statement iteration is executed in the whole scop. We now simplify the
1910 // assumed context under the assumption that such constraints hold and at
1911 // least a single statement iteration is executed. For cases where no
1912 // statement instances are executed, the assumptions we have taken about
1913 // the executed code do not matter and can be changed.
1914 //
1915 // WARNING: This only holds if the assumptions we have taken do not reduce
1916 // the set of statement instances that are executed. Otherwise we
1917 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001918 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001919 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001920 // performed. In such a case, modifying the run-time conditions and
1921 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001922 // to not be executed.
1923 //
1924 // Example:
1925 //
1926 // When delinearizing the following code:
1927 //
1928 // for (long i = 0; i < 100; i++)
1929 // for (long j = 0; j < m; j++)
1930 // A[i+p][j] = 1.0;
1931 //
1932 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001933 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001934 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001935 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1936 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001937}
1938
Johannes Doerfertb164c792014-09-18 11:17:17 +00001939/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001940static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001941 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1942 isl_pw_multi_aff *MinPMA, *MaxPMA;
1943 isl_pw_aff *LastDimAff;
1944 isl_aff *OneAff;
1945 unsigned Pos;
1946
Johannes Doerfert9143d672014-09-27 11:02:39 +00001947 // Restrict the number of parameters involved in the access as the lexmin/
1948 // lexmax computation will take too long if this number is high.
1949 //
1950 // Experiments with a simple test case using an i7 4800MQ:
1951 //
1952 // #Parameters involved | Time (in sec)
1953 // 6 | 0.01
1954 // 7 | 0.04
1955 // 8 | 0.12
1956 // 9 | 0.40
1957 // 10 | 1.54
1958 // 11 | 6.78
1959 // 12 | 30.38
1960 //
1961 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1962 unsigned InvolvedParams = 0;
1963 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1964 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1965 InvolvedParams++;
1966
1967 if (InvolvedParams > RunTimeChecksMaxParameters) {
1968 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001969 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001970 }
1971 }
1972
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001973 Set = isl_set_remove_divs(Set);
1974
Johannes Doerfertb164c792014-09-18 11:17:17 +00001975 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1976 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1977
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001978 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1979 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1980
Johannes Doerfertb164c792014-09-18 11:17:17 +00001981 // Adjust the last dimension of the maximal access by one as we want to
1982 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1983 // we test during code generation might now point after the end of the
1984 // allocated array but we will never dereference it anyway.
1985 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1986 "Assumed at least one output dimension");
1987 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1988 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1989 OneAff = isl_aff_zero_on_domain(
1990 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1991 OneAff = isl_aff_add_constant_si(OneAff, 1);
1992 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1993 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1994
1995 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1996
1997 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001998 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001999}
2000
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002001static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2002 isl_set *Domain = MA->getStatement()->getDomain();
2003 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2004 return isl_set_reset_tuple_id(Domain);
2005}
2006
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002007/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
2008static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00002009 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002010 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002011
2012 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2013 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002014 Locations = isl_union_set_coalesce(Locations);
2015 Locations = isl_union_set_detect_equalities(Locations);
2016 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002017 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002018 isl_union_set_free(Locations);
2019 return Valid;
2020}
2021
Johannes Doerfert96425c22015-08-30 21:13:53 +00002022/// @brief Helper to treat non-affine regions and basic blocks the same.
2023///
2024///{
2025
2026/// @brief Return the block that is the representing block for @p RN.
2027static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2028 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2029 : RN->getNodeAs<BasicBlock>();
2030}
2031
2032/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002033static inline BasicBlock *
2034getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002035 if (RN->isSubRegion()) {
2036 assert(idx == 0);
2037 return RN->getNodeAs<Region>()->getExit();
2038 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002039 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002040}
2041
2042/// @brief Return the smallest loop surrounding @p RN.
2043static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2044 if (!RN->isSubRegion())
2045 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2046
2047 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2048 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2049 while (L && NonAffineSubRegion->contains(L))
2050 L = L->getParentLoop();
2051 return L;
2052}
2053
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002054static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2055 if (!RN->isSubRegion())
2056 return 1;
2057
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002058 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002059 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002060}
2061
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002062static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2063 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002064 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002065 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002066 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002067 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002068 return true;
2069 return false;
2070}
2071
Johannes Doerfert96425c22015-08-30 21:13:53 +00002072///}
2073
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002074static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2075 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002076 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002077 isl_id *DimId =
2078 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2079 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2080}
2081
Johannes Doerfert96425c22015-08-30 21:13:53 +00002082isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
2083 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
2084 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002085 return getDomainConditions(BB);
2086}
2087
2088isl_set *Scop::getDomainConditions(BasicBlock *BB) {
2089 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002090 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002091}
2092
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002093void Scop::removeErrorBlockDomains(ScopDetection &SD, DominatorTree &DT,
2094 LoopInfo &LI) {
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002095 auto removeDomains = [this, &DT](BasicBlock *Start) {
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002096 auto BBNode = DT.getNode(Start);
2097 for (auto ErrorChild : depth_first(BBNode)) {
2098 auto ErrorChildBlock = ErrorChild->getBlock();
2099 auto CurrentDomain = DomainMap[ErrorChildBlock];
2100 auto Empty = isl_set_empty(isl_set_get_space(CurrentDomain));
2101 DomainMap[ErrorChildBlock] = Empty;
2102 isl_set_free(CurrentDomain);
2103 }
2104 };
2105
Tobias Grosser5ef2bc32015-11-23 10:18:23 +00002106 SmallVector<Region *, 4> Todo = {&R};
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002107
2108 while (!Todo.empty()) {
2109 auto SubRegion = Todo.back();
2110 Todo.pop_back();
2111
2112 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
2113 for (auto &Child : *SubRegion)
2114 Todo.push_back(Child.get());
2115 continue;
2116 }
2117 if (containsErrorBlock(SubRegion->getNode(), getRegion(), LI, DT))
2118 removeDomains(SubRegion->getEntry());
2119 }
2120
2121 for (auto BB : R.blocks())
2122 if (isErrorBlock(*BB, R, LI, DT))
2123 removeDomains(BB);
2124}
2125
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002126void Scop::buildDomains(Region *R, ScopDetection &SD, DominatorTree &DT,
2127 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002128
Johannes Doerfert432658d2016-01-26 11:01:41 +00002129 bool IsOnlyNonAffineRegion = SD.isNonAffineSubRegion(R, R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002130 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002131 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2132 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002133 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002134
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002135 while (LD-- >= 0) {
2136 S = addDomainDimId(S, LD + 1, L);
2137 L = L->getParentLoop();
2138 }
2139
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002140 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002141
Johannes Doerfert432658d2016-01-26 11:01:41 +00002142 if (IsOnlyNonAffineRegion)
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002143 return;
2144
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002145 buildDomainsWithBranchConstraints(R, SD, DT, LI);
2146 propagateDomainConstraints(R, SD, DT, LI);
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002147
2148 // Error blocks and blocks dominated by them have been assumed to never be
2149 // executed. Representing them in the Scop does not add any value. In fact,
2150 // it is likely to cause issues during construction of the ScopStmts. The
2151 // contents of error blocks have not been verfied to be expressible and
2152 // will cause problems when building up a ScopStmt for them.
2153 // Furthermore, basic blocks dominated by error blocks may reference
2154 // instructions in the error block which, if the error block is not modeled,
2155 // can themselves not be constructed properly.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002156 removeErrorBlockDomains(SD, DT, LI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002157}
2158
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002159void Scop::buildDomainsWithBranchConstraints(Region *R, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002160 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert6f50c292016-01-26 11:03:25 +00002161 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002162
2163 // To create the domain for each block in R we iterate over all blocks and
2164 // subregions in R and propagate the conditions under which the current region
2165 // element is executed. To this end we iterate in reverse post order over R as
2166 // it ensures that we first visit all predecessors of a region node (either a
2167 // basic block or a subregion) before we visit the region node itself.
2168 // Initially, only the domain for the SCoP region entry block is set and from
2169 // there we propagate the current domain to all successors, however we add the
2170 // condition that the successor is actually executed next.
2171 // As we are only interested in non-loop carried constraints here we can
2172 // simply skip loop back edges.
2173
2174 ReversePostOrderTraversal<Region *> RTraversal(R);
2175 for (auto *RN : RTraversal) {
2176
2177 // Recurse for affine subregions but go on for basic blocks and non-affine
2178 // subregions.
2179 if (RN->isSubRegion()) {
2180 Region *SubRegion = RN->getNodeAs<Region>();
2181 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002182 buildDomainsWithBranchConstraints(SubRegion, SD, DT, LI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002183 continue;
2184 }
2185 }
2186
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002187 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002188 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002189
Johannes Doerfert96425c22015-08-30 21:13:53 +00002190 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002191 TerminatorInst *TI = BB->getTerminator();
2192
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002193 if (isa<UnreachableInst>(TI))
2194 continue;
2195
Johannes Doerfertf5673802015-10-01 23:48:18 +00002196 isl_set *Domain = DomainMap.lookup(BB);
2197 if (!Domain) {
2198 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2199 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002200 continue;
2201 }
2202
Johannes Doerfert96425c22015-08-30 21:13:53 +00002203 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002204
2205 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2206 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2207
2208 // Build the condition sets for the successor nodes of the current region
2209 // node. If it is a non-affine subregion we will always execute the single
2210 // exit node, hence the single entry node domain is the condition set. For
2211 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002212 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002213 if (RN->isSubRegion())
2214 ConditionSets.push_back(isl_set_copy(Domain));
2215 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002216 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002217
2218 // Now iterate over the successors and set their initial domain based on
2219 // their condition set. We skip back edges here and have to be careful when
2220 // we leave a loop not to keep constraints over a dimension that doesn't
2221 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002222 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002223 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002224 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002225 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002226
2227 // Skip back edges.
2228 if (DT.dominates(SuccBB, BB)) {
2229 isl_set_free(CondSet);
2230 continue;
2231 }
2232
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002233 // Do not adjust the number of dimensions if we enter a boxed loop or are
2234 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002235 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfert6f50c292016-01-26 11:03:25 +00002236 while (BoxedLoops.count(SuccBBLoop))
2237 SuccBBLoop = SuccBBLoop->getParentLoop();
Johannes Doerfert634909c2015-10-04 14:57:41 +00002238
2239 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002240
2241 // Check if the edge to SuccBB is a loop entry or exit edge. If so
2242 // adjust the dimensionality accordingly. Lastly, if we leave a loop
2243 // and enter a new one we need to drop the old constraints.
2244 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002245 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002246 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002247 CondSet = isl_set_project_out(CondSet, isl_dim_set,
2248 isl_set_n_dim(CondSet) - LoopDepthDiff,
2249 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002250 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002251 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002252 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002253 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002254 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002255 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002256 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
2257 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002258 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002259 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002260 }
2261
2262 // Set the domain for the successor or merge it with an existing domain in
2263 // case there are multiple paths (without loop back edges) to the
2264 // successor block.
2265 isl_set *&SuccDomain = DomainMap[SuccBB];
2266 if (!SuccDomain)
2267 SuccDomain = CondSet;
2268 else
2269 SuccDomain = isl_set_union(SuccDomain, CondSet);
2270
2271 SuccDomain = isl_set_coalesce(SuccDomain);
Tobias Grosser75dc40c2015-12-20 13:31:48 +00002272 if (isl_set_n_basic_set(SuccDomain) > MaxConjunctsInDomain) {
2273 auto *Empty = isl_set_empty(isl_set_get_space(SuccDomain));
2274 isl_set_free(SuccDomain);
2275 SuccDomain = Empty;
2276 invalidate(ERROR_DOMAINCONJUNCTS, DebugLoc());
2277 }
Johannes Doerfert634909c2015-10-04 14:57:41 +00002278 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
2279 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002280 }
2281 }
2282}
2283
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002284/// @brief Return the domain for @p BB wrt @p DomainMap.
2285///
2286/// This helper function will lookup @p BB in @p DomainMap but also handle the
2287/// case where @p BB is contained in a non-affine subregion using the region
2288/// tree obtained by @p RI.
2289static __isl_give isl_set *
2290getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
2291 RegionInfo &RI) {
2292 auto DIt = DomainMap.find(BB);
2293 if (DIt != DomainMap.end())
2294 return isl_set_copy(DIt->getSecond());
2295
2296 Region *R = RI.getRegionFor(BB);
2297 while (R->getEntry() == BB)
2298 R = R->getParent();
2299 return getDomainForBlock(R->getEntry(), DomainMap, RI);
2300}
2301
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002302void Scop::propagateDomainConstraints(Region *R, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002303 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002304 // Iterate over the region R and propagate the domain constrains from the
2305 // predecessors to the current node. In contrast to the
2306 // buildDomainsWithBranchConstraints function, this one will pull the domain
2307 // information from the predecessors instead of pushing it to the successors.
2308 // Additionally, we assume the domains to be already present in the domain
2309 // map here. However, we iterate again in reverse post order so we know all
2310 // predecessors have been visited before a block or non-affine subregion is
2311 // visited.
2312
2313 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2314 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2315
2316 ReversePostOrderTraversal<Region *> RTraversal(R);
2317 for (auto *RN : RTraversal) {
2318
2319 // Recurse for affine subregions but go on for basic blocks and non-affine
2320 // subregions.
2321 if (RN->isSubRegion()) {
2322 Region *SubRegion = RN->getNodeAs<Region>();
2323 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002324 propagateDomainConstraints(SubRegion, SD, DT, LI);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002325 continue;
2326 }
2327 }
2328
Johannes Doerfertf5673802015-10-01 23:48:18 +00002329 // Get the domain for the current block and check if it was initialized or
2330 // not. The only way it was not is if this block is only reachable via error
2331 // blocks, thus will not be executed under the assumptions we make. Such
2332 // blocks have to be skipped as their predecessors might not have domains
2333 // either. It would not benefit us to compute the domain anyway, only the
2334 // domains of the error blocks that are reachable from non-error blocks
2335 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002336 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002337 isl_set *&Domain = DomainMap[BB];
2338 if (!Domain) {
2339 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2340 << ", it is only reachable from error blocks.\n");
2341 DomainMap.erase(BB);
2342 continue;
2343 }
2344 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
2345
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002346 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2347 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2348
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002349 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2350 for (auto *PredBB : predecessors(BB)) {
2351
2352 // Skip backedges
2353 if (DT.dominates(BB, PredBB))
2354 continue;
2355
2356 isl_set *PredBBDom = nullptr;
2357
2358 // Handle the SCoP entry block with its outside predecessors.
2359 if (!getRegion().contains(PredBB))
2360 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
2361
2362 if (!PredBBDom) {
2363 // Determine the loop depth of the predecessor and adjust its domain to
2364 // the domain of the current block. This can mean we have to:
2365 // o) Drop a dimension if this block is the exit of a loop, not the
2366 // header of a new loop and the predecessor was part of the loop.
2367 // o) Add an unconstrainted new dimension if this block is the header
2368 // of a loop and the predecessor is not part of it.
2369 // o) Drop the information about the innermost loop dimension when the
2370 // predecessor and the current block are surrounded by different
2371 // loops in the same depth.
2372 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2373 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2374 while (BoxedLoops.count(PredBBLoop))
2375 PredBBLoop = PredBBLoop->getParentLoop();
2376
2377 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002378 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002379 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002380 PredBBDom = isl_set_project_out(
2381 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2382 LoopDepthDiff);
2383 else if (PredBBLoopDepth < BBLoopDepth) {
2384 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002385 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002386 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2387 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002388 PredBBDom = isl_set_drop_constraints_involving_dims(
2389 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002390 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002391 }
2392
2393 PredDom = isl_set_union(PredDom, PredBBDom);
2394 }
2395
2396 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002397 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002398
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002399 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002400 addLoopBoundsToHeaderDomain(BBLoop, LI);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002401
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002402 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002403 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002404 IsOptimized = true;
2405 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002406 addAssumption(ERRORBLOCK, isl_set_complement(DomPar),
2407 BB->getTerminator()->getDebugLoc());
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002408 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002409 }
2410}
2411
2412/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2413/// is incremented by one and all other dimensions are equal, e.g.,
2414/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2415/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2416static __isl_give isl_map *
2417createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2418 auto *MapSpace = isl_space_map_from_set(SetSpace);
2419 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2420 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2421 if (u != Dim)
2422 NextIterationMap =
2423 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2424 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2425 C = isl_constraint_set_constant_si(C, 1);
2426 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2427 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2428 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2429 return NextIterationMap;
2430}
2431
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002432void Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002433 int LoopDepth = getRelativeLoopDepth(L);
2434 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002435
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002436 BasicBlock *HeaderBB = L->getHeader();
2437 assert(DomainMap.count(HeaderBB));
2438 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002439
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002440 isl_map *NextIterationMap =
2441 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002442
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002443 isl_set *UnionBackedgeCondition =
2444 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002445
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002446 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2447 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002448
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002449 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002450
2451 // If the latch is only reachable via error statements we skip it.
2452 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2453 if (!LatchBBDom)
2454 continue;
2455
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002456 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002457
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002458 TerminatorInst *TI = LatchBB->getTerminator();
2459 BranchInst *BI = dyn_cast<BranchInst>(TI);
2460 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002461 BackedgeCondition = isl_set_copy(LatchBBDom);
2462 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002463 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002464 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002465 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002466
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002467 // Free the non back edge condition set as we do not need it.
2468 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002469
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002470 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002471 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002472
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002473 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2474 assert(LatchLoopDepth >= LoopDepth);
2475 BackedgeCondition =
2476 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2477 LatchLoopDepth - LoopDepth);
2478 UnionBackedgeCondition =
2479 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002480 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002481
2482 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2483 for (int i = 0; i < LoopDepth; i++)
2484 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2485
2486 isl_set *UnionBackedgeConditionComplement =
2487 isl_set_complement(UnionBackedgeCondition);
2488 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2489 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2490 UnionBackedgeConditionComplement =
2491 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2492 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2493 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2494
2495 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2496 HeaderBBDom = Parts.second;
2497
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002498 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2499 // the bounded assumptions to the context as they are already implied by the
2500 // <nsw> tag.
2501 if (Affinator.hasNSWAddRecForLoop(L)) {
2502 isl_set_free(Parts.first);
2503 return;
2504 }
2505
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002506 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2507 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002508 addAssumption(INFINITELOOP, BoundedCtx,
2509 HeaderBB->getTerminator()->getDebugLoc());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002510}
2511
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002512void Scop::buildAliasChecks(AliasAnalysis &AA) {
2513 if (!PollyUseRuntimeAliasChecks)
2514 return;
2515
2516 if (buildAliasGroups(AA))
2517 return;
2518
2519 // If a problem occurs while building the alias groups we need to delete
2520 // this SCoP and pretend it wasn't valid in the first place. To this end
2521 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002522 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002523
2524 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2525 << " could not be created as the number of parameters involved "
2526 "is too high. The SCoP will be "
2527 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2528 "the maximal number of parameters but be advised that the "
2529 "compile time might increase exponentially.\n\n");
2530}
2531
Johannes Doerfert9143d672014-09-27 11:02:39 +00002532bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002533 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002534 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002535 // for all memory accesses inside the SCoP.
2536 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002537 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002538 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002539 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002540 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002541 // if their access domains intersect, otherwise they are in different
2542 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002543 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002544 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002545 // and maximal accesses to each array of a group in read only and non
2546 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002547 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2548
2549 AliasSetTracker AST(AA);
2550
2551 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002552 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002553 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002554
2555 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002556 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002557 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2558 isl_set_free(StmtDomain);
2559 if (StmtDomainEmpty)
2560 continue;
2561
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002562 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002563 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002564 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002565 if (!MA->isRead())
2566 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002567 MemAccInst Acc(MA->getAccessInstruction());
2568 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002569 AST.add(Acc);
2570 }
2571 }
2572
2573 SmallVector<AliasGroupTy, 4> AliasGroups;
2574 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002575 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002576 continue;
2577 AliasGroupTy AG;
2578 for (auto PR : AS)
2579 AG.push_back(PtrToAcc[PR.getValue()]);
2580 assert(AG.size() > 1 &&
2581 "Alias groups should contain at least two accesses");
2582 AliasGroups.push_back(std::move(AG));
2583 }
2584
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002585 // Split the alias groups based on their domain.
2586 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2587 AliasGroupTy NewAG;
2588 AliasGroupTy &AG = AliasGroups[u];
2589 AliasGroupTy::iterator AGI = AG.begin();
2590 isl_set *AGDomain = getAccessDomain(*AGI);
2591 while (AGI != AG.end()) {
2592 MemoryAccess *MA = *AGI;
2593 isl_set *MADomain = getAccessDomain(MA);
2594 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2595 NewAG.push_back(MA);
2596 AGI = AG.erase(AGI);
2597 isl_set_free(MADomain);
2598 } else {
2599 AGDomain = isl_set_union(AGDomain, MADomain);
2600 AGI++;
2601 }
2602 }
2603 if (NewAG.size() > 1)
2604 AliasGroups.push_back(std::move(NewAG));
2605 isl_set_free(AGDomain);
2606 }
2607
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002608 auto &F = *getRegion().getEntry()->getParent();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002609 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002610 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2611 for (AliasGroupTy &AG : AliasGroups) {
2612 NonReadOnlyBaseValues.clear();
2613 ReadOnlyPairs.clear();
2614
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002615 if (AG.size() < 2) {
2616 AG.clear();
2617 continue;
2618 }
2619
Johannes Doerfert13771732014-10-01 12:40:46 +00002620 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002621 emitOptimizationRemarkAnalysis(
2622 F.getContext(), DEBUG_TYPE, F,
2623 (*II)->getAccessInstruction()->getDebugLoc(),
2624 "Possibly aliasing pointer, use restrict keyword.");
2625
Johannes Doerfert13771732014-10-01 12:40:46 +00002626 Value *BaseAddr = (*II)->getBaseAddr();
2627 if (HasWriteAccess.count(BaseAddr)) {
2628 NonReadOnlyBaseValues.insert(BaseAddr);
2629 II++;
2630 } else {
2631 ReadOnlyPairs[BaseAddr].insert(*II);
2632 II = AG.erase(II);
2633 }
2634 }
2635
2636 // If we don't have read only pointers check if there are at least two
2637 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002638 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002639 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002640 continue;
2641 }
2642
2643 // If we don't have non read only pointers clear the alias group.
2644 if (NonReadOnlyBaseValues.empty()) {
2645 AG.clear();
2646 continue;
2647 }
2648
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002649 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002650 MinMaxAliasGroups.emplace_back();
2651 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2652 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2653 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2654 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002655
2656 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002657
2658 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002659 for (MemoryAccess *MA : AG)
2660 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002661
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002662 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2663 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002664
2665 // Bail out if the number of values we need to compare is too large.
2666 // This is important as the number of comparisions grows quadratically with
2667 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002668 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2669 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002670 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002671
2672 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002673 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002674 Accesses = isl_union_map_empty(getParamSpace());
2675
2676 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2677 for (MemoryAccess *MA : ReadOnlyPair.second)
2678 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2679
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002680 Valid =
2681 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002682
2683 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002684 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002685 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002686
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002687 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002688}
2689
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002690/// @brief Get the smallest loop that contains @p R but is not in @p R.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002691static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002692 // Start with the smallest loop containing the entry and expand that
2693 // loop until it contains all blocks in the region. If there is a loop
2694 // containing all blocks in the region check if it is itself contained
2695 // and if so take the parent loop as it will be the smallest containing
2696 // the region but not contained by it.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002697 Loop *L = LI.getLoopFor(R.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002698 while (L) {
2699 bool AllContained = true;
2700 for (auto *BB : R.blocks())
2701 AllContained &= L->contains(BB);
2702 if (AllContained)
2703 break;
2704 L = L->getParentLoop();
2705 }
2706
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002707 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2708}
2709
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002710static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2711 ScopDetection &SD) {
2712
2713 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2714
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002715 unsigned MinLD = INT_MAX, MaxLD = 0;
2716 for (BasicBlock *BB : R.blocks()) {
2717 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002718 if (!R.contains(L))
2719 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002720 if (BoxedLoops && BoxedLoops->count(L))
2721 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002722 unsigned LD = L->getLoopDepth();
2723 MinLD = std::min(MinLD, LD);
2724 MaxLD = std::max(MaxLD, LD);
2725 }
2726 }
2727
2728 // Handle the case that there is no loop in the SCoP first.
2729 if (MaxLD == 0)
2730 return 1;
2731
2732 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2733 assert(MaxLD >= MinLD &&
2734 "Maximal loop depth was smaller than mininaml loop depth?");
2735 return MaxLD - MinLD + 1;
2736}
2737
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00002738Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, isl_ctx *Context,
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002739 unsigned MaxLoopDepth)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00002740 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002741 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
2742 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Context(nullptr),
2743 Affinator(this), AssumedContext(nullptr), BoundaryContext(nullptr),
2744 Schedule(nullptr) {
Tobias Grosserd840fc72016-02-04 13:18:42 +00002745 buildContext();
2746}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002747
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002748void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002749 DominatorTree &DT, LoopInfo &LI) {
2750 addUserAssumptions(AC, DT, LI);
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002751 buildInvariantEquivalenceClasses(SD);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002752
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002753 buildDomains(&R, SD, DT, LI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002754
Michael Krusecac948e2015-10-02 13:53:07 +00002755 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002756 // Exit early in case there are no executable statements left in this scop.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002757 simplifySCoP(true, DT, LI);
Michael Kruseafe06702015-10-02 16:33:27 +00002758 if (Stmts.empty())
2759 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002760
Michael Krusecac948e2015-10-02 13:53:07 +00002761 // The ScopStmts now have enough information to initialize themselves.
2762 for (ScopStmt &Stmt : Stmts)
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002763 Stmt.init(SD);
Michael Krusecac948e2015-10-02 13:53:07 +00002764
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002765 buildSchedule(SD, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00002766
Tobias Grosser8286b832015-11-02 11:29:32 +00002767 if (isl_set_is_empty(AssumedContext))
2768 return;
2769
2770 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002771 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002772 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002773 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002774 buildBoundaryContext();
2775 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002776 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002777
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002778 hoistInvariantLoads(SD);
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002779 simplifySCoP(false, DT, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00002780}
2781
2782Scop::~Scop() {
2783 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002784 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002785 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002786 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002787
Johannes Doerfert96425c22015-08-30 21:13:53 +00002788 for (auto It : DomainMap)
2789 isl_set_free(It.second);
2790
Johannes Doerfertb164c792014-09-18 11:17:17 +00002791 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002792 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002793 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002794 isl_pw_multi_aff_free(MMA.first);
2795 isl_pw_multi_aff_free(MMA.second);
2796 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002797 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002798 isl_pw_multi_aff_free(MMA.first);
2799 isl_pw_multi_aff_free(MMA.second);
2800 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002801 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002802
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002803 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002804 isl_set_free(std::get<2>(IAClass));
Tobias Grosser75805372011-04-29 06:27:02 +00002805}
2806
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002807void Scop::updateAccessDimensionality() {
2808 for (auto &Stmt : *this)
2809 for (auto &Access : Stmt)
2810 Access->updateDimensionality();
2811}
2812
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002813void Scop::simplifySCoP(bool RemoveIgnoredStmts, DominatorTree &DT,
2814 LoopInfo &LI) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002815 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2816 ScopStmt &Stmt = *StmtIt;
Michael Krusecac948e2015-10-02 13:53:07 +00002817 RegionNode *RN = Stmt.isRegionStmt()
2818 ? Stmt.getRegion()->getNode()
2819 : getRegion().getBBNode(Stmt.getBasicBlock());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002820
Johannes Doerferteca9e892015-11-03 16:54:49 +00002821 bool RemoveStmt = StmtIt->isEmpty();
2822 if (!RemoveStmt)
2823 RemoveStmt = isl_set_is_empty(DomainMap[getRegionNodeBasicBlock(RN)]);
2824 if (!RemoveStmt)
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002825 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN, DT, LI));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002826
Johannes Doerferteca9e892015-11-03 16:54:49 +00002827 // Remove read only statements only after invariant loop hoisting.
2828 if (!RemoveStmt && !RemoveIgnoredStmts) {
2829 bool OnlyRead = true;
2830 for (MemoryAccess *MA : Stmt) {
2831 if (MA->isRead())
2832 continue;
2833
2834 OnlyRead = false;
2835 break;
2836 }
2837
2838 RemoveStmt = OnlyRead;
2839 }
2840
2841 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00002842 // Remove the statement because it is unnecessary.
2843 if (Stmt.isRegionStmt())
2844 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2845 StmtMap.erase(BB);
2846 else
2847 StmtMap.erase(Stmt.getBasicBlock());
2848
2849 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002850 continue;
2851 }
2852
Michael Krusecac948e2015-10-02 13:53:07 +00002853 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002854 }
2855}
2856
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002857const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2858 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2859 if (!LInst)
2860 return nullptr;
2861
2862 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2863 LInst = cast<LoadInst>(Rep);
2864
Johannes Doerfert96e54712016-02-07 17:30:13 +00002865 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002866 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2867 for (auto &IAClass : InvariantEquivClasses)
Johannes Doerfert96e54712016-02-07 17:30:13 +00002868 if (PointerSCEV == std::get<0>(IAClass) && Ty == std::get<3>(IAClass))
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002869 return &IAClass;
2870
2871 return nullptr;
2872}
2873
2874void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2875
2876 // Get the context under which the statement is executed.
2877 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2878 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2879 DomainCtx = isl_set_detect_equalities(DomainCtx);
2880 DomainCtx = isl_set_coalesce(DomainCtx);
2881
2882 // Project out all parameters that relate to loads in the statement. Otherwise
2883 // we could have cyclic dependences on the constraints under which the
2884 // hoisted loads are executed and we could not determine an order in which to
2885 // pre-load them. This happens because not only lower bounds are part of the
2886 // domain but also upper bounds.
2887 for (MemoryAccess *MA : InvMAs) {
2888 Instruction *AccInst = MA->getAccessInstruction();
2889 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00002890 SetVector<Value *> Values;
2891 for (const SCEV *Parameter : Parameters) {
2892 Values.clear();
2893 findValues(Parameter, Values);
2894 if (!Values.count(AccInst))
2895 continue;
2896
2897 if (isl_id *ParamId = getIdForParam(Parameter)) {
2898 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2899 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2900 isl_id_free(ParamId);
2901 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002902 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002903 }
2904 }
2905
2906 for (MemoryAccess *MA : InvMAs) {
2907 // Check for another invariant access that accesses the same location as
2908 // MA and if found consolidate them. Otherwise create a new equivalence
2909 // class at the end of InvariantEquivClasses.
2910 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00002911 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002912 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2913
2914 bool Consolidated = false;
2915 for (auto &IAClass : InvariantEquivClasses) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002916 if (PointerSCEV != std::get<0>(IAClass) || Ty != std::get<3>(IAClass))
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002917 continue;
2918
2919 Consolidated = true;
2920
2921 // Add MA to the list of accesses that are in this class.
2922 auto &MAs = std::get<1>(IAClass);
2923 MAs.push_front(MA);
2924
2925 // Unify the execution context of the class and this statement.
2926 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002927 if (IAClassDomainCtx)
2928 IAClassDomainCtx = isl_set_coalesce(
2929 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
2930 else
2931 IAClassDomainCtx = isl_set_copy(DomainCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002932 break;
2933 }
2934
2935 if (Consolidated)
2936 continue;
2937
2938 // If we did not consolidate MA, thus did not find an equivalence class
2939 // for it, we create a new one.
2940 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
Johannes Doerfert96e54712016-02-07 17:30:13 +00002941 isl_set_copy(DomainCtx), Ty);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002942 }
2943
2944 isl_set_free(DomainCtx);
2945}
2946
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002947bool Scop::isHoistableAccess(MemoryAccess *Access,
2948 __isl_keep isl_union_map *Writes) {
2949 // TODO: Loads that are not loop carried, hence are in a statement with
2950 // zero iterators, are by construction invariant, though we
2951 // currently "hoist" them anyway. This is necessary because we allow
2952 // them to be treated as parameters (e.g., in conditions) and our code
2953 // generation would otherwise use the old value.
2954
2955 auto &Stmt = *Access->getStatement();
2956 BasicBlock *BB =
2957 Stmt.isBlockStmt() ? Stmt.getBasicBlock() : Stmt.getRegion()->getEntry();
2958
2959 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
2960 return false;
2961
2962 // Skip accesses that have an invariant base pointer which is defined but
2963 // not loaded inside the SCoP. This can happened e.g., if a readnone call
2964 // returns a pointer that is used as a base address. However, as we want
2965 // to hoist indirect pointers, we allow the base pointer to be defined in
2966 // the region if it is also a memory access. Each ScopArrayInfo object
2967 // that has a base pointer origin has a base pointer that is loaded and
2968 // that it is invariant, thus it will be hoisted too. However, if there is
2969 // no base pointer origin we check that the base pointer is defined
2970 // outside the region.
2971 const ScopArrayInfo *SAI = Access->getScopArrayInfo();
2972 while (auto *BasePtrOriginSAI = SAI->getBasePtrOriginSAI())
2973 SAI = BasePtrOriginSAI;
2974
2975 if (auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr()))
2976 if (R.contains(BasePtrInst))
2977 return false;
2978
2979 // Skip accesses in non-affine subregions as they might not be executed
2980 // under the same condition as the entry of the non-affine subregion.
2981 if (BB != Access->getAccessInstruction()->getParent())
2982 return false;
2983
2984 isl_map *AccessRelation = Access->getAccessRelation();
2985
2986 // Skip accesses that have an empty access relation. These can be caused
2987 // by multiple offsets with a type cast in-between that cause the overall
2988 // byte offset to be not divisible by the new types sizes.
2989 if (isl_map_is_empty(AccessRelation)) {
2990 isl_map_free(AccessRelation);
2991 return false;
2992 }
2993
2994 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
2995 Stmt.getNumIterators())) {
2996 isl_map_free(AccessRelation);
2997 return false;
2998 }
2999
Johannes Doerfert2353e392016-02-14 23:37:14 +00003000 // See comment above the definition of SAI.
3001 if (SAI->getDerivedSAIs().size()) {
3002 isl_map_free(AccessRelation);
3003 return true;
3004 }
3005
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003006 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3007 isl_set *AccessRange = isl_map_range(AccessRelation);
3008
3009 isl_union_map *Written = isl_union_map_intersect_range(
3010 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
3011 bool IsWritten = !isl_union_map_is_empty(Written);
3012 isl_union_map_free(Written);
3013
3014 if (IsWritten)
3015 return false;
3016
3017 return true;
3018}
3019
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003020void Scop::verifyInvariantLoads(ScopDetection &SD) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003021 auto &RIL = *SD.getRequiredInvariantLoads(&getRegion());
3022 for (LoadInst *LI : RIL) {
3023 assert(LI && getRegion().contains(LI));
3024 ScopStmt *Stmt = getStmtForBasicBlock(LI->getParent());
Tobias Grosser949e8c62015-12-21 07:10:39 +00003025 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003026 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3027 return;
3028 }
3029 }
3030}
3031
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003032void Scop::hoistInvariantLoads(ScopDetection &SD) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003033 isl_union_map *Writes = getWrites();
3034 for (ScopStmt &Stmt : *this) {
3035
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003036 MemoryAccessList InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003037
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003038 for (MemoryAccess *Access : Stmt)
3039 if (isHoistableAccess(Access, Writes))
3040 InvariantAccesses.push_front(Access);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003041
3042 // We inserted invariant accesses always in the front but need them to be
3043 // sorted in a "natural order". The statements are already sorted in reverse
3044 // post order and that suffices for the accesses too. The reason we require
3045 // an order in the first place is the dependences between invariant loads
3046 // that can be caused by indirect loads.
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003047 InvariantAccesses.reverse();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003048
3049 // Transfer the memory access from the statement to the SCoP.
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003050 Stmt.removeMemoryAccesses(InvariantAccesses);
3051 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003052 }
3053 isl_union_map_free(Writes);
3054
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003055 verifyInvariantLoads(SD);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003056}
3057
Johannes Doerfert80ef1102014-11-07 08:31:31 +00003058const ScopArrayInfo *
Tobias Grossercc779502016-02-02 13:22:54 +00003059Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003060 ArrayRef<const SCEV *> Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00003061 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003062 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003063 if (!SAI) {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003064 auto &DL = getRegion().getEntry()->getModule()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003065 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003066 DL, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003067 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003068 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003069 // In case of mismatching array sizes, we bail out by setting the run-time
3070 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003071 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003072 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003073 }
Tobias Grosserab671442015-05-23 05:58:27 +00003074 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003075}
3076
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003077const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00003078 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003079 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003080 assert(SAI && "No ScopArrayInfo available for this base pointer");
3081 return SAI;
3082}
3083
Tobias Grosser74394f02013-01-14 22:40:23 +00003084std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003085std::string Scop::getAssumedContextStr() const {
3086 return stringFromIslObj(AssumedContext);
3087}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003088std::string Scop::getBoundaryContextStr() const {
3089 return stringFromIslObj(BoundaryContext);
3090}
Tobias Grosser75805372011-04-29 06:27:02 +00003091
3092std::string Scop::getNameStr() const {
3093 std::string ExitName, EntryName;
3094 raw_string_ostream ExitStr(ExitName);
3095 raw_string_ostream EntryStr(EntryName);
3096
Tobias Grosserf240b482014-01-09 10:42:15 +00003097 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003098 EntryStr.str();
3099
3100 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003101 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003102 ExitStr.str();
3103 } else
3104 ExitName = "FunctionExit";
3105
3106 return EntryName + "---" + ExitName;
3107}
3108
Tobias Grosser74394f02013-01-14 22:40:23 +00003109__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003110__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003111 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003112}
3113
Tobias Grossere86109f2013-10-29 21:05:49 +00003114__isl_give isl_set *Scop::getAssumedContext() const {
3115 return isl_set_copy(AssumedContext);
3116}
3117
Johannes Doerfert43788c52015-08-20 05:58:56 +00003118__isl_give isl_set *Scop::getRuntimeCheckContext() const {
3119 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003120 RuntimeCheckContext =
3121 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
3122 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00003123 return RuntimeCheckContext;
3124}
3125
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003126bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003127 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003128 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00003129 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
3130 isl_set_free(RuntimeCheckContext);
3131 return IsFeasible;
3132}
3133
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003134static std::string toString(AssumptionKind Kind) {
3135 switch (Kind) {
3136 case ALIASING:
3137 return "No-aliasing";
3138 case INBOUNDS:
3139 return "Inbounds";
3140 case WRAPPING:
3141 return "No-overflows";
Johannes Doerferta4b77c02015-11-12 20:15:32 +00003142 case ALIGNMENT:
3143 return "Alignment";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003144 case ERRORBLOCK:
3145 return "No-error";
3146 case INFINITELOOP:
3147 return "Finite loop";
3148 case INVARIANTLOAD:
3149 return "Invariant load";
3150 case DELINEARIZATION:
3151 return "Delinearization";
Tobias Grosser75dc40c2015-12-20 13:31:48 +00003152 case ERROR_DOMAINCONJUNCTS:
3153 return "Low number of domain conjuncts";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003154 }
3155 llvm_unreachable("Unknown AssumptionKind!");
3156}
3157
3158void Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3159 DebugLoc Loc) {
3160 if (isl_set_is_subset(Context, Set))
3161 return;
3162
3163 if (isl_set_is_subset(AssumedContext, Set))
3164 return;
3165
3166 auto &F = *getRegion().getEntry()->getParent();
3167 std::string Msg = toString(Kind) + " assumption:\t" + stringFromIslObj(Set);
3168 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
3169}
3170
3171void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
3172 DebugLoc Loc) {
3173 trackAssumption(Kind, Set, Loc);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003174 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003175
Johannes Doerfert9d7899e2015-11-11 20:01:31 +00003176 int NSets = isl_set_n_basic_set(AssumedContext);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003177 if (NSets >= MaxDisjunctsAssumed) {
3178 isl_space *Space = isl_set_get_space(AssumedContext);
3179 isl_set_free(AssumedContext);
Tobias Grossere19fca42015-11-11 20:21:39 +00003180 AssumedContext = isl_set_empty(Space);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003181 }
3182
Tobias Grosser7b50bee2014-11-25 10:51:12 +00003183 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003184}
3185
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003186void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
3187 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc);
3188}
3189
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003190__isl_give isl_set *Scop::getBoundaryContext() const {
3191 return isl_set_copy(BoundaryContext);
3192}
3193
Tobias Grosser75805372011-04-29 06:27:02 +00003194void Scop::printContext(raw_ostream &OS) const {
3195 OS << "Context:\n";
3196
3197 if (!Context) {
3198 OS.indent(4) << "n/a\n\n";
3199 return;
3200 }
3201
3202 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003203
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003204 OS.indent(4) << "Assumed Context:\n";
3205 if (!AssumedContext) {
3206 OS.indent(4) << "n/a\n\n";
3207 return;
3208 }
3209
3210 OS.indent(4) << getAssumedContextStr() << "\n";
3211
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003212 OS.indent(4) << "Boundary Context:\n";
3213 if (!BoundaryContext) {
3214 OS.indent(4) << "n/a\n\n";
3215 return;
3216 }
3217
3218 OS.indent(4) << getBoundaryContextStr() << "\n";
3219
Tobias Grosser083d3d32014-06-28 08:59:45 +00003220 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00003221 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00003222 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
3223 }
Tobias Grosser75805372011-04-29 06:27:02 +00003224}
3225
Johannes Doerfertb164c792014-09-18 11:17:17 +00003226void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003227 int noOfGroups = 0;
3228 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003229 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003230 noOfGroups += 1;
3231 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003232 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003233 }
3234
Tobias Grosserbb853c22015-07-25 12:31:03 +00003235 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003236 if (MinMaxAliasGroups.empty()) {
3237 OS.indent(8) << "n/a\n";
3238 return;
3239 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003240
Tobias Grosserbb853c22015-07-25 12:31:03 +00003241 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003242
3243 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003244 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003245 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003246 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003247 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3248 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003249 }
3250 OS << " ]]\n";
3251 }
3252
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003253 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003254 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003255 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003256 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003257 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3258 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003259 }
3260 OS << " ]]\n";
3261 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003262 }
3263}
3264
Tobias Grosser75805372011-04-29 06:27:02 +00003265void Scop::printStatements(raw_ostream &OS) const {
3266 OS << "Statements {\n";
3267
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003268 for (const ScopStmt &Stmt : *this)
3269 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003270
3271 OS.indent(4) << "}\n";
3272}
3273
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003274void Scop::printArrayInfo(raw_ostream &OS) const {
3275 OS << "Arrays {\n";
3276
Tobias Grosserab671442015-05-23 05:58:27 +00003277 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003278 Array.second->print(OS);
3279
3280 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003281
3282 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3283
3284 for (auto &Array : arrays())
3285 Array.second->print(OS, /* SizeAsPwAff */ true);
3286
3287 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003288}
3289
Tobias Grosser75805372011-04-29 06:27:02 +00003290void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00003291 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
3292 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003293 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003294 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003295 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003296 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003297 const auto &MAs = std::get<1>(IAClass);
3298 if (MAs.empty()) {
3299 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003300 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003301 MAs.front()->print(OS);
3302 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003303 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003304 }
3305 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003306 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003307 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003308 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003309 printStatements(OS.indent(4));
3310}
3311
3312void Scop::dump() const { print(dbgs()); }
3313
Tobias Grosser9a38ab82011-11-08 15:41:03 +00003314isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00003315
Johannes Doerfertcef616f2015-09-15 22:49:04 +00003316__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
3317 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003318}
3319
Tobias Grosser808cd692015-07-14 09:33:13 +00003320__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003321 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003322
Tobias Grosser808cd692015-07-14 09:33:13 +00003323 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003324 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003325
3326 return Domain;
3327}
3328
Tobias Grossere5a35142015-11-12 14:07:09 +00003329__isl_give isl_union_map *
3330Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3331 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003332
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003333 for (ScopStmt &Stmt : *this) {
3334 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003335 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003336 continue;
3337
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003338 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003339 isl_map *AccessDomain = MA->getAccessRelation();
3340 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003341 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003342 }
3343 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003344 return isl_union_map_coalesce(Accesses);
3345}
3346
3347__isl_give isl_union_map *Scop::getMustWrites() {
3348 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003349}
3350
3351__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003352 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003353}
3354
Tobias Grosser37eb4222014-02-20 21:43:54 +00003355__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003356 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003357}
3358
3359__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003360 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003361}
3362
Tobias Grosser2ac23382015-11-12 14:07:13 +00003363__isl_give isl_union_map *Scop::getAccesses() {
3364 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3365}
3366
Tobias Grosser808cd692015-07-14 09:33:13 +00003367__isl_give isl_union_map *Scop::getSchedule() const {
3368 auto Tree = getScheduleTree();
3369 auto S = isl_schedule_get_map(Tree);
3370 isl_schedule_free(Tree);
3371 return S;
3372}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003373
Tobias Grosser808cd692015-07-14 09:33:13 +00003374__isl_give isl_schedule *Scop::getScheduleTree() const {
3375 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3376 getDomains());
3377}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003378
Tobias Grosser808cd692015-07-14 09:33:13 +00003379void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3380 auto *S = isl_schedule_from_domain(getDomains());
3381 S = isl_schedule_insert_partial_schedule(
3382 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3383 isl_schedule_free(Schedule);
3384 Schedule = S;
3385}
3386
3387void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3388 isl_schedule_free(Schedule);
3389 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003390}
3391
3392bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3393 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003394 for (ScopStmt &Stmt : *this) {
3395 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003396 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3397 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3398
3399 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3400 isl_union_set_free(StmtDomain);
3401 isl_union_set_free(NewStmtDomain);
3402 continue;
3403 }
3404
3405 Changed = true;
3406
3407 isl_union_set_free(StmtDomain);
3408 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3409
3410 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003411 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003412 isl_union_set_free(NewStmtDomain);
3413 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003414 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003415 }
3416 isl_union_set_free(Domain);
3417 return Changed;
3418}
3419
Tobias Grosser75805372011-04-29 06:27:02 +00003420ScalarEvolution *Scop::getSE() const { return SE; }
3421
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003422bool Scop::isIgnored(RegionNode *RN, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003423 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Michael Krusea902ba62015-12-13 19:21:45 +00003424 ScopStmt *Stmt = getStmtForRegionNode(RN);
3425
3426 // If there is no stmt, then it already has been removed.
3427 if (!Stmt)
3428 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00003429
Johannes Doerfertf5673802015-10-01 23:48:18 +00003430 // Check if there are accesses contained.
Michael Krusea902ba62015-12-13 19:21:45 +00003431 if (Stmt->isEmpty())
Johannes Doerfertf5673802015-10-01 23:48:18 +00003432 return true;
3433
3434 // Check for reachability via non-error blocks.
3435 if (!DomainMap.count(BB))
3436 return true;
3437
3438 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003439 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003440 return true;
3441
3442 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003443}
3444
Tobias Grosser808cd692015-07-14 09:33:13 +00003445struct MapToDimensionDataTy {
3446 int N;
3447 isl_union_pw_multi_aff *Res;
3448};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003449
Tobias Grosser808cd692015-07-14 09:33:13 +00003450// @brief Create a function that maps the elements of 'Set' to its N-th
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003451// dimension and add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00003452//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003453// @param Set The input set.
3454// @param User->N The dimension to map to.
3455// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00003456//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003457// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00003458static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3459 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3460 int Dim;
3461 isl_space *Space;
3462 isl_pw_multi_aff *PMA;
3463
3464 Dim = isl_set_dim(Set, isl_dim_set);
3465 Space = isl_set_get_space(Set);
3466 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3467 Dim - Data->N);
3468 if (Data->N > 1)
3469 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3470 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3471
3472 isl_set_free(Set);
3473
3474 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003475}
3476
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003477// @brief Create an isl_multi_union_aff that defines an identity mapping
3478// from the elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003479//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003480// # Example:
3481//
3482// Domain: { A[i,j]; B[i,j,k] }
3483// N: 1
3484//
3485// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
3486//
3487// @param USet A union set describing the elements for which to generate a
3488// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00003489// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003490// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003491static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003492mapToDimension(__isl_take isl_union_set *USet, int N) {
3493 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00003494 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003495 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003496
Tobias Grosser808cd692015-07-14 09:33:13 +00003497 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00003498
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003499 auto *Space = isl_union_set_get_space(USet);
3500 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00003501
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003502 Data = {N, PwAff};
3503
3504 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
3505
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00003506 (void)Res;
3507
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003508 assert(Res == isl_stat_ok);
3509
3510 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00003511 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3512}
3513
Tobias Grosser316b5b22015-11-11 19:28:14 +00003514void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003515 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003516 Stmts.emplace_back(*this, *BB);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003517 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003518 StmtMap[BB] = Stmt;
3519 } else {
3520 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003521 Stmts.emplace_back(*this, *R);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003522 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003523 for (BasicBlock *BB : R->blocks())
3524 StmtMap[BB] = Stmt;
3525 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003526}
3527
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003528void Scop::buildSchedule(ScopDetection &SD, LoopInfo &LI) {
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003529 Loop *L = getLoopSurroundingRegion(getRegion(), LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003530 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003531 buildSchedule(getRegion().getNode(), LoopStack, SD, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003532 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
3533 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003534}
3535
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003536/// To generate a schedule for the elements in a Region we traverse the Region
3537/// in reverse-post-order and add the contained RegionNodes in traversal order
3538/// to the schedule of the loop that is currently at the top of the LoopStack.
3539/// For loop-free codes, this results in a correct sequential ordering.
3540///
3541/// Example:
3542/// bb1(0)
3543/// / \.
3544/// bb2(1) bb3(2)
3545/// \ / \.
3546/// bb4(3) bb5(4)
3547/// \ /
3548/// bb6(5)
3549///
3550/// Including loops requires additional processing. Whenever a loop header is
3551/// encountered, the corresponding loop is added to the @p LoopStack. Starting
3552/// from an empty schedule, we first process all RegionNodes that are within
3553/// this loop and complete the sequential schedule at this loop-level before
3554/// processing about any other nodes. To implement this
3555/// loop-nodes-first-processing, the reverse post-order traversal is
3556/// insufficient. Hence, we additionally check if the traversal yields
3557/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
3558/// These region-nodes are then queue and only traverse after the all nodes
3559/// within the current loop have been processed.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003560void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, ScopDetection &SD,
3561 LoopInfo &LI) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003562 Loop *OuterScopLoop = getLoopSurroundingRegion(getRegion(), LI);
3563
3564 ReversePostOrderTraversal<Region *> RTraversal(R);
3565 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
3566 std::deque<RegionNode *> DelayList;
3567 bool LastRNWaiting = false;
3568
3569 // Iterate over the region @p R in reverse post-order but queue
3570 // sub-regions/blocks iff they are not part of the last encountered but not
3571 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
3572 // that we queued the last sub-region/block from the reverse post-order
3573 // iterator. If it is set we have to explore the next sub-region/block from
3574 // the iterator (if any) to guarantee progress. If it is not set we first try
3575 // the next queued sub-region/blocks.
3576 while (!WorkList.empty() || !DelayList.empty()) {
3577 RegionNode *RN;
3578
3579 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
3580 RN = WorkList.front();
3581 WorkList.pop_front();
3582 LastRNWaiting = false;
3583 } else {
3584 RN = DelayList.front();
3585 DelayList.pop_front();
3586 }
3587
3588 Loop *L = getRegionNodeLoop(RN, LI);
3589 if (!getRegion().contains(L))
3590 L = OuterScopLoop;
3591
3592 Loop *LastLoop = LoopStack.back().L;
3593 if (LastLoop != L) {
3594 if (!LastLoop->contains(L)) {
3595 LastRNWaiting = true;
3596 DelayList.push_back(RN);
3597 continue;
3598 }
3599 LoopStack.push_back({L, nullptr, 0});
3600 }
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003601 buildSchedule(RN, LoopStack, SD, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003602 }
3603
3604 return;
3605}
3606
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003607void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003608 ScopDetection &SD, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00003609
Tobias Grosser8362c262016-01-06 15:30:06 +00003610 if (RN->isSubRegion()) {
3611 auto *LocalRegion = RN->getNodeAs<Region>();
3612 if (!SD.isNonAffineSubRegion(LocalRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003613 buildSchedule(LocalRegion, LoopStack, SD, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00003614 return;
3615 }
3616 }
Michael Kruse046dde42015-08-10 13:01:57 +00003617
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003618 auto &LoopData = LoopStack.back();
3619 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00003620
Tobias Grosserc9abde82016-01-23 20:23:06 +00003621 if (auto *Stmt = getStmtForRegionNode(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00003622 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3623 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003624 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00003625 }
3626
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003627 // Check if we just processed the last node in this loop. If we did, finalize
3628 // the loop by:
3629 //
3630 // - adding new schedule dimensions
3631 // - folding the resulting schedule into the parent loop schedule
3632 // - dropping the loop schedule from the LoopStack.
3633 //
3634 // Then continue to check surrounding loops, which might also have been
3635 // completed by this node.
3636 while (LoopData.L &&
3637 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
3638 auto Schedule = LoopData.Schedule;
3639 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00003640
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003641 LoopStack.pop_back();
3642 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00003643
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003644 if (Schedule) {
3645 auto *Domain = isl_schedule_get_domain(Schedule);
3646 auto *MUPA = mapToDimension(Domain, LoopStack.size());
3647 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
3648 NextLoopData.Schedule =
3649 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003650 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003651
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003652 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
3653 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00003654 }
Tobias Grosser75805372011-04-29 06:27:02 +00003655}
3656
Johannes Doerfert7c494212014-10-31 23:13:39 +00003657ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003658 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003659 if (StmtMapIt == StmtMap.end())
3660 return nullptr;
3661 return StmtMapIt->second;
3662}
3663
Michael Krusea902ba62015-12-13 19:21:45 +00003664ScopStmt *Scop::getStmtForRegionNode(RegionNode *RN) const {
3665 return getStmtForBasicBlock(getRegionNodeBasicBlock(RN));
3666}
3667
Johannes Doerfert96425c22015-08-30 21:13:53 +00003668int Scop::getRelativeLoopDepth(const Loop *L) const {
3669 Loop *OuterLoop =
3670 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3671 if (!OuterLoop)
3672 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003673 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3674}
3675
Michael Krused868b5d2015-09-10 15:25:24 +00003676void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003677 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003678
3679 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3680 // true, are not modeled as ordinary PHI nodes as they are not part of the
3681 // region. However, we model the operands in the predecessor blocks that are
3682 // part of the region as regular scalar accesses.
3683
3684 // If we can synthesize a PHI we can skip it, however only if it is in
3685 // the region. If it is not it can only be in the exit block of the region.
3686 // In this case we model the operands but not the PHI itself.
3687 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3688 return;
3689
3690 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3691 // detection. Hence, the PHI is a load of a new memory location in which the
3692 // incoming value was written at the end of the incoming basic block.
3693 bool OnlyNonAffineSubRegionOperands = true;
3694 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3695 Value *Op = PHI->getIncomingValue(u);
3696 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3697
3698 // Do not build scalar dependences inside a non-affine subregion.
3699 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3700 continue;
3701
3702 OnlyNonAffineSubRegionOperands = false;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00003703 ensurePHIWrite(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003704 }
3705
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003706 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3707 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003708 }
3709}
3710
Michael Kruse2e02d562016-02-06 09:19:40 +00003711void ScopInfo::buildScalarDependences(Instruction *Inst) {
3712 assert(!isa<PHINode>(Inst));
Michael Kruse7bf39442015-09-10 12:46:52 +00003713
Michael Kruse2e02d562016-02-06 09:19:40 +00003714 // Pull-in required operands.
3715 for (Use &Op : Inst->operands())
3716 ensureValueRead(Op.get(), Inst->getParent());
3717}
Michael Kruse7bf39442015-09-10 12:46:52 +00003718
Michael Kruse2e02d562016-02-06 09:19:40 +00003719void ScopInfo::buildEscapingDependences(Instruction *Inst) {
3720 Region *R = &scop->getRegion();
Michael Kruse7bf39442015-09-10 12:46:52 +00003721
Michael Kruse2e02d562016-02-06 09:19:40 +00003722 // Check for uses of this instruction outside the scop. Because we do not
3723 // iterate over such instructions and therefore did not "ensure" the existence
3724 // of a write, we must determine such use here.
3725 for (Use &U : Inst->uses()) {
3726 Instruction *UI = dyn_cast<Instruction>(U.getUser());
3727 if (!UI)
Michael Kruse7bf39442015-09-10 12:46:52 +00003728 continue;
3729
Michael Kruse2e02d562016-02-06 09:19:40 +00003730 BasicBlock *UseParent = getUseBlock(U);
3731 BasicBlock *UserParent = UI->getParent();
Michael Kruse7bf39442015-09-10 12:46:52 +00003732
Michael Kruse2e02d562016-02-06 09:19:40 +00003733 // An escaping value is either used by an instruction not within the scop,
3734 // or (when the scop region's exit needs to be simplified) by a PHI in the
3735 // scop's exit block. This is because region simplification before code
3736 // generation inserts new basic blocks before the PHI such that its incoming
3737 // blocks are not in the scop anymore.
3738 if (!R->contains(UseParent) ||
3739 (isa<PHINode>(UI) && UserParent == R->getExit() &&
3740 R->getExitingBlock())) {
3741 // At least one escaping use found.
3742 ensureValueWrite(Inst);
3743 break;
Michael Kruse7bf39442015-09-10 12:46:52 +00003744 }
3745 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003746}
3747
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003748bool ScopInfo::buildAccessMultiDimFixed(
Michael Kruse70131d32016-01-27 17:09:17 +00003749 MemAccInst Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003750 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3751 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse70131d32016-01-27 17:09:17 +00003752 Value *Val = Inst.getValueOperand();
3753 Type *SizeType = Val->getType();
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003754 unsigned ElementSize = DL->getTypeAllocSize(SizeType);
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003755 Value *Address = Inst.getPointerOperand();
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003756 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003757 const SCEVUnknown *BasePointer =
3758 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003759 enum MemoryAccess::AccessType Type =
3760 Inst.isLoad() ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003761
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003762 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3763 auto NewAddress = Address;
3764 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3765 auto Src = BitCast->getOperand(0);
3766 auto SrcTy = Src->getType();
3767 auto DstTy = BitCast->getType();
3768 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3769 NewAddress = Src;
3770 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003771
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003772 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3773 std::vector<const SCEV *> Subscripts;
3774 std::vector<int> Sizes;
3775 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3776 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003777
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003778 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003779
Johannes Doerfert09e36972015-10-07 20:17:36 +00003780 for (auto Subscript : Subscripts) {
3781 InvariantLoadsSetTy AccessILS;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003782 if (!isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS))
3783 return false;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003784
3785 for (LoadInst *LInst : AccessILS)
3786 if (!ScopRIL.count(LInst))
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003787 return false;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003788 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003789
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003790 if (Sizes.size() > 0) {
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003791 for (auto V : Sizes)
3792 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3793 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003794
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003795 addArrayAccess(Inst, Type, BasePointer->getValue(), ElementSize, true,
Tobias Grossera535dff2015-12-13 19:59:01 +00003796 Subscripts, SizesSCEV, Val);
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003797 return true;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003798 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003799 }
3800 }
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003801 return false;
3802}
3803
3804bool ScopInfo::buildAccessMultiDimParam(
3805 MemAccInst Inst, Loop *L, Region *R,
3806 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
Hongbin Zheng22623202016-02-15 00:20:58 +00003807 const InvariantLoadsSetTy &ScopRIL, const MapInsnToMemAcc &InsnToMemAcc) {
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003808 Value *Address = Inst.getPointerOperand();
3809 Value *Val = Inst.getValueOperand();
3810 Type *SizeType = Val->getType();
3811 unsigned ElementSize = DL->getTypeAllocSize(SizeType);
3812 enum MemoryAccess::AccessType Type =
3813 Inst.isLoad() ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
3814
3815 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
3816 const SCEVUnknown *BasePointer =
3817 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3818
3819 assert(BasePointer && "Could not find base pointer");
3820 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003821
Michael Kruse7bf39442015-09-10 12:46:52 +00003822 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003823 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003824 std::vector<const SCEV *> Sizes(
3825 AccItr->second.Shape->DelinearizedSizes.begin(),
3826 AccItr->second.Shape->DelinearizedSizes.end());
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003827 // Remove the element size. This information is already provided by the
Tobias Grosserd840fc72016-02-04 13:18:42 +00003828 // ElementSize parameter. In case the element size of this access and the
3829 // element size used for delinearization differs the delinearization is
3830 // incorrect. Hence, we invalidate the scop.
3831 //
3832 // TODO: Handle delinearization with differing element sizes.
3833 auto DelinearizedSize =
3834 cast<SCEVConstant>(Sizes.back())->getAPInt().getSExtValue();
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003835 Sizes.pop_back();
Tobias Grosserd840fc72016-02-04 13:18:42 +00003836 if (ElementSize != DelinearizedSize)
3837 scop->invalidate(DELINEARIZATION, Inst.getDebugLoc());
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003838
3839 addArrayAccess(Inst, Type, BasePointer->getValue(), ElementSize, true,
3840 AccItr->second.DelinearizedSubscripts, Sizes, Val);
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003841 return true;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003842 }
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003843 return false;
3844}
3845
3846void ScopInfo::buildAccessSingleDim(
3847 MemAccInst Inst, Loop *L, Region *R,
3848 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3849 const InvariantLoadsSetTy &ScopRIL) {
3850 Value *Address = Inst.getPointerOperand();
3851 Value *Val = Inst.getValueOperand();
3852 Type *SizeType = Val->getType();
3853 unsigned ElementSize = DL->getTypeAllocSize(SizeType);
3854 enum MemoryAccess::AccessType Type =
3855 Inst.isLoad() ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
3856
3857 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
3858 const SCEVUnknown *BasePointer =
3859 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3860
3861 assert(BasePointer && "Could not find base pointer");
3862 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
Michael Kruse7bf39442015-09-10 12:46:52 +00003863
3864 // Check if the access depends on a loop contained in a non-affine subregion.
3865 bool isVariantInNonAffineLoop = false;
3866 if (BoxedLoops) {
3867 SetVector<const Loop *> Loops;
3868 findLoops(AccessFunction, Loops);
3869 for (const Loop *L : Loops)
3870 if (BoxedLoops->count(L))
3871 isVariantInNonAffineLoop = true;
3872 }
3873
Johannes Doerfert09e36972015-10-07 20:17:36 +00003874 InvariantLoadsSetTy AccessILS;
3875 bool IsAffine =
3876 !isVariantInNonAffineLoop &&
3877 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3878
3879 for (LoadInst *LInst : AccessILS)
3880 if (!ScopRIL.count(LInst))
3881 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003882
Michael Krusee2bccbb2015-09-18 19:59:43 +00003883 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3884 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003885
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003886 addArrayAccess(Inst, Type, BasePointer->getValue(), ElementSize, IsAffine,
3887 {AccessFunction}, {}, Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003888}
3889
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003890void ScopInfo::buildMemoryAccess(
3891 MemAccInst Inst, Loop *L, Region *R,
3892 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
Hongbin Zheng22623202016-02-15 00:20:58 +00003893 const InvariantLoadsSetTy &ScopRIL, const MapInsnToMemAcc &InsnToMemAcc) {
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003894
3895 if (buildAccessMultiDimFixed(Inst, L, R, BoxedLoops, ScopRIL))
3896 return;
3897
Hongbin Zheng22623202016-02-15 00:20:58 +00003898 if (buildAccessMultiDimParam(Inst, L, R, BoxedLoops, ScopRIL, InsnToMemAcc))
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003899 return;
3900
3901 buildAccessSingleDim(Inst, L, R, BoxedLoops, ScopRIL);
3902}
3903
Hongbin Zheng22623202016-02-15 00:20:58 +00003904void ScopInfo::buildAccessFunctions(Region &R, Region &SR,
3905 const MapInsnToMemAcc &InsnToMemAcc) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003906
3907 if (SD->isNonAffineSubRegion(&SR, &R)) {
3908 for (BasicBlock *BB : SR.blocks())
Hongbin Zheng22623202016-02-15 00:20:58 +00003909 buildAccessFunctions(R, *BB, InsnToMemAcc, &SR);
Michael Kruse7bf39442015-09-10 12:46:52 +00003910 return;
3911 }
3912
3913 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3914 if (I->isSubRegion())
Hongbin Zheng22623202016-02-15 00:20:58 +00003915 buildAccessFunctions(R, *I->getNodeAs<Region>(), InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00003916 else
Hongbin Zheng22623202016-02-15 00:20:58 +00003917 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>(), InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00003918}
3919
Johannes Doerferta8781032016-02-02 14:14:40 +00003920void ScopInfo::buildStmts(Region &R, Region &SR) {
Michael Krusecac948e2015-10-02 13:53:07 +00003921
Johannes Doerferta8781032016-02-02 14:14:40 +00003922 if (SD->isNonAffineSubRegion(&SR, &R)) {
Michael Krusecac948e2015-10-02 13:53:07 +00003923 scop->addScopStmt(nullptr, &SR);
3924 return;
3925 }
3926
3927 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3928 if (I->isSubRegion())
Johannes Doerferta8781032016-02-02 14:14:40 +00003929 buildStmts(R, *I->getNodeAs<Region>());
Michael Krusecac948e2015-10-02 13:53:07 +00003930 else
3931 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
3932}
3933
Michael Krused868b5d2015-09-10 15:25:24 +00003934void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
Hongbin Zheng22623202016-02-15 00:20:58 +00003935 const MapInsnToMemAcc &InsnToMemAcc,
Michael Krused868b5d2015-09-10 15:25:24 +00003936 Region *NonAffineSubRegion,
3937 bool IsExitBlock) {
Tobias Grosser910cf262015-11-11 20:15:49 +00003938 // We do not build access functions for error blocks, as they may contain
3939 // instructions we can not model.
Johannes Doerfertc36d39b2016-02-02 14:14:20 +00003940 if (isErrorBlock(BB, R, *LI, *DT) && !IsExitBlock)
Tobias Grosser910cf262015-11-11 20:15:49 +00003941 return;
3942
Michael Kruse7bf39442015-09-10 12:46:52 +00003943 Loop *L = LI->getLoopFor(&BB);
3944
3945 // The set of loops contained in non-affine subregions that are part of R.
3946 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3947
Johannes Doerfert09e36972015-10-07 20:17:36 +00003948 // The set of loads that are required to be invariant.
3949 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
3950
Michael Kruse2e02d562016-02-06 09:19:40 +00003951 for (Instruction &Inst : BB) {
3952 PHINode *PHI = dyn_cast<PHINode>(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003953 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003954 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003955
3956 // For the exit block we stop modeling after the last PHI node.
3957 if (!PHI && IsExitBlock)
3958 break;
3959
Johannes Doerfert09e36972015-10-07 20:17:36 +00003960 // TODO: At this point we only know that elements of ScopRIL have to be
3961 // invariant and will be hoisted for the SCoP to be processed. Though,
3962 // there might be other invariant accesses that will be hoisted and
3963 // that would allow to make a non-affine access affine.
Michael Kruse70131d32016-01-27 17:09:17 +00003964 if (auto MemInst = MemAccInst::dyn_cast(Inst))
Hongbin Zheng22623202016-02-15 00:20:58 +00003965 buildMemoryAccess(MemInst, L, &R, BoxedLoops, ScopRIL, InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00003966
Michael Kruse2e02d562016-02-06 09:19:40 +00003967 if (isIgnoredIntrinsic(&Inst))
Michael Kruse7bf39442015-09-10 12:46:52 +00003968 continue;
3969
Michael Kruse2e02d562016-02-06 09:19:40 +00003970 if (!PHI)
3971 buildScalarDependences(&Inst);
3972 if (!IsExitBlock)
3973 buildEscapingDependences(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003974 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003975}
Michael Kruse7bf39442015-09-10 12:46:52 +00003976
Michael Kruseee6a4fc2016-01-26 13:33:27 +00003977MemoryAccess *ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3978 MemoryAccess::AccessType Type,
3979 Value *BaseAddress, unsigned ElemBytes,
3980 bool Affine, Value *AccessValue,
3981 ArrayRef<const SCEV *> Subscripts,
3982 ArrayRef<const SCEV *> Sizes,
3983 ScopArrayInfo::MemoryKind Kind) {
Michael Krusecac948e2015-10-02 13:53:07 +00003984 ScopStmt *Stmt = scop->getStmtForBasicBlock(BB);
3985
3986 // Do not create a memory access for anything not in the SCoP. It would be
3987 // ignored anyway.
3988 if (!Stmt)
Michael Kruseee6a4fc2016-01-26 13:33:27 +00003989 return nullptr;
Michael Krusecac948e2015-10-02 13:53:07 +00003990
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00003991 AccFuncSetType &AccList = scop->getOrCreateAccessFunctions(BB);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003992 Value *BaseAddr = BaseAddress;
3993 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3994
Tobias Grosserf4f68702015-12-14 15:05:37 +00003995 bool isKnownMustAccess = false;
3996
3997 // Accesses in single-basic block statements are always excuted.
3998 if (Stmt->isBlockStmt())
3999 isKnownMustAccess = true;
4000
4001 if (Stmt->isRegionStmt()) {
4002 // Accesses that dominate the exit block of a non-affine region are always
4003 // executed. In non-affine regions there may exist MK_Values that do not
4004 // dominate the exit. MK_Values will always dominate the exit and MK_PHIs
4005 // only if there is at most one PHI_WRITE in the non-affine region.
4006 if (DT->dominates(BB, Stmt->getRegion()->getExit()))
4007 isKnownMustAccess = true;
4008 }
4009
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004010 // Non-affine PHI writes do not "happen" at a particular instruction, but
4011 // after exiting the statement. Therefore they are guaranteed execute and
4012 // overwrite the old value.
4013 if (Kind == ScopArrayInfo::MK_PHI || Kind == ScopArrayInfo::MK_ExitPHI)
4014 isKnownMustAccess = true;
4015
Tobias Grosserf4f68702015-12-14 15:05:37 +00004016 if (!isKnownMustAccess && Type == MemoryAccess::MUST_WRITE)
Michael Krusecac948e2015-10-02 13:53:07 +00004017 Type = MemoryAccess::MAY_WRITE;
4018
Tobias Grosserf1bfd752015-11-05 20:15:37 +00004019 AccList.emplace_back(Stmt, Inst, Type, BaseAddress, ElemBytes, Affine,
Tobias Grossera535dff2015-12-13 19:59:01 +00004020 Subscripts, Sizes, AccessValue, Kind, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00004021 Stmt->addAccess(&AccList.back());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004022 return &AccList.back();
Michael Kruse7bf39442015-09-10 12:46:52 +00004023}
4024
Michael Kruse70131d32016-01-27 17:09:17 +00004025void ScopInfo::addArrayAccess(MemAccInst MemAccInst,
Tobias Grossera535dff2015-12-13 19:59:01 +00004026 MemoryAccess::AccessType Type, Value *BaseAddress,
4027 unsigned ElemBytes, bool IsAffine,
4028 ArrayRef<const SCEV *> Subscripts,
4029 ArrayRef<const SCEV *> Sizes,
4030 Value *AccessValue) {
Michael Kruse70131d32016-01-27 17:09:17 +00004031 assert(MemAccInst.isLoad() == (Type == MemoryAccess::READ));
4032 addMemoryAccess(MemAccInst.getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00004033 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00004034 ScopArrayInfo::MK_Array);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004035}
Michael Kruse436db622016-01-26 13:33:10 +00004036void ScopInfo::ensureValueWrite(Instruction *Value) {
4037 ScopStmt *Stmt = scop->getStmtForBasicBlock(Value->getParent());
4038
4039 // Value not defined within this SCoP.
4040 if (!Stmt)
4041 return;
4042
4043 // Do not process further if the value is already written.
4044 if (Stmt->lookupValueWriteOf(Value))
4045 return;
4046
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004047 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
4048 true, Value, ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004049 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004050}
Michael Krusead28e5a2016-01-26 13:33:15 +00004051void ScopInfo::ensureValueRead(Value *Value, BasicBlock *UserBB) {
Michael Krusefd463082016-01-27 22:51:56 +00004052
Michael Kruse2e02d562016-02-06 09:19:40 +00004053 // There cannot be an "access" for literal constants. BasicBlock references
4054 // (jump destinations) also never change.
4055 if ((isa<Constant>(Value) && !isa<GlobalVariable>(Value)) ||
4056 isa<BasicBlock>(Value))
4057 return;
4058
Michael Krusefd463082016-01-27 22:51:56 +00004059 // If the instruction can be synthesized and the user is in the region we do
4060 // not need to add a value dependences.
4061 Region &ScopRegion = scop->getRegion();
4062 if (canSynthesize(Value, LI, SE, &ScopRegion))
4063 return;
4064
Michael Kruse2e02d562016-02-06 09:19:40 +00004065 // Do not build scalar dependences for required invariant loads as we will
4066 // hoist them later on anyway or drop the SCoP if we cannot.
4067 auto ScopRIL = SD->getRequiredInvariantLoads(&ScopRegion);
4068 if (ScopRIL->count(dyn_cast<LoadInst>(Value)))
4069 return;
4070
4071 // Determine the ScopStmt containing the value's definition and use. There is
4072 // no defining ScopStmt if the value is a function argument, a global value,
4073 // or defined outside the SCoP.
4074 Instruction *ValueInst = dyn_cast<Instruction>(Value);
4075 ScopStmt *ValueStmt =
4076 ValueInst ? scop->getStmtForBasicBlock(ValueInst->getParent()) : nullptr;
4077
Michael Krusead28e5a2016-01-26 13:33:15 +00004078 ScopStmt *UserStmt = scop->getStmtForBasicBlock(UserBB);
4079
4080 // We do not model uses outside the scop.
4081 if (!UserStmt)
4082 return;
4083
Michael Kruse2e02d562016-02-06 09:19:40 +00004084 // Add MemoryAccess for invariant values only if requested.
4085 if (!ModelReadOnlyScalars && !ValueStmt)
4086 return;
4087
4088 // Ignore use-def chains within the same ScopStmt.
4089 if (ValueStmt == UserStmt)
4090 return;
4091
Michael Krusead28e5a2016-01-26 13:33:15 +00004092 // Do not create another MemoryAccess for reloading the value if one already
4093 // exists.
4094 if (UserStmt->lookupValueReadOf(Value))
4095 return;
4096
4097 addMemoryAccess(UserBB, nullptr, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00004098 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004099 ScopArrayInfo::MK_Value);
Michael Kruse2e02d562016-02-06 09:19:40 +00004100 if (ValueInst)
4101 ensureValueWrite(ValueInst);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004102}
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004103void ScopInfo::ensurePHIWrite(PHINode *PHI, BasicBlock *IncomingBlock,
4104 Value *IncomingValue, bool IsExitBlock) {
4105 ScopStmt *IncomingStmt = scop->getStmtForBasicBlock(IncomingBlock);
Michael Kruse2e02d562016-02-06 09:19:40 +00004106 if (!IncomingStmt)
4107 return;
4108
4109 // Take care for the incoming value being available in the incoming block.
4110 // This must be done before the check for multiple PHI writes because multiple
4111 // exiting edges from subregion each can be the effective written value of the
4112 // subregion. As such, all of them must be made available in the subregion
4113 // statement.
4114 ensureValueRead(IncomingValue, IncomingBlock);
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004115
4116 // Do not add more than one MemoryAccess per PHINode and ScopStmt.
4117 if (MemoryAccess *Acc = IncomingStmt->lookupPHIWriteOf(PHI)) {
4118 assert(Acc->getAccessInstruction() == PHI);
4119 Acc->addIncoming(IncomingBlock, IncomingValue);
4120 return;
4121 }
4122
4123 MemoryAccess *Acc = addMemoryAccess(
4124 IncomingStmt->isBlockStmt() ? IncomingBlock
4125 : IncomingStmt->getRegion()->getEntry(),
4126 PHI, MemoryAccess::MUST_WRITE, PHI, 1, true, PHI,
4127 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
4128 IsExitBlock ? ScopArrayInfo::MK_ExitPHI : ScopArrayInfo::MK_PHI);
4129 assert(Acc);
4130 Acc->addIncoming(IncomingBlock, IncomingValue);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004131}
4132void ScopInfo::addPHIReadAccess(PHINode *PHI) {
4133 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00004134 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004135 ScopArrayInfo::MK_PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004136}
4137
Michael Krusedaf66942015-12-13 22:10:37 +00004138void ScopInfo::buildScop(Region &R, AssumptionCache &AC) {
Michael Kruse9d080092015-09-11 21:41:48 +00004139 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Hongbin Zhengfec32802016-02-13 15:13:02 +00004140 scop.reset(new Scop(R, *SE, ctx, MaxLoopDepth));
Michael Kruse7bf39442015-09-10 12:46:52 +00004141
Johannes Doerferta8781032016-02-02 14:14:40 +00004142 buildStmts(R, R);
Hongbin Zheng22623202016-02-15 00:20:58 +00004143 buildAccessFunctions(R, R, *SD->getInsnToMemAccMap(&R));
Michael Kruse7bf39442015-09-10 12:46:52 +00004144
4145 // In case the region does not have an exiting block we will later (during
4146 // code generation) split the exit block. This will move potential PHI nodes
4147 // from the current exit block into the new region exiting block. Hence, PHI
4148 // nodes that are at this point not part of the region will be.
4149 // To handle these PHI nodes later we will now model their operands as scalar
4150 // accesses. Note that we do not model anything in the exit block if we have
4151 // an exiting block in the region, as there will not be any splitting later.
4152 if (!R.getExitingBlock())
Hongbin Zheng22623202016-02-15 00:20:58 +00004153 buildAccessFunctions(R, *R.getExit(), *SD->getInsnToMemAccMap(&R), nullptr,
4154 /* IsExitBlock */ true);
Michael Kruse7bf39442015-09-10 12:46:52 +00004155
Hongbin Zheng192f69a2016-02-13 15:12:54 +00004156 scop->init(*AA, AC, *SD, *DT, *LI);
Michael Kruse7bf39442015-09-10 12:46:52 +00004157}
4158
Michael Krused868b5d2015-09-10 15:25:24 +00004159void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00004160 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00004161 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00004162 return;
4163 }
4164
Michael Kruse9d080092015-09-11 21:41:48 +00004165 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00004166}
4167
Hongbin Zhengfec32802016-02-13 15:13:02 +00004168void ScopInfo::clear() { scop.reset(); }
Michael Kruse7bf39442015-09-10 12:46:52 +00004169
4170//===----------------------------------------------------------------------===//
Hongbin Zhengfec32802016-02-13 15:13:02 +00004171ScopInfo::ScopInfo() : RegionPass(ID) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00004172 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00004173 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00004174}
4175
4176ScopInfo::~ScopInfo() {
4177 clear();
4178 isl_ctx_free(ctx);
4179}
4180
Tobias Grosser75805372011-04-29 06:27:02 +00004181void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00004182 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00004183 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00004184 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00004185 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4186 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004187 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004188 AU.addRequired<AssumptionCacheTracker>();
Tobias Grosser75805372011-04-29 06:27:02 +00004189 AU.setPreservesAll();
4190}
4191
4192bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00004193 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00004194
Michael Krused868b5d2015-09-10 15:25:24 +00004195 if (!SD->isMaxRegionInScop(*R))
4196 return false;
4197
4198 Function *F = R->getEntry()->getParent();
4199 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4200 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4201 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Johannes Doerferta1f291e2016-02-02 14:15:13 +00004202 DL = &F->getParent()->getDataLayout();
Michael Krusedaf66942015-12-13 22:10:37 +00004203 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004204 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krused868b5d2015-09-10 15:25:24 +00004205
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004206 DebugLoc Beg, End;
4207 getDebugLocations(R, Beg, End);
4208 std::string Msg = "SCoP begins here.";
4209 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg);
4210
Michael Krusedaf66942015-12-13 22:10:37 +00004211 buildScop(*R, AC);
Tobias Grosser75805372011-04-29 06:27:02 +00004212
Tobias Grosserd6a50b32015-05-30 06:26:21 +00004213 DEBUG(scop->print(dbgs()));
4214
Michael Kruseafe06702015-10-02 16:33:27 +00004215 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004216 Msg = "SCoP ends here but was dismissed.";
Hongbin Zhengfec32802016-02-13 15:13:02 +00004217 scop.reset();
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004218 } else {
4219 Msg = "SCoP ends here.";
4220 ++ScopFound;
4221 if (scop->getMaxLoopDepth() > 0)
4222 ++RichScopFound;
Johannes Doerfert43788c52015-08-20 05:58:56 +00004223 }
4224
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004225 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg);
4226
Tobias Grosser75805372011-04-29 06:27:02 +00004227 return false;
4228}
4229
4230char ScopInfo::ID = 0;
4231
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004232Pass *polly::createScopInfoPass() { return new ScopInfo(); }
4233
Tobias Grosser73600b82011-10-08 00:30:40 +00004234INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
4235 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004236 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004237INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004238INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004239INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004240INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004241INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004242INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004243INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00004244INITIALIZE_PASS_END(ScopInfo, "polly-scops",
4245 "Polly - Create polyhedral description of Scops", false,
4246 false)