blob: 4e940350f2413ab3d737faffc4b919deda8d6de5 [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 {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000192 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000193 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 Doerferta7920982016-02-25 14:08:48 +0000205 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000206 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) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000264 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000265 OS << " " << Size << " ";
266 isl_pw_aff_free(Size);
267 } else {
268 OS << *getDimensionSize(u);
269 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000270
271 OS << "]";
272 }
273
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000274 OS << ";";
275
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000276 if (BasePtrOriginSAI)
277 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
278
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000279 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000280}
281
282const ScopArrayInfo *
283ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
284 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
285 assert(Id && "Output dimension didn't have an ID");
286 return getFromId(Id);
287}
288
289const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
290 void *User = isl_id_get_user(Id);
291 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
292 isl_id_free(Id);
293 return SAI;
294}
295
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000296void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000297 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000298 auto *ArraySpace = SAI->getSpace();
299 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000300 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000301
302 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
303 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
304 auto DimsMissing = DimsArray - DimsAccess;
305
Michael Kruse375cb5f2016-02-24 22:08:24 +0000306 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000307 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000308 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000309 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000310
Johannes Doerferta90943d2016-02-21 16:37:25 +0000311 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000312 isl_set_universe(AccessSpace),
313 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000314
315 for (unsigned i = 0; i < DimsMissing; i++)
316 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
317
318 for (unsigned i = DimsMissing; i < DimsArray; i++)
319 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
320
321 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000322
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000323 // For the non delinearized arrays, divide the access function of the last
324 // subscript by the size of the elements in the array.
325 //
326 // A stride one array access in C expressed as A[i] is expressed in
327 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
328 // two subsequent values of 'i' index two values that are stored next to
329 // each other in memory. By this division we make this characteristic
330 // obvious again. If the base pointer was accessed with offsets not divisible
331 // by the accesses element size, we will have choosen a smaller ArrayElemSize
332 // that divides the offsets of all accesses to this base pointer.
333 if (DimsAccess == 1) {
334 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
335 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
336 }
337
338 if (!isAffine())
339 computeBoundsOnAccessRelation(ArrayElemSize);
340
Tobias Grosserd840fc72016-02-04 13:18:42 +0000341 // Introduce multi-element accesses in case the type loaded by this memory
342 // access is larger than the canonical element type of the array.
343 //
344 // An access ((float *)A)[i] to an array char *A is modeled as
345 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000346 if (ElemBytes > ArrayElemSize) {
347 assert(ElemBytes % ArrayElemSize == 0 &&
348 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000349 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000350 isl_set_universe(isl_space_copy(ArraySpace)),
351 isl_set_universe(isl_space_copy(ArraySpace)));
352 for (unsigned i = 0; i < DimsArray - 1; i++)
353 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
354
Tobias Grosserd840fc72016-02-04 13:18:42 +0000355 isl_constraint *C;
356 isl_local_space *LS;
357
358 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000359 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
360
361 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
362 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000363 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000364 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
365 Map = isl_map_add_constraint(Map, C);
366
367 C = isl_constraint_alloc_inequality(LS);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000368 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000369 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
370 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
371 Map = isl_map_add_constraint(Map, C);
372 AccessRelation = isl_map_apply_range(AccessRelation, Map);
373 }
374
375 isl_space_free(ArraySpace);
376
Roman Gareev10595a12016-01-08 14:01:59 +0000377 assumeNoOutOfBound();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000378}
379
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000380const std::string
381MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
382 switch (RT) {
383 case MemoryAccess::RT_NONE:
384 llvm_unreachable("Requested a reduction operator string for a memory "
385 "access which isn't a reduction");
386 case MemoryAccess::RT_ADD:
387 return "+";
388 case MemoryAccess::RT_MUL:
389 return "*";
390 case MemoryAccess::RT_BOR:
391 return "|";
392 case MemoryAccess::RT_BXOR:
393 return "^";
394 case MemoryAccess::RT_BAND:
395 return "&";
396 }
397 llvm_unreachable("Unknown reduction type");
398 return "";
399}
400
Johannes Doerfertf6183392014-07-01 20:52:51 +0000401/// @brief Return the reduction type for a given binary operator
402static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
403 const Instruction *Load) {
404 if (!BinOp)
405 return MemoryAccess::RT_NONE;
406 switch (BinOp->getOpcode()) {
407 case Instruction::FAdd:
408 if (!BinOp->hasUnsafeAlgebra())
409 return MemoryAccess::RT_NONE;
410 // Fall through
411 case Instruction::Add:
412 return MemoryAccess::RT_ADD;
413 case Instruction::Or:
414 return MemoryAccess::RT_BOR;
415 case Instruction::Xor:
416 return MemoryAccess::RT_BXOR;
417 case Instruction::And:
418 return MemoryAccess::RT_BAND;
419 case Instruction::FMul:
420 if (!BinOp->hasUnsafeAlgebra())
421 return MemoryAccess::RT_NONE;
422 // Fall through
423 case Instruction::Mul:
424 if (DisableMultiplicativeReductions)
425 return MemoryAccess::RT_NONE;
426 return MemoryAccess::RT_MUL;
427 default:
428 return MemoryAccess::RT_NONE;
429 }
430}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000431
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000432/// @brief Derive the individual index expressions from a GEP instruction
433///
434/// This function optimistically assumes the GEP references into a fixed size
435/// array. If this is actually true, this function returns a list of array
436/// subscript expressions as SCEV as well as a list of integers describing
437/// the size of the individual array dimensions. Both lists have either equal
438/// length of the size list is one element shorter in case there is no known
439/// size available for the outermost array dimension.
440///
441/// @param GEP The GetElementPtr instruction to analyze.
442///
443/// @return A tuple with the subscript expressions and the dimension sizes.
444static std::tuple<std::vector<const SCEV *>, std::vector<int>>
445getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
446 std::vector<const SCEV *> Subscripts;
447 std::vector<int> Sizes;
448
449 Type *Ty = GEP->getPointerOperandType();
450
451 bool DroppedFirstDim = false;
452
Michael Kruse26ed65e2015-09-24 17:32:49 +0000453 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000454
455 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
456
457 if (i == 1) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000458 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000459 Ty = PtrTy->getElementType();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000460 } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000461 Ty = ArrayTy->getElementType();
462 } else {
463 Subscripts.clear();
464 Sizes.clear();
465 break;
466 }
Johannes Doerferta90943d2016-02-21 16:37:25 +0000467 if (auto *Const = dyn_cast<SCEVConstant>(Expr))
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000468 if (Const->getValue()->isZero()) {
469 DroppedFirstDim = true;
470 continue;
471 }
472 Subscripts.push_back(Expr);
473 continue;
474 }
475
Johannes Doerferta90943d2016-02-21 16:37:25 +0000476 auto *ArrayTy = dyn_cast<ArrayType>(Ty);
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000477 if (!ArrayTy) {
478 Subscripts.clear();
479 Sizes.clear();
480 break;
481 }
482
483 Subscripts.push_back(Expr);
484 if (!(DroppedFirstDim && i == 2))
485 Sizes.push_back(ArrayTy->getNumElements());
486
487 Ty = ArrayTy->getElementType();
488 }
489
490 return std::make_tuple(Subscripts, Sizes);
491}
492
Tobias Grosser75805372011-04-29 06:27:02 +0000493MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000494 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000495 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000496 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000497}
498
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000499const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
500 isl_id *ArrayId = getArrayId();
501 void *User = isl_id_get_user(ArrayId);
502 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
503 isl_id_free(ArrayId);
504 return SAI;
505}
506
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000507__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000508 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
509}
510
Tobias Grosserd840fc72016-02-04 13:18:42 +0000511__isl_give isl_map *MemoryAccess::getAddressFunction() const {
512 return isl_map_lexmin(getAccessRelation());
513}
514
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000515__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
516 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000517 isl_map *Schedule, *ScheduledAccRel;
518 isl_union_set *UDomain;
519
520 UDomain = isl_union_set_from_set(getStatement()->getDomain());
521 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
522 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000523 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000524 return isl_pw_multi_aff_from_map(ScheduledAccRel);
525}
526
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000527__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000528 return isl_map_copy(AccessRelation);
529}
530
Johannes Doerferta99130f2014-10-13 12:58:03 +0000531std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000532 return stringFromIslObj(AccessRelation);
533}
534
Johannes Doerferta99130f2014-10-13 12:58:03 +0000535__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000536 return isl_map_get_space(AccessRelation);
537}
538
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000539__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000540 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000541}
542
Tobias Grosser6f730082015-09-05 07:46:47 +0000543std::string MemoryAccess::getNewAccessRelationStr() const {
544 return stringFromIslObj(NewAccessRelation);
545}
546
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000547__isl_give isl_basic_map *
548MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000549 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000550 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000551
Tobias Grosser084d8f72012-05-29 09:29:44 +0000552 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000553 isl_basic_set_universe(Statement->getDomainSpace()),
554 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000555}
556
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000557// Formalize no out-of-bound access assumption
558//
559// When delinearizing array accesses we optimistically assume that the
560// delinearized accesses do not access out of bound locations (the subscript
561// expression of each array evaluates for each statement instance that is
562// executed to a value that is larger than zero and strictly smaller than the
563// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000564// dimension for which we do not need to assume any upper bound. At this point
565// we formalize this assumption to ensure that at code generation time the
566// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000567//
568// To find the set of constraints necessary to avoid out of bound accesses, we
569// first build the set of data locations that are not within array bounds. We
570// then apply the reverse access relation to obtain the set of iterations that
571// may contain invalid accesses and reduce this set of iterations to the ones
572// that are actually executed by intersecting them with the domain of the
573// statement. If we now project out all loop dimensions, we obtain a set of
574// parameters that may cause statement instances to be executed that may
575// possibly yield out of bound memory accesses. The complement of these
576// constraints is the set of constraints that needs to be assumed to ensure such
577// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000578void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000579 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000580 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000581 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000582 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000583 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
584 isl_pw_aff *Var =
585 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
586 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
587
588 isl_set *DimOutside;
589
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000590 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000591 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000592 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
593 isl_space_dim(Space, isl_dim_set));
594 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
595 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000596
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000597 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000598
599 Outside = isl_set_union(Outside, DimOutside);
600 }
601
602 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
603 Outside = isl_set_intersect(Outside, Statement->getDomain());
604 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000605
606 // Remove divs to avoid the construction of overly complicated assumptions.
607 // Doing so increases the set of parameter combinations that are assumed to
608 // not appear. This is always save, but may make the resulting run-time check
609 // bail out more often than strictly necessary.
610 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000611 Outside = isl_set_complement(Outside);
Johannes Doerfert066dbf32016-03-01 13:06:28 +0000612 auto &Loc = getAccessInstruction() ? getAccessInstruction()->getDebugLoc()
613 : DebugLoc();
614 Statement->getParent()->addAssumption(INBOUNDS, Outside, Loc, AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000615 isl_space_free(Space);
616}
617
Johannes Doerfertcea61932016-02-21 19:13:19 +0000618void MemoryAccess::buildMemIntrinsicAccessRelation() {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000619 assert(isa<MemIntrinsic>(getAccessInstruction()));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000620 assert(Subscripts.size() == 2 && Sizes.size() == 0);
621
Johannes Doerfertcea61932016-02-21 19:13:19 +0000622 auto *SubscriptPWA = Statement->getPwAff(Subscripts[0]);
623 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000624
625 isl_map *LengthMap;
626 if (Subscripts[1] == nullptr) {
627 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
628 } else {
629 auto *LengthPWA = Statement->getPwAff(Subscripts[1]);
630 LengthMap = isl_map_from_pw_aff(LengthPWA);
631 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
632 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
633 }
634 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
635 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000636 SubscriptMap =
637 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000638 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
639 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
640 getStatement()->getDomainId());
641}
642
Johannes Doerferte7044942015-02-24 11:58:30 +0000643void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
644 ScalarEvolution *SE = Statement->getParent()->getSE();
645
Johannes Doerfertcea61932016-02-21 19:13:19 +0000646 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000647 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000648 return;
649
650 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000651 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
652 return;
653
654 auto *PtrSCEV = SE->getSCEV(Ptr);
655 if (isa<SCEVCouldNotCompute>(PtrSCEV))
656 return;
657
658 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
659 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
660 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
661
662 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
663 if (Range.isFullSet())
664 return;
665
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000666 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000667 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000668 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000669 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000670 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000671
672 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000673 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000674
675 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
676 AccessRange =
677 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
678 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
679}
680
Michael Krusee2bccbb2015-09-18 19:59:43 +0000681__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000682 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000683 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000684
685 for (int i = Size - 2; i >= 0; --i) {
686 isl_space *Space;
687 isl_map *MapOne, *MapTwo;
Michael Krusee2bccbb2015-09-18 19:59:43 +0000688 isl_pw_aff *DimSize = Statement->getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000689
690 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
691 isl_pw_aff_free(DimSize);
692 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
693
694 Space = isl_map_get_space(AccessRelation);
695 Space = isl_space_map_from_set(isl_space_range(Space));
696 Space = isl_space_align_params(Space, SpaceSize);
697
698 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
699 isl_id_free(ParamId);
700
701 MapOne = isl_map_universe(isl_space_copy(Space));
702 for (int j = 0; j < Size; ++j)
703 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
704 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
705
706 MapTwo = isl_map_universe(isl_space_copy(Space));
707 for (int j = 0; j < Size; ++j)
708 if (j < i || j > i + 1)
709 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
710
711 isl_local_space *LS = isl_local_space_from_space(Space);
712 isl_constraint *C;
713 C = isl_equality_alloc(isl_local_space_copy(LS));
714 C = isl_constraint_set_constant_si(C, -1);
715 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
716 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
717 MapTwo = isl_map_add_constraint(MapTwo, C);
718 C = isl_equality_alloc(LS);
719 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
720 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
721 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
722 MapTwo = isl_map_add_constraint(MapTwo, C);
723 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
724
725 MapOne = isl_map_union(MapOne, MapTwo);
726 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
727 }
728 return AccessRelation;
729}
730
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000731/// @brief Check if @p Expr is divisible by @p Size.
732static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000733 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000734 if (Size == 1)
735 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000736
737 // Only one factor needs to be divisible.
738 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
739 for (auto *FactorExpr : MulExpr->operands())
740 if (isDivisible(FactorExpr, Size, SE))
741 return true;
742 return false;
743 }
744
745 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
746 // to be divisble.
747 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
748 for (auto *OpExpr : NAryExpr->operands())
749 if (!isDivisible(OpExpr, Size, SE))
750 return false;
751 return true;
752 }
753
754 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
755 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
756 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
757 return MulSCEV == Expr;
758}
759
Michael Krusee2bccbb2015-09-18 19:59:43 +0000760void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
761 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000762
Michael Krusee2bccbb2015-09-18 19:59:43 +0000763 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000764 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000765
Michael Krusee2bccbb2015-09-18 19:59:43 +0000766 if (!isAffine()) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000767 if (isa<MemIntrinsic>(getAccessInstruction()))
768 buildMemIntrinsicAccessRelation();
769
Tobias Grosser4f967492013-06-23 05:21:18 +0000770 // We overapproximate non-affine accesses with a possible access to the
771 // whole array. For read accesses it does not make a difference, if an
772 // access must or may happen. However, for write accesses it is important to
773 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000774 if (!AccessRelation)
775 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
776
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000777 AccessRelation =
778 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000779 return;
780 }
781
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000782 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000783 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000784
Michael Krusee2bccbb2015-09-18 19:59:43 +0000785 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
786 isl_pw_aff *Affine = Statement->getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000787 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000788 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000789 }
790
Tobias Grosser5d51afe2016-02-02 16:46:45 +0000791 if (Sizes.size() >= 1 && !isa<SCEVConstant>(Sizes[0]))
Michael Krusee2bccbb2015-09-18 19:59:43 +0000792 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000793
Tobias Grosser79baa212014-04-10 08:38:02 +0000794 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000795 AccessRelation = isl_map_set_tuple_id(
796 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000797 AccessRelation =
798 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
799
Tobias Grosseraa660a92015-03-30 00:07:50 +0000800 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000801 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000802}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000803
Michael Krusecac948e2015-10-02 13:53:07 +0000804MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000805 AccessType AccType, Value *BaseAddress,
806 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000807 ArrayRef<const SCEV *> Subscripts,
808 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000809 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000810 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
811 BaseAddr(BaseAddress), BaseName(BaseName), ElementType(ElementType),
Michael Krusecac948e2015-10-02 13:53:07 +0000812 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
813 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000814 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000815 NewAccessRelation(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000816 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Johannes Doerfertcea61932016-02-21 19:13:19 +0000817 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000818
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000819 std::string IdName =
820 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000821 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
822}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000823
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000824void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000825 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000826 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000827}
828
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000829const std::string MemoryAccess::getReductionOperatorStr() const {
830 return MemoryAccess::getReductionOperatorStr(getReductionType());
831}
832
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000833__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
834
Johannes Doerfertf6183392014-07-01 20:52:51 +0000835raw_ostream &polly::operator<<(raw_ostream &OS,
836 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000837 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000838 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000839 else
840 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000841 return OS;
842}
843
Tobias Grosser75805372011-04-29 06:27:02 +0000844void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000845 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000846 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000847 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000848 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000849 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000850 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000851 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000852 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000853 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000854 break;
855 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000856 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000857 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000858 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000859 if (hasNewAccessRelation())
860 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000861}
862
Tobias Grosser74394f02013-01-14 22:40:23 +0000863void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000864
865// Create a map in the size of the provided set domain, that maps from the
866// one element of the provided set domain to another element of the provided
867// set domain.
868// The mapping is limited to all points that are equal in all but the last
869// dimension and for which the last dimension of the input is strict smaller
870// than the last dimension of the output.
871//
872// getEqualAndLarger(set[i0, i1, ..., iX]):
873//
874// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
875// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
876//
Tobias Grosserf5338802011-10-06 00:03:35 +0000877static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000878 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000879 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000880 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000881
882 // Set all but the last dimension to be equal for the input and output
883 //
884 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
885 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000886 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000887 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000888
889 // Set the last dimension of the input to be strict smaller than the
890 // last dimension of the output.
891 //
892 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000893 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
894 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000895 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000896}
897
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000898__isl_give isl_set *
899MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000900 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000901 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000902 isl_space *Space = isl_space_range(isl_map_get_space(S));
903 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000904
Sebastian Popa00a0292012-12-18 07:46:06 +0000905 S = isl_map_reverse(S);
906 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000907
Sebastian Popa00a0292012-12-18 07:46:06 +0000908 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
909 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
910 NextScatt = isl_map_apply_domain(NextScatt, S);
911 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000912
Sebastian Popa00a0292012-12-18 07:46:06 +0000913 isl_set *Deltas = isl_map_deltas(NextScatt);
914 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000915}
916
Sebastian Popa00a0292012-12-18 07:46:06 +0000917bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000918 int StrideWidth) const {
919 isl_set *Stride, *StrideX;
920 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000921
Sebastian Popa00a0292012-12-18 07:46:06 +0000922 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000923 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000924 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
925 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
926 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
927 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000928 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000929
Tobias Grosser28dd4862012-01-24 16:42:16 +0000930 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000931 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000932
Tobias Grosser28dd4862012-01-24 16:42:16 +0000933 return IsStrideX;
934}
935
Sebastian Popa00a0292012-12-18 07:46:06 +0000936bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
937 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000938}
939
Sebastian Popa00a0292012-12-18 07:46:06 +0000940bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
941 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000942}
943
Tobias Grosser166c4222015-09-05 07:46:40 +0000944void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
945 isl_map_free(NewAccessRelation);
946 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000947}
Tobias Grosser75805372011-04-29 06:27:02 +0000948
949//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000950
Tobias Grosser808cd692015-07-14 09:33:13 +0000951isl_map *ScopStmt::getSchedule() const {
952 isl_set *Domain = getDomain();
953 if (isl_set_is_empty(Domain)) {
954 isl_set_free(Domain);
955 return isl_map_from_aff(
956 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
957 }
958 auto *Schedule = getParent()->getSchedule();
959 Schedule = isl_union_map_intersect_domain(
960 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
961 if (isl_union_map_is_empty(Schedule)) {
962 isl_set_free(Domain);
963 isl_union_map_free(Schedule);
964 return isl_map_from_aff(
965 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
966 }
967 auto *M = isl_map_from_union_map(Schedule);
968 M = isl_map_coalesce(M);
969 M = isl_map_gist_domain(M, Domain);
970 M = isl_map_coalesce(M);
971 return M;
972}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000973
Johannes Doerfert574182d2015-08-12 10:19:50 +0000974__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Michael Kruse375cb5f2016-02-24 22:08:24 +0000975 return getParent()->getPwAff(E, getEntryBlock());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000976}
977
Tobias Grosser37eb4222014-02-20 21:43:54 +0000978void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
979 assert(isl_set_is_subset(NewDomain, Domain) &&
980 "New domain is not a subset of old domain!");
981 isl_set_free(Domain);
982 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000983}
984
Michael Krusecac948e2015-10-02 13:53:07 +0000985void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000986 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +0000987 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000988 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000989
Tobias Grossera535dff2015-12-13 19:59:01 +0000990 ScopArrayInfo::MemoryKind Ty;
991 if (Access->isPHIKind())
992 Ty = ScopArrayInfo::MK_PHI;
993 else if (Access->isExitPHIKind())
994 Ty = ScopArrayInfo::MK_ExitPHI;
995 else if (Access->isValueKind())
996 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000997 else
Tobias Grossera535dff2015-12-13 19:59:01 +0000998 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000999
Johannes Doerfertadeab372016-02-07 13:57:32 +00001000 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
1001 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001002 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001003 }
1004}
1005
Michael Krusecac948e2015-10-02 13:53:07 +00001006void ScopStmt::addAccess(MemoryAccess *Access) {
1007 Instruction *AccessInst = Access->getAccessInstruction();
1008
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001009 if (Access->isArrayKind()) {
1010 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1011 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001012 } else if (Access->isValueKind() && Access->isWrite()) {
1013 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001014 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001015 assert(!ValueWrites.lookup(AccessVal));
1016
1017 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001018 } else if (Access->isValueKind() && Access->isRead()) {
1019 Value *AccessVal = Access->getAccessValue();
1020 assert(!ValueReads.lookup(AccessVal));
1021
1022 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001023 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1024 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
1025 assert(!PHIWrites.lookup(PHI));
1026
1027 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001028 }
1029
1030 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001031}
1032
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001033void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001034 for (MemoryAccess *MA : *this)
1035 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001036
1037 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001038}
1039
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001040/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
1041static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1042 void *User) {
1043 isl_set **BoundedParts = static_cast<isl_set **>(User);
1044 if (isl_basic_set_is_bounded(BSet))
1045 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1046 else
1047 isl_basic_set_free(BSet);
1048 return isl_stat_ok;
1049}
1050
1051/// @brief Return the bounded parts of @p S.
1052static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1053 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1054 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1055 isl_set_free(S);
1056 return BoundedParts;
1057}
1058
1059/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
1060///
1061/// @returns A separation of @p S into first an unbounded then a bounded subset,
1062/// both with regards to the dimension @p Dim.
1063static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1064partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1065
1066 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001067 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001068
1069 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001070 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001071
1072 // Remove dimensions that are greater than Dim as they are not interesting.
1073 assert(NumDimsS >= Dim + 1);
1074 OnlyDimS =
1075 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1076
1077 // Create artificial parametric upper bounds for dimensions smaller than Dim
1078 // as we are not interested in them.
1079 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1080 for (unsigned u = 0; u < Dim; u++) {
1081 isl_constraint *C = isl_inequality_alloc(
1082 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1083 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1084 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1085 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1086 }
1087
1088 // Collect all bounded parts of OnlyDimS.
1089 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1090
1091 // Create the dimensions greater than Dim again.
1092 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1093 NumDimsS - Dim - 1);
1094
1095 // Remove the artificial upper bound parameters again.
1096 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1097
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001098 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001099 return std::make_pair(UnboundedParts, BoundedParts);
1100}
1101
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001102/// @brief Set the dimension Ids from @p From in @p To.
1103static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1104 __isl_take isl_set *To) {
1105 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1106 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1107 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1108 }
1109 return To;
1110}
1111
1112/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001113static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001114 __isl_take isl_pw_aff *L,
1115 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001116 switch (Pred) {
1117 case ICmpInst::ICMP_EQ:
1118 return isl_pw_aff_eq_set(L, R);
1119 case ICmpInst::ICMP_NE:
1120 return isl_pw_aff_ne_set(L, R);
1121 case ICmpInst::ICMP_SLT:
1122 return isl_pw_aff_lt_set(L, R);
1123 case ICmpInst::ICMP_SLE:
1124 return isl_pw_aff_le_set(L, R);
1125 case ICmpInst::ICMP_SGT:
1126 return isl_pw_aff_gt_set(L, R);
1127 case ICmpInst::ICMP_SGE:
1128 return isl_pw_aff_ge_set(L, R);
1129 case ICmpInst::ICMP_ULT:
1130 return isl_pw_aff_lt_set(L, R);
1131 case ICmpInst::ICMP_UGT:
1132 return isl_pw_aff_gt_set(L, R);
1133 case ICmpInst::ICMP_ULE:
1134 return isl_pw_aff_le_set(L, R);
1135 case ICmpInst::ICMP_UGE:
1136 return isl_pw_aff_ge_set(L, R);
1137 default:
1138 llvm_unreachable("Non integer predicate not supported");
1139 }
1140}
1141
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001142/// @brief Create the conditions under which @p L @p Pred @p R is true.
1143///
1144/// Helper function that will make sure the dimensions of the result have the
1145/// same isl_id's as the @p Domain.
1146static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1147 __isl_take isl_pw_aff *L,
1148 __isl_take isl_pw_aff *R,
1149 __isl_keep isl_set *Domain) {
1150 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1151 return setDimensionIds(Domain, ConsequenceCondSet);
1152}
1153
1154/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001155///
1156/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001157/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1158/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001159static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001160buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001161 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1162
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001163 Value *Condition = getConditionFromTerminator(SI);
1164 assert(Condition && "No condition for switch");
1165
1166 ScalarEvolution &SE = *S.getSE();
1167 BasicBlock *BB = SI->getParent();
1168 isl_pw_aff *LHS, *RHS;
1169 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
1170
1171 unsigned NumSuccessors = SI->getNumSuccessors();
1172 ConditionSets.resize(NumSuccessors);
1173 for (auto &Case : SI->cases()) {
1174 unsigned Idx = Case.getSuccessorIndex();
1175 ConstantInt *CaseValue = Case.getCaseValue();
1176
1177 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
1178 isl_set *CaseConditionSet =
1179 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1180 ConditionSets[Idx] = isl_set_coalesce(
1181 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1182 }
1183
1184 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1185 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1186 for (unsigned u = 2; u < NumSuccessors; u++)
1187 ConditionSetUnion =
1188 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1189 ConditionSets[0] = setDimensionIds(
1190 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1191
1192 S.markAsOptimized();
1193 isl_pw_aff_free(LHS);
1194}
1195
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001196/// @brief Build the conditions sets for the branch condition @p Condition in
1197/// the @p Domain.
1198///
1199/// This will fill @p ConditionSets with the conditions under which control
1200/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001201/// have as many elements as @p TI has successors. If @p TI is nullptr the
1202/// context under which @p Condition is true/false will be returned as the
1203/// new elements of @p ConditionSets.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001204static void
1205buildConditionSets(Scop &S, Value *Condition, TerminatorInst *TI, Loop *L,
1206 __isl_keep isl_set *Domain,
1207 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1208
1209 isl_set *ConsequenceCondSet = nullptr;
1210 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1211 if (CCond->isZero())
1212 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1213 else
1214 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1215 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1216 auto Opcode = BinOp->getOpcode();
1217 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1218
1219 buildConditionSets(S, BinOp->getOperand(0), TI, L, Domain, ConditionSets);
1220 buildConditionSets(S, BinOp->getOperand(1), TI, L, Domain, ConditionSets);
1221
1222 isl_set_free(ConditionSets.pop_back_val());
1223 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1224 isl_set_free(ConditionSets.pop_back_val());
1225 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1226
1227 if (Opcode == Instruction::And)
1228 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1229 else
1230 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1231 } else {
1232 auto *ICond = dyn_cast<ICmpInst>(Condition);
1233 assert(ICond &&
1234 "Condition of exiting branch was neither constant nor ICmp!");
1235
1236 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001237 BasicBlock *BB = TI ? TI->getParent() : nullptr;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001238 isl_pw_aff *LHS, *RHS;
1239 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1240 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
1241 ConsequenceCondSet =
1242 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1243 }
1244
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001245 // If no terminator was given we are only looking for parameter constraints
1246 // under which @p Condition is true/false.
1247 if (!TI)
1248 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
1249
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001250 assert(ConsequenceCondSet);
1251 isl_set *AlternativeCondSet =
1252 isl_set_complement(isl_set_copy(ConsequenceCondSet));
1253
1254 ConditionSets.push_back(isl_set_coalesce(
1255 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
1256 ConditionSets.push_back(isl_set_coalesce(
1257 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
1258}
1259
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001260/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1261///
1262/// This will fill @p ConditionSets with the conditions under which control
1263/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1264/// have as many elements as @p TI has successors.
1265static void
1266buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1267 __isl_keep isl_set *Domain,
1268 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1269
1270 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1271 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1272
1273 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1274
1275 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001276 ConditionSets.push_back(isl_set_copy(Domain));
1277 return;
1278 }
1279
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001280 Value *Condition = getConditionFromTerminator(TI);
1281 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001282
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001283 return buildConditionSets(S, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001284}
1285
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001286void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001287 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001288
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001289 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001290 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001291}
1292
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001293void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP,
1294 ScopDetection &SD) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001295 isl_ctx *Ctx = Parent.getIslCtx();
1296 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1297 Type *Ty = GEP->getPointerOperandType();
1298 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001299
1300 // The set of loads that are required to be invariant.
1301 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001302
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001303 std::vector<const SCEV *> Subscripts;
1304 std::vector<int> Sizes;
1305
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001306 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001307
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001308 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001309 Ty = PtrTy->getElementType();
1310 }
1311
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001312 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001313
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001314 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001315
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001316 auto *NotExecuted = isl_set_complement(isl_set_params(getDomain()));
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001317 for (size_t i = 0; i < Sizes.size(); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001318 auto *Expr = Subscripts[i + IndexOffset];
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001319 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001320
Johannes Doerfert09e36972015-10-07 20:17:36 +00001321 InvariantLoadsSetTy AccessILS;
1322 if (!isAffineExpr(&Parent.getRegion(), Expr, SE, nullptr, &AccessILS))
1323 continue;
1324
1325 bool NonAffine = false;
1326 for (LoadInst *LInst : AccessILS)
1327 if (!ScopRIL.count(LInst))
1328 NonAffine = true;
1329
1330 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001331 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001332
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001333 isl_pw_aff *AccessOffset = getPwAff(Expr);
1334 AccessOffset =
1335 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001336
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001337 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1338 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001339
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001340 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1341 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1342 OutOfBound = isl_set_params(OutOfBound);
1343 isl_set *InBound = isl_set_complement(OutOfBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001344
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001345 // A => B == !A or B
1346 isl_set *InBoundIfExecuted =
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001347 isl_set_union(isl_set_copy(NotExecuted), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001348
Roman Gareev10595a12016-01-08 14:01:59 +00001349 InBoundIfExecuted = isl_set_coalesce(InBoundIfExecuted);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001350 Parent.addAssumption(INBOUNDS, InBoundIfExecuted, GEP->getDebugLoc(),
1351 AS_ASSUMPTION);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001352 }
1353
1354 isl_local_space_free(LSpace);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001355 isl_set_free(NotExecuted);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001356}
1357
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001358void ScopStmt::deriveAssumptions(BasicBlock *Block, ScopDetection &SD) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001359 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001360 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001361 deriveAssumptionsFromGEP(GEP, SD);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001362}
1363
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001364void ScopStmt::collectSurroundingLoops() {
1365 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1366 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1367 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1368 isl_id_free(DimId);
1369 }
1370}
1371
Michael Kruse9d080092015-09-11 21:41:48 +00001372ScopStmt::ScopStmt(Scop &parent, Region &R)
Michael Krusecac948e2015-10-02 13:53:07 +00001373 : Parent(parent), Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001374
Tobias Grosser16c44032015-07-09 07:31:45 +00001375 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001376}
1377
Michael Kruse9d080092015-09-11 21:41:48 +00001378ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Michael Krusecac948e2015-10-02 13:53:07 +00001379 : Parent(parent), Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001380
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001381 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001382}
1383
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001384void ScopStmt::init(ScopDetection &SD) {
Michael Krusecac948e2015-10-02 13:53:07 +00001385 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001386
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001387 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001388 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001389 buildAccessRelations();
1390
1391 if (BB) {
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001392 deriveAssumptions(BB, SD);
Michael Krusecac948e2015-10-02 13:53:07 +00001393 } else {
1394 for (BasicBlock *Block : R->blocks()) {
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001395 deriveAssumptions(Block, SD);
Michael Krusecac948e2015-10-02 13:53:07 +00001396 }
1397 }
1398
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001399 if (DetectReductions)
1400 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001401}
1402
Johannes Doerferte58a0122014-06-27 20:31:28 +00001403/// @brief Collect loads which might form a reduction chain with @p StoreMA
1404///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001405/// Check if the stored value for @p StoreMA is a binary operator with one or
1406/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001407/// used only once (by @p StoreMA) and its load operands are also used only
1408/// once, we have found a possible reduction chain. It starts at an operand
1409/// load and includes the binary operator and @p StoreMA.
1410///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001411/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001412/// escape this block or into any other store except @p StoreMA.
1413void ScopStmt::collectCandiateReductionLoads(
1414 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1415 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1416 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001417 return;
1418
1419 // Skip if there is not one binary operator between the load and the store
1420 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001421 if (!BinOp)
1422 return;
1423
1424 // Skip if the binary operators has multiple uses
1425 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001426 return;
1427
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001428 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001429 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1430 return;
1431
Johannes Doerfert9890a052014-07-01 00:32:29 +00001432 // Skip if the binary operator is outside the current SCoP
1433 if (BinOp->getParent() != Store->getParent())
1434 return;
1435
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001436 // Skip if it is a multiplicative reduction and we disabled them
1437 if (DisableMultiplicativeReductions &&
1438 (BinOp->getOpcode() == Instruction::Mul ||
1439 BinOp->getOpcode() == Instruction::FMul))
1440 return;
1441
Johannes Doerferte58a0122014-06-27 20:31:28 +00001442 // Check the binary operator operands for a candidate load
1443 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1444 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1445 if (!PossibleLoad0 && !PossibleLoad1)
1446 return;
1447
1448 // A load is only a candidate if it cannot escape (thus has only this use)
1449 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001450 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001451 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001452 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001453 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001454 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001455}
1456
1457/// @brief Check for reductions in this ScopStmt
1458///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001459/// Iterate over all store memory accesses and check for valid binary reduction
1460/// like chains. For all candidates we check if they have the same base address
1461/// and there are no other accesses which overlap with them. The base address
1462/// check rules out impossible reductions candidates early. The overlap check,
1463/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001464/// guarantees that none of the intermediate results will escape during
1465/// execution of the loop nest. We basically check here that no other memory
1466/// access can access the same memory as the potential reduction.
1467void ScopStmt::checkForReductions() {
1468 SmallVector<MemoryAccess *, 2> Loads;
1469 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1470
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001471 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001472 // stores and collecting possible reduction loads.
1473 for (MemoryAccess *StoreMA : MemAccs) {
1474 if (StoreMA->isRead())
1475 continue;
1476
1477 Loads.clear();
1478 collectCandiateReductionLoads(StoreMA, Loads);
1479 for (MemoryAccess *LoadMA : Loads)
1480 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1481 }
1482
1483 // Then check each possible candidate pair.
1484 for (const auto &CandidatePair : Candidates) {
1485 bool Valid = true;
1486 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1487 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1488
1489 // Skip those with obviously unequal base addresses.
1490 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1491 isl_map_free(LoadAccs);
1492 isl_map_free(StoreAccs);
1493 continue;
1494 }
1495
1496 // And check if the remaining for overlap with other memory accesses.
1497 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1498 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1499 isl_set *AllAccs = isl_map_range(AllAccsRel);
1500
1501 for (MemoryAccess *MA : MemAccs) {
1502 if (MA == CandidatePair.first || MA == CandidatePair.second)
1503 continue;
1504
1505 isl_map *AccRel =
1506 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1507 isl_set *Accs = isl_map_range(AccRel);
1508
1509 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1510 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1511 Valid = Valid && isl_set_is_empty(OverlapAccs);
1512 isl_set_free(OverlapAccs);
1513 }
1514 }
1515
1516 isl_set_free(AllAccs);
1517 if (!Valid)
1518 continue;
1519
Johannes Doerfertf6183392014-07-01 20:52:51 +00001520 const LoadInst *Load =
1521 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1522 MemoryAccess::ReductionType RT =
1523 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1524
Johannes Doerferte58a0122014-06-27 20:31:28 +00001525 // If no overlapping access was found we mark the load and store as
1526 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001527 CandidatePair.first->markAsReductionLike(RT);
1528 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001529 }
Tobias Grosser75805372011-04-29 06:27:02 +00001530}
1531
Tobias Grosser74394f02013-01-14 22:40:23 +00001532std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001533
Tobias Grosser54839312015-04-21 11:37:25 +00001534std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001535 auto *S = getSchedule();
1536 auto Str = stringFromIslObj(S);
1537 isl_map_free(S);
1538 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001539}
1540
Michael Kruse375cb5f2016-02-24 22:08:24 +00001541BasicBlock *ScopStmt::getEntryBlock() const {
1542 if (isBlockStmt())
1543 return getBasicBlock();
1544 return getRegion()->getEntry();
1545}
1546
Michael Kruse7b5caa42016-02-24 22:08:28 +00001547RegionNode *ScopStmt::getRegionNode() const {
1548 if (isRegionStmt())
1549 return getRegion()->getNode();
1550 return getParent()->getRegion().getBBNode(getBasicBlock());
1551}
1552
Tobias Grosser74394f02013-01-14 22:40:23 +00001553unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001554
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001555unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001556
Tobias Grosser75805372011-04-29 06:27:02 +00001557const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1558
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001559const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001560 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001561}
1562
Tobias Grosser74394f02013-01-14 22:40:23 +00001563isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001564
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001565__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001566
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001567__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001568 return isl_set_get_space(Domain);
1569}
1570
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001571__isl_give isl_id *ScopStmt::getDomainId() const {
1572 return isl_set_get_tuple_id(Domain);
1573}
Tobias Grossercd95b772012-08-30 11:49:38 +00001574
Tobias Grosser10120182015-12-16 16:14:03 +00001575ScopStmt::~ScopStmt() { isl_set_free(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001576
1577void ScopStmt::print(raw_ostream &OS) const {
1578 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001579 OS.indent(12) << "Domain :=\n";
1580
1581 if (Domain) {
1582 OS.indent(16) << getDomainStr() << ";\n";
1583 } else
1584 OS.indent(16) << "n/a\n";
1585
Tobias Grosser54839312015-04-21 11:37:25 +00001586 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001587
1588 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001589 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001590 } else
1591 OS.indent(16) << "n/a\n";
1592
Tobias Grosser083d3d32014-06-28 08:59:45 +00001593 for (MemoryAccess *Access : MemAccs)
1594 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001595}
1596
1597void ScopStmt::dump() const { print(dbgs()); }
1598
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001599void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001600 // Remove all memory accesses in @p InvMAs from this statement
1601 // together with all scalar accesses that were caused by them.
Michael Krusead28e5a2016-01-26 13:33:15 +00001602 // MK_Value READs have no access instruction, hence would not be removed by
1603 // this function. However, it is only used for invariant LoadInst accesses,
1604 // its arguments are always affine, hence synthesizable, and therefore there
1605 // are no MK_Value READ accesses to be removed.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001606 for (MemoryAccess *MA : InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001607 auto Predicate = [&](MemoryAccess *Acc) {
Tobias Grosser3a6ac9f2015-11-30 21:13:43 +00001608 return Acc->getAccessInstruction() == MA->getAccessInstruction();
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001609 };
1610 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1611 MemAccs.end());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001612 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001613 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001614}
1615
Tobias Grosser75805372011-04-29 06:27:02 +00001616//===----------------------------------------------------------------------===//
1617/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001618
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001619void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001620 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1621 isl_set_free(Context);
1622 Context = NewContext;
1623}
1624
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001625/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1626struct SCEVSensitiveParameterRewriter
1627 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1628 ValueToValueMap &VMap;
1629 ScalarEvolution &SE;
1630
1631public:
1632 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1633 : VMap(VMap), SE(SE) {}
1634
1635 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1636 ValueToValueMap &VMap) {
1637 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1638 return SSPR.visit(E);
1639 }
1640
1641 const SCEV *visit(const SCEV *E) {
1642 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1643 }
1644
1645 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1646
1647 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1648 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1649 }
1650
1651 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1652 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1653 }
1654
1655 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1656 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1657 }
1658
1659 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1660 SmallVector<const SCEV *, 4> Operands;
1661 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1662 Operands.push_back(visit(E->getOperand(i)));
1663 return SE.getAddExpr(Operands);
1664 }
1665
1666 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1667 SmallVector<const SCEV *, 4> Operands;
1668 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1669 Operands.push_back(visit(E->getOperand(i)));
1670 return SE.getMulExpr(Operands);
1671 }
1672
1673 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1674 SmallVector<const SCEV *, 4> Operands;
1675 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1676 Operands.push_back(visit(E->getOperand(i)));
1677 return SE.getSMaxExpr(Operands);
1678 }
1679
1680 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1681 SmallVector<const SCEV *, 4> Operands;
1682 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1683 Operands.push_back(visit(E->getOperand(i)));
1684 return SE.getUMaxExpr(Operands);
1685 }
1686
1687 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1688 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1689 }
1690
1691 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1692 auto *Start = visit(E->getStart());
1693 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1694 visit(E->getStepRecurrence(SE)),
1695 E->getLoop(), SCEV::FlagAnyWrap);
1696 return SE.getAddExpr(Start, AddRec);
1697 }
1698
1699 const SCEV *visitUnknown(const SCEVUnknown *E) {
1700 if (auto *NewValue = VMap.lookup(E->getValue()))
1701 return SE.getUnknown(NewValue);
1702 return E;
1703 }
1704};
1705
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001706const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001707 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001708}
1709
Tobias Grosserabfbe632013-02-05 12:09:06 +00001710void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001711 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001712 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001713
1714 // Normalize the SCEV to get the representing element for an invariant load.
1715 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1716
Tobias Grosser60b54f12011-11-08 15:41:28 +00001717 if (ParameterIds.find(Parameter) != ParameterIds.end())
1718 continue;
1719
1720 int dimension = Parameters.size();
1721
1722 Parameters.push_back(Parameter);
1723 ParameterIds[Parameter] = dimension;
1724 }
1725}
1726
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001727__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001728 // Normalize the SCEV to get the representing element for an invariant load.
1729 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1730
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001731 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001732
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001733 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001734 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001735
Tobias Grosser8f99c162011-11-15 11:38:55 +00001736 std::string ParameterName;
1737
Craig Topper7fb6e472016-01-31 20:36:20 +00001738 ParameterName = "p_" + utostr(IdIter->second);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001739
Tobias Grosser8f99c162011-11-15 11:38:55 +00001740 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1741 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001742
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001743 // If this parameter references a specific Value and this value has a name
1744 // we use this name as it is likely to be unique and more useful than just
1745 // a number.
1746 if (Val->hasName())
1747 ParameterName = Val->getName();
1748 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001749 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001750 if (LoadOrigin->hasName()) {
1751 ParameterName += "_loaded_from_";
1752 ParameterName +=
1753 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1754 }
1755 }
1756 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001757
Tobias Grosser20532b82014-04-11 17:56:49 +00001758 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1759 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001760}
Tobias Grosser75805372011-04-29 06:27:02 +00001761
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001762isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1763 isl_set *DomainContext = isl_union_set_params(getDomains());
1764 return isl_set_intersect_params(C, DomainContext);
1765}
1766
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001767void Scop::addWrappingContext() {
1768 if (IgnoreIntegerWrapping)
Tobias Grosser4927c8e2015-11-24 12:50:02 +00001769 return;
Tobias Grosser4927c8e2015-11-24 12:50:02 +00001770
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001771 auto *WrappingContext = Affinator.getWrappingContext();
1772 addAssumption(WRAPPING, WrappingContext, DebugLoc(), AS_RESTRICTION);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001773}
1774
Hongbin Zheng192f69a2016-02-13 15:12:54 +00001775void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
1776 LoopInfo &LI) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001777 auto *R = &getRegion();
1778 auto &F = *R->getEntry()->getParent();
1779 for (auto &Assumption : AC.assumptions()) {
1780 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1781 if (!CI || CI->getNumArgOperands() != 1)
1782 continue;
1783 if (!DT.dominates(CI->getParent(), R->getEntry()))
1784 continue;
1785
1786 auto *Val = CI->getArgOperand(0);
1787 std::vector<const SCEV *> Params;
1788 if (!isAffineParamConstraint(Val, R, *SE, Params)) {
1789 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1790 CI->getDebugLoc(),
1791 "Non-affine user assumption ignored.");
1792 continue;
1793 }
1794
1795 addParams(Params);
1796
1797 auto *L = LI.getLoopFor(CI->getParent());
1798 SmallVector<isl_set *, 2> ConditionSets;
1799 buildConditionSets(*this, Val, nullptr, L, Context, ConditionSets);
1800 assert(ConditionSets.size() == 2);
1801 isl_set_free(ConditionSets[1]);
1802
1803 auto *AssumptionCtx = ConditionSets[0];
1804 emitOptimizationRemarkAnalysis(
1805 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1806 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1807 Context = isl_set_intersect(Context, AssumptionCtx);
1808 }
1809}
1810
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001811void Scop::addUserContext() {
1812 if (UserContextStr.empty())
1813 return;
1814
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001815 isl_set *UserContext =
1816 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001817 isl_space *Space = getParamSpace();
1818 if (isl_space_dim(Space, isl_dim_param) !=
1819 isl_set_dim(UserContext, isl_dim_param)) {
1820 auto SpaceStr = isl_space_to_str(Space);
1821 errs() << "Error: the context provided in -polly-context has not the same "
1822 << "number of dimensions than the computed context. Due to this "
1823 << "mismatch, the -polly-context option is ignored. Please provide "
1824 << "the context in the parameter space: " << SpaceStr << ".\n";
1825 free(SpaceStr);
1826 isl_set_free(UserContext);
1827 isl_space_free(Space);
1828 return;
1829 }
1830
1831 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001832 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1833 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001834
1835 if (strcmp(NameContext, NameUserContext) != 0) {
1836 auto SpaceStr = isl_space_to_str(Space);
1837 errs() << "Error: the name of dimension " << i
1838 << " provided in -polly-context "
1839 << "is '" << NameUserContext << "', but the name in the computed "
1840 << "context is '" << NameContext
1841 << "'. Due to this name mismatch, "
1842 << "the -polly-context option is ignored. Please provide "
1843 << "the context in the parameter space: " << SpaceStr << ".\n";
1844 free(SpaceStr);
1845 isl_set_free(UserContext);
1846 isl_space_free(Space);
1847 return;
1848 }
1849
1850 UserContext =
1851 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1852 isl_space_get_dim_id(Space, isl_dim_param, i));
1853 }
1854
1855 Context = isl_set_intersect(Context, UserContext);
1856 isl_space_free(Space);
1857}
1858
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001859void Scop::buildInvariantEquivalenceClasses(ScopDetection &SD) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00001860 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001861
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001862 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001863 for (LoadInst *LInst : RIL) {
1864 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1865
Johannes Doerfert96e54712016-02-07 17:30:13 +00001866 Type *Ty = LInst->getType();
1867 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001868 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001869 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001870 continue;
1871 }
1872
1873 ClassRep = LInst;
Johannes Doerfert96e54712016-02-07 17:30:13 +00001874 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(), nullptr,
1875 Ty);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001876 }
1877}
1878
Tobias Grosser6be480c2011-11-08 15:41:13 +00001879void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001880 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001881 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001882 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00001883 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001884}
1885
Tobias Grosser18daaca2012-05-22 10:47:27 +00001886void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001887 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001888 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001889
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001890 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001891
Johannes Doerferte7044942015-02-24 11:58:30 +00001892 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001893 }
1894}
1895
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001896void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001897 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001898 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001899
Tobias Grosser083d3d32014-06-28 08:59:45 +00001900 for (const auto &ParamID : ParameterIds) {
1901 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001902 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001903 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001904 }
1905
1906 // Align the parameters of all data structures to the model.
1907 Context = isl_set_align_params(Context, Space);
1908
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001909 for (ScopStmt &Stmt : *this)
1910 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001911}
1912
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001913static __isl_give isl_set *
1914simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1915 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001916 // If we modelt all blocks in the SCoP that have side effects we can simplify
1917 // the context with the constraints that are needed for anything to be
1918 // executed at all. However, if we have error blocks in the SCoP we already
1919 // assumed some parameter combinations cannot occure and removed them from the
1920 // domains, thus we cannot use the remaining domain to simplify the
1921 // assumptions.
1922 if (!S.hasErrorBlock()) {
1923 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1924 AssumptionContext =
1925 isl_set_gist_params(AssumptionContext, DomainParameters);
1926 }
1927
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001928 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1929 return AssumptionContext;
1930}
1931
1932void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001933 // The parameter constraints of the iteration domains give us a set of
1934 // constraints that need to hold for all cases where at least a single
1935 // statement iteration is executed in the whole scop. We now simplify the
1936 // assumed context under the assumption that such constraints hold and at
1937 // least a single statement iteration is executed. For cases where no
1938 // statement instances are executed, the assumptions we have taken about
1939 // the executed code do not matter and can be changed.
1940 //
1941 // WARNING: This only holds if the assumptions we have taken do not reduce
1942 // the set of statement instances that are executed. Otherwise we
1943 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001944 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001945 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001946 // performed. In such a case, modifying the run-time conditions and
1947 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001948 // to not be executed.
1949 //
1950 // Example:
1951 //
1952 // When delinearizing the following code:
1953 //
1954 // for (long i = 0; i < 100; i++)
1955 // for (long j = 0; j < m; j++)
1956 // A[i+p][j] = 1.0;
1957 //
1958 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001959 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001960 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001961 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001962 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001963}
1964
Johannes Doerfertb164c792014-09-18 11:17:17 +00001965/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001966static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001967 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1968 isl_pw_multi_aff *MinPMA, *MaxPMA;
1969 isl_pw_aff *LastDimAff;
1970 isl_aff *OneAff;
1971 unsigned Pos;
1972
Johannes Doerfert9143d672014-09-27 11:02:39 +00001973 // Restrict the number of parameters involved in the access as the lexmin/
1974 // lexmax computation will take too long if this number is high.
1975 //
1976 // Experiments with a simple test case using an i7 4800MQ:
1977 //
1978 // #Parameters involved | Time (in sec)
1979 // 6 | 0.01
1980 // 7 | 0.04
1981 // 8 | 0.12
1982 // 9 | 0.40
1983 // 10 | 1.54
1984 // 11 | 6.78
1985 // 12 | 30.38
1986 //
1987 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1988 unsigned InvolvedParams = 0;
1989 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1990 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1991 InvolvedParams++;
1992
1993 if (InvolvedParams > RunTimeChecksMaxParameters) {
1994 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001995 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001996 }
1997 }
1998
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001999 Set = isl_set_remove_divs(Set);
2000
Johannes Doerfertb164c792014-09-18 11:17:17 +00002001 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2002 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2003
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002004 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2005 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2006
Johannes Doerfertb164c792014-09-18 11:17:17 +00002007 // Adjust the last dimension of the maximal access by one as we want to
2008 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2009 // we test during code generation might now point after the end of the
2010 // allocated array but we will never dereference it anyway.
2011 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2012 "Assumed at least one output dimension");
2013 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2014 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2015 OneAff = isl_aff_zero_on_domain(
2016 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2017 OneAff = isl_aff_add_constant_si(OneAff, 1);
2018 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2019 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2020
2021 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2022
2023 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002024 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002025}
2026
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002027static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2028 isl_set *Domain = MA->getStatement()->getDomain();
2029 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2030 return isl_set_reset_tuple_id(Domain);
2031}
2032
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002033/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
2034static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00002035 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002036 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002037
2038 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2039 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002040 Locations = isl_union_set_coalesce(Locations);
2041 Locations = isl_union_set_detect_equalities(Locations);
2042 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002043 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002044 isl_union_set_free(Locations);
2045 return Valid;
2046}
2047
Johannes Doerfert96425c22015-08-30 21:13:53 +00002048/// @brief Helper to treat non-affine regions and basic blocks the same.
2049///
2050///{
2051
2052/// @brief Return the block that is the representing block for @p RN.
2053static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2054 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2055 : RN->getNodeAs<BasicBlock>();
2056}
2057
2058/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002059static inline BasicBlock *
2060getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002061 if (RN->isSubRegion()) {
2062 assert(idx == 0);
2063 return RN->getNodeAs<Region>()->getExit();
2064 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002065 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002066}
2067
2068/// @brief Return the smallest loop surrounding @p RN.
2069static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2070 if (!RN->isSubRegion())
2071 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2072
2073 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2074 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2075 while (L && NonAffineSubRegion->contains(L))
2076 L = L->getParentLoop();
2077 return L;
2078}
2079
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002080static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2081 if (!RN->isSubRegion())
2082 return 1;
2083
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002084 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002085 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002086}
2087
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002088static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2089 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002090 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002091 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002092 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002093 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002094 return true;
2095 return false;
2096}
2097
Johannes Doerfert96425c22015-08-30 21:13:53 +00002098///}
2099
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002100static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2101 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002102 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002103 isl_id *DimId =
2104 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2105 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2106}
2107
Johannes Doerfert96425c22015-08-30 21:13:53 +00002108isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002109 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002110}
2111
2112isl_set *Scop::getDomainConditions(BasicBlock *BB) {
2113 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002114 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002115}
2116
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002117void Scop::removeErrorBlockDomains(ScopDetection &SD, DominatorTree &DT,
2118 LoopInfo &LI) {
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002119 auto removeDomains = [this, &DT](BasicBlock *Start) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002120 auto *BBNode = DT.getNode(Start);
2121 for (auto *ErrorChild : depth_first(BBNode)) {
2122 auto *ErrorChildBlock = ErrorChild->getBlock();
2123 auto *CurrentDomain = DomainMap[ErrorChildBlock];
2124 auto *Empty = isl_set_empty(isl_set_get_space(CurrentDomain));
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002125 DomainMap[ErrorChildBlock] = Empty;
2126 isl_set_free(CurrentDomain);
2127 }
2128 };
2129
Tobias Grosser5ef2bc32015-11-23 10:18:23 +00002130 SmallVector<Region *, 4> Todo = {&R};
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002131
2132 while (!Todo.empty()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002133 auto *SubRegion = Todo.back();
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002134 Todo.pop_back();
2135
2136 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
2137 for (auto &Child : *SubRegion)
2138 Todo.push_back(Child.get());
2139 continue;
2140 }
2141 if (containsErrorBlock(SubRegion->getNode(), getRegion(), LI, DT))
2142 removeDomains(SubRegion->getEntry());
2143 }
2144
Johannes Doerferta90943d2016-02-21 16:37:25 +00002145 for (auto *BB : R.blocks())
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002146 if (isErrorBlock(*BB, R, LI, DT))
2147 removeDomains(BB);
2148}
2149
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002150void Scop::buildDomains(Region *R, ScopDetection &SD, DominatorTree &DT,
2151 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002152
Johannes Doerfert432658d2016-01-26 11:01:41 +00002153 bool IsOnlyNonAffineRegion = SD.isNonAffineSubRegion(R, R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002154 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002155 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2156 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002157 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002158
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002159 while (LD-- >= 0) {
2160 S = addDomainDimId(S, LD + 1, L);
2161 L = L->getParentLoop();
2162 }
2163
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002164 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002165
Johannes Doerfert432658d2016-01-26 11:01:41 +00002166 if (IsOnlyNonAffineRegion)
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002167 return;
2168
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002169 buildDomainsWithBranchConstraints(R, SD, DT, LI);
2170 propagateDomainConstraints(R, SD, DT, LI);
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002171
2172 // Error blocks and blocks dominated by them have been assumed to never be
2173 // executed. Representing them in the Scop does not add any value. In fact,
2174 // it is likely to cause issues during construction of the ScopStmts. The
2175 // contents of error blocks have not been verfied to be expressible and
2176 // will cause problems when building up a ScopStmt for them.
2177 // Furthermore, basic blocks dominated by error blocks may reference
2178 // instructions in the error block which, if the error block is not modeled,
2179 // can themselves not be constructed properly.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002180 removeErrorBlockDomains(SD, DT, LI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002181}
2182
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002183void Scop::buildDomainsWithBranchConstraints(Region *R, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002184 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert6f50c292016-01-26 11:03:25 +00002185 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002186
2187 // To create the domain for each block in R we iterate over all blocks and
2188 // subregions in R and propagate the conditions under which the current region
2189 // element is executed. To this end we iterate in reverse post order over R as
2190 // it ensures that we first visit all predecessors of a region node (either a
2191 // basic block or a subregion) before we visit the region node itself.
2192 // Initially, only the domain for the SCoP region entry block is set and from
2193 // there we propagate the current domain to all successors, however we add the
2194 // condition that the successor is actually executed next.
2195 // As we are only interested in non-loop carried constraints here we can
2196 // simply skip loop back edges.
2197
2198 ReversePostOrderTraversal<Region *> RTraversal(R);
2199 for (auto *RN : RTraversal) {
2200
2201 // Recurse for affine subregions but go on for basic blocks and non-affine
2202 // subregions.
2203 if (RN->isSubRegion()) {
2204 Region *SubRegion = RN->getNodeAs<Region>();
2205 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002206 buildDomainsWithBranchConstraints(SubRegion, SD, DT, LI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002207 continue;
2208 }
2209 }
2210
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002211 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002212 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002213
Johannes Doerfert96425c22015-08-30 21:13:53 +00002214 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002215 TerminatorInst *TI = BB->getTerminator();
2216
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002217 if (isa<UnreachableInst>(TI))
2218 continue;
2219
Johannes Doerfertf5673802015-10-01 23:48:18 +00002220 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002221 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002222 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002223
2224 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2225 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2226
2227 // Build the condition sets for the successor nodes of the current region
2228 // node. If it is a non-affine subregion we will always execute the single
2229 // exit node, hence the single entry node domain is the condition set. For
2230 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002231 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002232 if (RN->isSubRegion())
2233 ConditionSets.push_back(isl_set_copy(Domain));
2234 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002235 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002236
2237 // Now iterate over the successors and set their initial domain based on
2238 // their condition set. We skip back edges here and have to be careful when
2239 // we leave a loop not to keep constraints over a dimension that doesn't
2240 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002241 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002242 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002243 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002244 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002245
2246 // Skip back edges.
2247 if (DT.dominates(SuccBB, BB)) {
2248 isl_set_free(CondSet);
2249 continue;
2250 }
2251
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002252 // Do not adjust the number of dimensions if we enter a boxed loop or are
2253 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002254 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfert6f50c292016-01-26 11:03:25 +00002255 while (BoxedLoops.count(SuccBBLoop))
2256 SuccBBLoop = SuccBBLoop->getParentLoop();
Johannes Doerfert634909c2015-10-04 14:57:41 +00002257
2258 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002259
2260 // Check if the edge to SuccBB is a loop entry or exit edge. If so
2261 // adjust the dimensionality accordingly. Lastly, if we leave a loop
2262 // and enter a new one we need to drop the old constraints.
2263 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002264 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002265 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002266 CondSet = isl_set_project_out(CondSet, isl_dim_set,
2267 isl_set_n_dim(CondSet) - LoopDepthDiff,
2268 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002269 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002270 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002271 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002272 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002273 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002274 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002275 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
2276 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002277 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002278 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002279 }
2280
2281 // Set the domain for the successor or merge it with an existing domain in
2282 // case there are multiple paths (without loop back edges) to the
2283 // successor block.
2284 isl_set *&SuccDomain = DomainMap[SuccBB];
2285 if (!SuccDomain)
2286 SuccDomain = CondSet;
2287 else
2288 SuccDomain = isl_set_union(SuccDomain, CondSet);
2289
2290 SuccDomain = isl_set_coalesce(SuccDomain);
Tobias Grosser75dc40c2015-12-20 13:31:48 +00002291 if (isl_set_n_basic_set(SuccDomain) > MaxConjunctsInDomain) {
2292 auto *Empty = isl_set_empty(isl_set_get_space(SuccDomain));
2293 isl_set_free(SuccDomain);
2294 SuccDomain = Empty;
2295 invalidate(ERROR_DOMAINCONJUNCTS, DebugLoc());
2296 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002297 }
2298 }
2299}
2300
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002301/// @brief Return the domain for @p BB wrt @p DomainMap.
2302///
2303/// This helper function will lookup @p BB in @p DomainMap but also handle the
2304/// case where @p BB is contained in a non-affine subregion using the region
2305/// tree obtained by @p RI.
2306static __isl_give isl_set *
2307getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
2308 RegionInfo &RI) {
2309 auto DIt = DomainMap.find(BB);
2310 if (DIt != DomainMap.end())
2311 return isl_set_copy(DIt->getSecond());
2312
2313 Region *R = RI.getRegionFor(BB);
2314 while (R->getEntry() == BB)
2315 R = R->getParent();
2316 return getDomainForBlock(R->getEntry(), DomainMap, RI);
2317}
2318
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002319void Scop::propagateDomainConstraints(Region *R, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002320 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002321 // Iterate over the region R and propagate the domain constrains from the
2322 // predecessors to the current node. In contrast to the
2323 // buildDomainsWithBranchConstraints function, this one will pull the domain
2324 // information from the predecessors instead of pushing it to the successors.
2325 // Additionally, we assume the domains to be already present in the domain
2326 // map here. However, we iterate again in reverse post order so we know all
2327 // predecessors have been visited before a block or non-affine subregion is
2328 // visited.
2329
2330 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2331 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2332
2333 ReversePostOrderTraversal<Region *> RTraversal(R);
2334 for (auto *RN : RTraversal) {
2335
2336 // Recurse for affine subregions but go on for basic blocks and non-affine
2337 // subregions.
2338 if (RN->isSubRegion()) {
2339 Region *SubRegion = RN->getNodeAs<Region>();
2340 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002341 propagateDomainConstraints(SubRegion, SD, DT, LI);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002342 continue;
2343 }
2344 }
2345
Johannes Doerfertf5673802015-10-01 23:48:18 +00002346 // Get the domain for the current block and check if it was initialized or
2347 // not. The only way it was not is if this block is only reachable via error
2348 // blocks, thus will not be executed under the assumptions we make. Such
2349 // blocks have to be skipped as their predecessors might not have domains
2350 // either. It would not benefit us to compute the domain anyway, only the
2351 // domains of the error blocks that are reachable from non-error blocks
2352 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002353 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002354 isl_set *&Domain = DomainMap[BB];
2355 if (!Domain) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002356 DomainMap.erase(BB);
2357 continue;
2358 }
Johannes Doerfertf5673802015-10-01 23:48:18 +00002359
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002360 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2361 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2362
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002363 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2364 for (auto *PredBB : predecessors(BB)) {
2365
2366 // Skip backedges
2367 if (DT.dominates(BB, PredBB))
2368 continue;
2369
2370 isl_set *PredBBDom = nullptr;
2371
2372 // Handle the SCoP entry block with its outside predecessors.
2373 if (!getRegion().contains(PredBB))
2374 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
2375
2376 if (!PredBBDom) {
2377 // Determine the loop depth of the predecessor and adjust its domain to
2378 // the domain of the current block. This can mean we have to:
2379 // o) Drop a dimension if this block is the exit of a loop, not the
2380 // header of a new loop and the predecessor was part of the loop.
2381 // o) Add an unconstrainted new dimension if this block is the header
2382 // of a loop and the predecessor is not part of it.
2383 // o) Drop the information about the innermost loop dimension when the
2384 // predecessor and the current block are surrounded by different
2385 // loops in the same depth.
2386 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2387 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2388 while (BoxedLoops.count(PredBBLoop))
2389 PredBBLoop = PredBBLoop->getParentLoop();
2390
2391 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002392 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002393 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002394 PredBBDom = isl_set_project_out(
2395 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2396 LoopDepthDiff);
2397 else if (PredBBLoopDepth < BBLoopDepth) {
2398 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002399 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002400 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2401 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002402 PredBBDom = isl_set_drop_constraints_involving_dims(
2403 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002404 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002405 }
2406
2407 PredDom = isl_set_union(PredDom, PredBBDom);
2408 }
2409
2410 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002411 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002412
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002413 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002414 addLoopBoundsToHeaderDomain(BBLoop, LI);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002415
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002416 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002417 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002418 IsOptimized = true;
2419 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002420 addAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2421 AS_RESTRICTION);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002422 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002423 }
2424}
2425
2426/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2427/// is incremented by one and all other dimensions are equal, e.g.,
2428/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2429/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2430static __isl_give isl_map *
2431createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2432 auto *MapSpace = isl_space_map_from_set(SetSpace);
2433 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2434 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2435 if (u != Dim)
2436 NextIterationMap =
2437 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2438 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2439 C = isl_constraint_set_constant_si(C, 1);
2440 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2441 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2442 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2443 return NextIterationMap;
2444}
2445
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002446void Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002447 int LoopDepth = getRelativeLoopDepth(L);
2448 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002449
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002450 BasicBlock *HeaderBB = L->getHeader();
2451 assert(DomainMap.count(HeaderBB));
2452 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002453
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002454 isl_map *NextIterationMap =
2455 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002456
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002457 isl_set *UnionBackedgeCondition =
2458 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002459
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002460 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2461 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002462
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002463 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002464
2465 // If the latch is only reachable via error statements we skip it.
2466 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2467 if (!LatchBBDom)
2468 continue;
2469
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002470 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002471
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002472 TerminatorInst *TI = LatchBB->getTerminator();
2473 BranchInst *BI = dyn_cast<BranchInst>(TI);
2474 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002475 BackedgeCondition = isl_set_copy(LatchBBDom);
2476 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002477 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002478 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002479 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002480
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002481 // Free the non back edge condition set as we do not need it.
2482 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002483
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002484 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002485 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002486
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002487 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2488 assert(LatchLoopDepth >= LoopDepth);
2489 BackedgeCondition =
2490 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2491 LatchLoopDepth - LoopDepth);
2492 UnionBackedgeCondition =
2493 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002494 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002495
2496 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2497 for (int i = 0; i < LoopDepth; i++)
2498 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2499
2500 isl_set *UnionBackedgeConditionComplement =
2501 isl_set_complement(UnionBackedgeCondition);
2502 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2503 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2504 UnionBackedgeConditionComplement =
2505 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2506 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2507 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2508
2509 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2510 HeaderBBDom = Parts.second;
2511
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002512 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2513 // the bounded assumptions to the context as they are already implied by the
2514 // <nsw> tag.
2515 if (Affinator.hasNSWAddRecForLoop(L)) {
2516 isl_set_free(Parts.first);
2517 return;
2518 }
2519
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002520 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002521 addAssumption(INFINITELOOP, UnboundedCtx,
2522 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002523}
2524
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002525void Scop::buildAliasChecks(AliasAnalysis &AA) {
2526 if (!PollyUseRuntimeAliasChecks)
2527 return;
2528
2529 if (buildAliasGroups(AA))
2530 return;
2531
2532 // If a problem occurs while building the alias groups we need to delete
2533 // this SCoP and pretend it wasn't valid in the first place. To this end
2534 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002535 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002536
2537 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2538 << " could not be created as the number of parameters involved "
2539 "is too high. The SCoP will be "
2540 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2541 "the maximal number of parameters but be advised that the "
2542 "compile time might increase exponentially.\n\n");
2543}
2544
Johannes Doerfert9143d672014-09-27 11:02:39 +00002545bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002546 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002547 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002548 // for all memory accesses inside the SCoP.
2549 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002550 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002551 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002552 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002553 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002554 // if their access domains intersect, otherwise they are in different
2555 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002556 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002557 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002558 // and maximal accesses to each array of a group in read only and non
2559 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002560 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2561
2562 AliasSetTracker AST(AA);
2563
2564 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002565 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002566 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002567
2568 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002569 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002570 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2571 isl_set_free(StmtDomain);
2572 if (StmtDomainEmpty)
2573 continue;
2574
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002575 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002576 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002577 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002578 if (!MA->isRead())
2579 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002580 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00002581 if (MA->isRead() && isa<MemTransferInst>(Acc))
2582 PtrToAcc[cast<MemTransferInst>(Acc)->getSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00002583 else
2584 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002585 AST.add(Acc);
2586 }
2587 }
2588
2589 SmallVector<AliasGroupTy, 4> AliasGroups;
2590 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002591 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002592 continue;
2593 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00002594 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00002595 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00002596 if (AG.size() < 2)
2597 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002598 AliasGroups.push_back(std::move(AG));
2599 }
2600
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002601 // Split the alias groups based on their domain.
2602 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2603 AliasGroupTy NewAG;
2604 AliasGroupTy &AG = AliasGroups[u];
2605 AliasGroupTy::iterator AGI = AG.begin();
2606 isl_set *AGDomain = getAccessDomain(*AGI);
2607 while (AGI != AG.end()) {
2608 MemoryAccess *MA = *AGI;
2609 isl_set *MADomain = getAccessDomain(MA);
2610 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2611 NewAG.push_back(MA);
2612 AGI = AG.erase(AGI);
2613 isl_set_free(MADomain);
2614 } else {
2615 AGDomain = isl_set_union(AGDomain, MADomain);
2616 AGI++;
2617 }
2618 }
2619 if (NewAG.size() > 1)
2620 AliasGroups.push_back(std::move(NewAG));
2621 isl_set_free(AGDomain);
2622 }
2623
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002624 auto &F = *getRegion().getEntry()->getParent();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002625 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002626 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2627 for (AliasGroupTy &AG : AliasGroups) {
2628 NonReadOnlyBaseValues.clear();
2629 ReadOnlyPairs.clear();
2630
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002631 if (AG.size() < 2) {
2632 AG.clear();
2633 continue;
2634 }
2635
Johannes Doerfert13771732014-10-01 12:40:46 +00002636 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002637 emitOptimizationRemarkAnalysis(
2638 F.getContext(), DEBUG_TYPE, F,
2639 (*II)->getAccessInstruction()->getDebugLoc(),
2640 "Possibly aliasing pointer, use restrict keyword.");
2641
Johannes Doerfert13771732014-10-01 12:40:46 +00002642 Value *BaseAddr = (*II)->getBaseAddr();
2643 if (HasWriteAccess.count(BaseAddr)) {
2644 NonReadOnlyBaseValues.insert(BaseAddr);
2645 II++;
2646 } else {
2647 ReadOnlyPairs[BaseAddr].insert(*II);
2648 II = AG.erase(II);
2649 }
2650 }
2651
2652 // If we don't have read only pointers check if there are at least two
2653 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002654 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002655 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002656 continue;
2657 }
2658
2659 // If we don't have non read only pointers clear the alias group.
2660 if (NonReadOnlyBaseValues.empty()) {
2661 AG.clear();
2662 continue;
2663 }
2664
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00002665 // Check if we have non-affine accesses left, if so bail out as we cannot
2666 // generate a good access range yet.
2667 for (auto *MA : AG)
2668 if (!MA->isAffine()) {
2669 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
2670 return false;
2671 }
2672 for (auto &ReadOnlyPair : ReadOnlyPairs)
2673 for (auto *MA : ReadOnlyPair.second)
2674 if (!MA->isAffine()) {
2675 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
2676 return false;
2677 }
2678
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002679 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002680 MinMaxAliasGroups.emplace_back();
2681 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2682 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2683 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2684 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002685
2686 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002687
2688 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002689 for (MemoryAccess *MA : AG)
2690 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002691
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002692 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2693 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002694
2695 // Bail out if the number of values we need to compare is too large.
2696 // This is important as the number of comparisions grows quadratically with
2697 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002698 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2699 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002700 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002701
2702 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002703 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002704 Accesses = isl_union_map_empty(getParamSpace());
2705
2706 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2707 for (MemoryAccess *MA : ReadOnlyPair.second)
2708 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2709
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002710 Valid =
2711 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002712
2713 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002714 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002715 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002716
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002717 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002718}
2719
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002720/// @brief Get the smallest loop that contains @p R but is not in @p R.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002721static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002722 // Start with the smallest loop containing the entry and expand that
2723 // loop until it contains all blocks in the region. If there is a loop
2724 // containing all blocks in the region check if it is itself contained
2725 // and if so take the parent loop as it will be the smallest containing
2726 // the region but not contained by it.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002727 Loop *L = LI.getLoopFor(R.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002728 while (L) {
2729 bool AllContained = true;
2730 for (auto *BB : R.blocks())
2731 AllContained &= L->contains(BB);
2732 if (AllContained)
2733 break;
2734 L = L->getParentLoop();
2735 }
2736
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002737 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2738}
2739
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002740static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2741 ScopDetection &SD) {
2742
2743 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2744
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002745 unsigned MinLD = INT_MAX, MaxLD = 0;
2746 for (BasicBlock *BB : R.blocks()) {
2747 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002748 if (!R.contains(L))
2749 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002750 if (BoxedLoops && BoxedLoops->count(L))
2751 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002752 unsigned LD = L->getLoopDepth();
2753 MinLD = std::min(MinLD, LD);
2754 MaxLD = std::max(MaxLD, LD);
2755 }
2756 }
2757
2758 // Handle the case that there is no loop in the SCoP first.
2759 if (MaxLD == 0)
2760 return 1;
2761
2762 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2763 assert(MaxLD >= MinLD &&
2764 "Maximal loop depth was smaller than mininaml loop depth?");
2765 return MaxLD - MinLD + 1;
2766}
2767
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002768Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, unsigned MaxLoopDepth)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00002769 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002770 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002771 MaxLoopDepth(MaxLoopDepth), IslCtx(isl_ctx_alloc(), isl_ctx_free),
2772 Context(nullptr), Affinator(this), AssumedContext(nullptr),
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002773 InvalidContext(nullptr), Schedule(nullptr) {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002774 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00002775 buildContext();
2776}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002777
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002778void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002779 DominatorTree &DT, LoopInfo &LI) {
2780 addUserAssumptions(AC, DT, LI);
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002781 buildInvariantEquivalenceClasses(SD);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002782
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002783 buildDomains(&R, SD, DT, LI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002784
Michael Krusecac948e2015-10-02 13:53:07 +00002785 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002786 // Exit early in case there are no executable statements left in this scop.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002787 simplifySCoP(true, DT, LI);
Michael Kruseafe06702015-10-02 16:33:27 +00002788 if (Stmts.empty())
2789 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002790
Michael Krusecac948e2015-10-02 13:53:07 +00002791 // The ScopStmts now have enough information to initialize themselves.
2792 for (ScopStmt &Stmt : Stmts)
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002793 Stmt.init(SD);
Michael Krusecac948e2015-10-02 13:53:07 +00002794
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002795 buildSchedule(SD, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00002796
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002797 if (!hasFeasibleRuntimeContext())
Tobias Grosser8286b832015-11-02 11:29:32 +00002798 return;
2799
2800 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002801 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002802 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002803 addUserContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002804 addWrappingContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002805 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002806 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002807
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002808 hoistInvariantLoads(SD);
Tobias Grosser0865e7752016-02-29 07:29:42 +00002809 verifyInvariantLoads(SD);
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002810 simplifySCoP(false, DT, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00002811}
2812
2813Scop::~Scop() {
2814 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002815 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002816 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002817 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002818
Johannes Doerfert96425c22015-08-30 21:13:53 +00002819 for (auto It : DomainMap)
2820 isl_set_free(It.second);
2821
Johannes Doerfertb164c792014-09-18 11:17:17 +00002822 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002823 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002824 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002825 isl_pw_multi_aff_free(MMA.first);
2826 isl_pw_multi_aff_free(MMA.second);
2827 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002828 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002829 isl_pw_multi_aff_free(MMA.first);
2830 isl_pw_multi_aff_free(MMA.second);
2831 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002832 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002833
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002834 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002835 isl_set_free(std::get<2>(IAClass));
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002836
2837 // Explicitly release all Scop objects and the underlying isl objects before
2838 // we relase the isl context.
2839 Stmts.clear();
2840 ScopArrayInfoMap.clear();
2841 AccFuncMap.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00002842}
2843
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002844void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00002845 // Check all array accesses for each base pointer and find a (virtual) element
2846 // size for the base pointer that divides all access functions.
2847 for (auto &Stmt : *this)
2848 for (auto *Access : Stmt) {
2849 if (!Access->isArrayKind())
2850 continue;
2851 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(),
2852 ScopArrayInfo::MK_Array)];
2853 if (SAI->getNumberOfDimensions() != 1)
2854 continue;
2855 unsigned DivisibleSize = SAI->getElemSizeInBytes();
2856 auto *Subscript = Access->getSubscript(0);
2857 while (!isDivisible(Subscript, DivisibleSize, *SE))
2858 DivisibleSize /= 2;
2859 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
2860 SAI->updateElementType(Ty);
2861 }
2862
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002863 for (auto &Stmt : *this)
2864 for (auto &Access : Stmt)
2865 Access->updateDimensionality();
2866}
2867
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002868void Scop::simplifySCoP(bool RemoveIgnoredStmts, DominatorTree &DT,
2869 LoopInfo &LI) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002870 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2871 ScopStmt &Stmt = *StmtIt;
Michael Kruse7b5caa42016-02-24 22:08:28 +00002872 RegionNode *RN = Stmt.getRegionNode();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002873
Johannes Doerferteca9e892015-11-03 16:54:49 +00002874 bool RemoveStmt = StmtIt->isEmpty();
2875 if (!RemoveStmt)
Michael Kruse375cb5f2016-02-24 22:08:24 +00002876 RemoveStmt = isl_set_is_empty(DomainMap[Stmt.getEntryBlock()]);
Johannes Doerferteca9e892015-11-03 16:54:49 +00002877 if (!RemoveStmt)
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002878 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN, DT, LI));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002879
Johannes Doerferteca9e892015-11-03 16:54:49 +00002880 // Remove read only statements only after invariant loop hoisting.
2881 if (!RemoveStmt && !RemoveIgnoredStmts) {
2882 bool OnlyRead = true;
2883 for (MemoryAccess *MA : Stmt) {
2884 if (MA->isRead())
2885 continue;
2886
2887 OnlyRead = false;
2888 break;
2889 }
2890
2891 RemoveStmt = OnlyRead;
2892 }
2893
2894 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00002895 // Remove the statement because it is unnecessary.
2896 if (Stmt.isRegionStmt())
2897 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2898 StmtMap.erase(BB);
2899 else
2900 StmtMap.erase(Stmt.getBasicBlock());
2901
2902 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002903 continue;
2904 }
2905
Michael Krusecac948e2015-10-02 13:53:07 +00002906 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002907 }
2908}
2909
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002910const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2911 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2912 if (!LInst)
2913 return nullptr;
2914
2915 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2916 LInst = cast<LoadInst>(Rep);
2917
Johannes Doerfert96e54712016-02-07 17:30:13 +00002918 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002919 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2920 for (auto &IAClass : InvariantEquivClasses)
Johannes Doerfert96e54712016-02-07 17:30:13 +00002921 if (PointerSCEV == std::get<0>(IAClass) && Ty == std::get<3>(IAClass))
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002922 return &IAClass;
2923
2924 return nullptr;
2925}
2926
2927void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2928
2929 // Get the context under which the statement is executed.
2930 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2931 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2932 DomainCtx = isl_set_detect_equalities(DomainCtx);
2933 DomainCtx = isl_set_coalesce(DomainCtx);
2934
2935 // Project out all parameters that relate to loads in the statement. Otherwise
2936 // we could have cyclic dependences on the constraints under which the
2937 // hoisted loads are executed and we could not determine an order in which to
2938 // pre-load them. This happens because not only lower bounds are part of the
2939 // domain but also upper bounds.
2940 for (MemoryAccess *MA : InvMAs) {
2941 Instruction *AccInst = MA->getAccessInstruction();
2942 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00002943 SetVector<Value *> Values;
2944 for (const SCEV *Parameter : Parameters) {
2945 Values.clear();
2946 findValues(Parameter, Values);
2947 if (!Values.count(AccInst))
2948 continue;
2949
2950 if (isl_id *ParamId = getIdForParam(Parameter)) {
2951 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2952 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2953 isl_id_free(ParamId);
2954 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002955 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002956 }
2957 }
2958
2959 for (MemoryAccess *MA : InvMAs) {
2960 // Check for another invariant access that accesses the same location as
2961 // MA and if found consolidate them. Otherwise create a new equivalence
2962 // class at the end of InvariantEquivClasses.
2963 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00002964 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002965 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2966
2967 bool Consolidated = false;
2968 for (auto &IAClass : InvariantEquivClasses) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002969 if (PointerSCEV != std::get<0>(IAClass) || Ty != std::get<3>(IAClass))
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002970 continue;
2971
Johannes Doerfertdf880232016-03-03 12:26:58 +00002972 // If the pointer and the type is equal check if the access function wrt.
2973 // to the domain is equal too. It can happen that the domain fixes
2974 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00002975 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00002976 // create a new invariant load equivalence class.
2977 auto &MAs = std::get<1>(IAClass);
2978 if (!MAs.empty()) {
2979 auto *LastMA = MAs.front();
2980
2981 auto *AR = isl_map_range(MA->getAccessRelation());
2982 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
2983 bool SameAR = isl_set_is_equal(AR, LastAR);
2984 isl_set_free(AR);
2985 isl_set_free(LastAR);
2986
2987 if (!SameAR)
2988 continue;
2989 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002990
2991 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002992 MAs.push_front(MA);
2993
Johannes Doerfertdf880232016-03-03 12:26:58 +00002994 Consolidated = true;
2995
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002996 // Unify the execution context of the class and this statement.
2997 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002998 if (IAClassDomainCtx)
2999 IAClassDomainCtx = isl_set_coalesce(
3000 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
3001 else
3002 IAClassDomainCtx = isl_set_copy(DomainCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003003 break;
3004 }
3005
3006 if (Consolidated)
3007 continue;
3008
3009 // If we did not consolidate MA, thus did not find an equivalence class
3010 // for it, we create a new one.
3011 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
Johannes Doerfert96e54712016-02-07 17:30:13 +00003012 isl_set_copy(DomainCtx), Ty);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003013 }
3014
3015 isl_set_free(DomainCtx);
3016}
3017
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003018bool Scop::isHoistableAccess(MemoryAccess *Access,
3019 __isl_keep isl_union_map *Writes) {
3020 // TODO: Loads that are not loop carried, hence are in a statement with
3021 // zero iterators, are by construction invariant, though we
3022 // currently "hoist" them anyway. This is necessary because we allow
3023 // them to be treated as parameters (e.g., in conditions) and our code
3024 // generation would otherwise use the old value.
3025
3026 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003027 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003028
3029 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
3030 return false;
3031
3032 // Skip accesses that have an invariant base pointer which is defined but
3033 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3034 // returns a pointer that is used as a base address. However, as we want
3035 // to hoist indirect pointers, we allow the base pointer to be defined in
3036 // the region if it is also a memory access. Each ScopArrayInfo object
3037 // that has a base pointer origin has a base pointer that is loaded and
3038 // that it is invariant, thus it will be hoisted too. However, if there is
3039 // no base pointer origin we check that the base pointer is defined
3040 // outside the region.
3041 const ScopArrayInfo *SAI = Access->getScopArrayInfo();
Johannes Doerfert4cf15802016-02-15 12:42:05 +00003042 auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr());
3043 if (SAI->getBasePtrOriginSAI()) {
3044 assert(BasePtrInst && R.contains(BasePtrInst));
3045 if (!isa<LoadInst>(BasePtrInst))
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003046 return false;
Michael Kruse6f7721f2016-02-24 22:08:19 +00003047 auto *BasePtrStmt = getStmtFor(BasePtrInst);
Johannes Doerfert4cf15802016-02-15 12:42:05 +00003048 assert(BasePtrStmt);
3049 auto *BasePtrMA = BasePtrStmt->getArrayAccessOrNULLFor(BasePtrInst);
3050 if (BasePtrMA && !isHoistableAccess(BasePtrMA, Writes))
3051 return false;
3052 } else if (BasePtrInst && R.contains(BasePtrInst))
3053 return false;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003054
3055 // Skip accesses in non-affine subregions as they might not be executed
3056 // under the same condition as the entry of the non-affine subregion.
3057 if (BB != Access->getAccessInstruction()->getParent())
3058 return false;
3059
3060 isl_map *AccessRelation = Access->getAccessRelation();
3061
3062 // Skip accesses that have an empty access relation. These can be caused
3063 // by multiple offsets with a type cast in-between that cause the overall
3064 // byte offset to be not divisible by the new types sizes.
3065 if (isl_map_is_empty(AccessRelation)) {
3066 isl_map_free(AccessRelation);
3067 return false;
3068 }
3069
3070 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3071 Stmt.getNumIterators())) {
3072 isl_map_free(AccessRelation);
3073 return false;
3074 }
3075
3076 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3077 isl_set *AccessRange = isl_map_range(AccessRelation);
3078
3079 isl_union_map *Written = isl_union_map_intersect_range(
3080 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
3081 bool IsWritten = !isl_union_map_is_empty(Written);
3082 isl_union_map_free(Written);
3083
3084 if (IsWritten)
3085 return false;
3086
3087 return true;
3088}
3089
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003090void Scop::verifyInvariantLoads(ScopDetection &SD) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003091 auto &RIL = *SD.getRequiredInvariantLoads(&getRegion());
3092 for (LoadInst *LI : RIL) {
3093 assert(LI && getRegion().contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003094 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003095 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003096 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3097 return;
3098 }
3099 }
3100}
3101
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003102void Scop::hoistInvariantLoads(ScopDetection &SD) {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003103 if (!PollyInvariantLoadHoisting)
3104 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003105
Tobias Grosser0865e7752016-02-29 07:29:42 +00003106 isl_union_map *Writes = getWrites();
3107 for (ScopStmt &Stmt : *this) {
3108 MemoryAccessList InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003109
Tobias Grosser0865e7752016-02-29 07:29:42 +00003110 for (MemoryAccess *Access : Stmt)
3111 if (isHoistableAccess(Access, Writes))
3112 InvariantAccesses.push_front(Access);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003113
Tobias Grosser0865e7752016-02-29 07:29:42 +00003114 // We inserted invariant accesses always in the front but need them to be
3115 // sorted in a "natural order". The statements are already sorted in
3116 // reverse post order and that suffices for the accesses too. The reason
3117 // we require an order in the first place is the dependences between
3118 // invariant loads that can be caused by indirect loads.
3119 InvariantAccesses.reverse();
3120
3121 // Transfer the memory access from the statement to the SCoP.
3122 Stmt.removeMemoryAccesses(InvariantAccesses);
3123 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003124 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003125 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003126}
3127
Johannes Doerfert80ef1102014-11-07 08:31:31 +00003128const ScopArrayInfo *
Tobias Grossercc779502016-02-02 13:22:54 +00003129Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003130 ArrayRef<const SCEV *> Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00003131 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003132 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003133 if (!SAI) {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003134 auto &DL = getRegion().getEntry()->getModule()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003135 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003136 DL, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003137 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003138 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003139 // In case of mismatching array sizes, we bail out by setting the run-time
3140 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003141 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003142 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003143 }
Tobias Grosserab671442015-05-23 05:58:27 +00003144 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003145}
3146
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003147const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00003148 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003149 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003150 assert(SAI && "No ScopArrayInfo available for this base pointer");
3151 return SAI;
3152}
3153
Tobias Grosser74394f02013-01-14 22:40:23 +00003154std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003155
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003156std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003157 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003158 return stringFromIslObj(AssumedContext);
3159}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003160
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003161std::string Scop::getInvalidContextStr() const {
3162 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003163}
Tobias Grosser75805372011-04-29 06:27:02 +00003164
3165std::string Scop::getNameStr() const {
3166 std::string ExitName, EntryName;
3167 raw_string_ostream ExitStr(ExitName);
3168 raw_string_ostream EntryStr(EntryName);
3169
Tobias Grosserf240b482014-01-09 10:42:15 +00003170 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003171 EntryStr.str();
3172
3173 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003174 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003175 ExitStr.str();
3176 } else
3177 ExitName = "FunctionExit";
3178
3179 return EntryName + "---" + ExitName;
3180}
3181
Tobias Grosser74394f02013-01-14 22:40:23 +00003182__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003183__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003184 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003185}
3186
Tobias Grossere86109f2013-10-29 21:05:49 +00003187__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003188 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003189 return isl_set_copy(AssumedContext);
3190}
3191
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003192bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003193 auto *PositiveContext = getAssumedContext();
3194 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3195 bool IsFeasible = !isl_set_is_empty(PositiveContext);
3196 isl_set_free(PositiveContext);
3197 if (!IsFeasible)
3198 return false;
3199
3200 auto *NegativeContext = getInvalidContext();
3201 auto *DomainContext = isl_union_set_params(getDomains());
3202 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
3203 isl_set_free(NegativeContext);
3204 isl_set_free(DomainContext);
3205
Johannes Doerfert43788c52015-08-20 05:58:56 +00003206 return IsFeasible;
3207}
3208
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003209static std::string toString(AssumptionKind Kind) {
3210 switch (Kind) {
3211 case ALIASING:
3212 return "No-aliasing";
3213 case INBOUNDS:
3214 return "Inbounds";
3215 case WRAPPING:
3216 return "No-overflows";
3217 case ERRORBLOCK:
3218 return "No-error";
3219 case INFINITELOOP:
3220 return "Finite loop";
3221 case INVARIANTLOAD:
3222 return "Invariant load";
3223 case DELINEARIZATION:
3224 return "Delinearization";
Tobias Grosser75dc40c2015-12-20 13:31:48 +00003225 case ERROR_DOMAINCONJUNCTS:
3226 return "Low number of domain conjuncts";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003227 }
3228 llvm_unreachable("Unknown AssumptionKind!");
3229}
3230
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003231bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3232 DebugLoc Loc, AssumptionSign Sign) {
3233 if (Sign == AS_ASSUMPTION) {
3234 if (isl_set_is_subset(Context, Set))
3235 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003236
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003237 if (isl_set_is_subset(AssumedContext, Set))
3238 return false;
3239 } else {
3240 if (isl_set_is_disjoint(Set, Context))
3241 return false;
3242
3243 if (isl_set_is_subset(Set, InvalidContext))
3244 return false;
3245 }
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003246
3247 auto &F = *getRegion().getEntry()->getParent();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003248 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
3249 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003250 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003251 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003252}
3253
3254void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003255 DebugLoc Loc, AssumptionSign Sign) {
3256 if (!trackAssumption(Kind, Set, Loc, Sign)) {
3257 isl_set_free(Set);
3258 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003259 }
3260
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003261 if (Sign == AS_ASSUMPTION) {
3262 AssumedContext = isl_set_intersect(AssumedContext, Set);
3263 AssumedContext = isl_set_coalesce(AssumedContext);
3264 } else {
3265 InvalidContext = isl_set_union(InvalidContext, Set);
3266 InvalidContext = isl_set_coalesce(InvalidContext);
3267 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003268}
3269
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003270void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003271 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003272}
3273
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003274__isl_give isl_set *Scop::getInvalidContext() const {
3275 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003276}
3277
Tobias Grosser75805372011-04-29 06:27:02 +00003278void Scop::printContext(raw_ostream &OS) const {
3279 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003280 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003281
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003282 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003283 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003284
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003285 OS.indent(4) << "Invalid Context:\n";
3286 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003287
Tobias Grosser083d3d32014-06-28 08:59:45 +00003288 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00003289 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00003290 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
3291 }
Tobias Grosser75805372011-04-29 06:27:02 +00003292}
3293
Johannes Doerfertb164c792014-09-18 11:17:17 +00003294void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003295 int noOfGroups = 0;
3296 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003297 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003298 noOfGroups += 1;
3299 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003300 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003301 }
3302
Tobias Grosserbb853c22015-07-25 12:31:03 +00003303 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003304 if (MinMaxAliasGroups.empty()) {
3305 OS.indent(8) << "n/a\n";
3306 return;
3307 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003308
Tobias Grosserbb853c22015-07-25 12:31:03 +00003309 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003310
3311 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003312 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003313 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003314 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003315 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3316 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003317 }
3318 OS << " ]]\n";
3319 }
3320
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003321 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003322 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003323 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003324 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003325 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3326 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003327 }
3328 OS << " ]]\n";
3329 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003330 }
3331}
3332
Tobias Grosser75805372011-04-29 06:27:02 +00003333void Scop::printStatements(raw_ostream &OS) const {
3334 OS << "Statements {\n";
3335
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003336 for (const ScopStmt &Stmt : *this)
3337 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003338
3339 OS.indent(4) << "}\n";
3340}
3341
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003342void Scop::printArrayInfo(raw_ostream &OS) const {
3343 OS << "Arrays {\n";
3344
Tobias Grosserab671442015-05-23 05:58:27 +00003345 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003346 Array.second->print(OS);
3347
3348 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003349
3350 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3351
3352 for (auto &Array : arrays())
3353 Array.second->print(OS, /* SizeAsPwAff */ true);
3354
3355 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003356}
3357
Tobias Grosser75805372011-04-29 06:27:02 +00003358void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00003359 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
3360 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003361 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003362 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003363 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003364 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003365 const auto &MAs = std::get<1>(IAClass);
3366 if (MAs.empty()) {
3367 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003368 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003369 MAs.front()->print(OS);
3370 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003371 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003372 }
3373 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003374 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003375 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003376 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003377 printStatements(OS.indent(4));
3378}
3379
3380void Scop::dump() const { print(dbgs()); }
3381
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003382isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00003383
Johannes Doerfertcef616f2015-09-15 22:49:04 +00003384__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
3385 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003386}
3387
Tobias Grosser808cd692015-07-14 09:33:13 +00003388__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003389 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003390
Tobias Grosser808cd692015-07-14 09:33:13 +00003391 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003392 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003393
3394 return Domain;
3395}
3396
Tobias Grossere5a35142015-11-12 14:07:09 +00003397__isl_give isl_union_map *
3398Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3399 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003400
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003401 for (ScopStmt &Stmt : *this) {
3402 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003403 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003404 continue;
3405
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003406 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003407 isl_map *AccessDomain = MA->getAccessRelation();
3408 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003409 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003410 }
3411 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003412 return isl_union_map_coalesce(Accesses);
3413}
3414
3415__isl_give isl_union_map *Scop::getMustWrites() {
3416 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003417}
3418
3419__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003420 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003421}
3422
Tobias Grosser37eb4222014-02-20 21:43:54 +00003423__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003424 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003425}
3426
3427__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003428 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003429}
3430
Tobias Grosser2ac23382015-11-12 14:07:13 +00003431__isl_give isl_union_map *Scop::getAccesses() {
3432 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3433}
3434
Tobias Grosser808cd692015-07-14 09:33:13 +00003435__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00003436 auto *Tree = getScheduleTree();
3437 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00003438 isl_schedule_free(Tree);
3439 return S;
3440}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003441
Tobias Grosser808cd692015-07-14 09:33:13 +00003442__isl_give isl_schedule *Scop::getScheduleTree() const {
3443 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3444 getDomains());
3445}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003446
Tobias Grosser808cd692015-07-14 09:33:13 +00003447void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3448 auto *S = isl_schedule_from_domain(getDomains());
3449 S = isl_schedule_insert_partial_schedule(
3450 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3451 isl_schedule_free(Schedule);
3452 Schedule = S;
3453}
3454
3455void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3456 isl_schedule_free(Schedule);
3457 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003458}
3459
3460bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3461 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003462 for (ScopStmt &Stmt : *this) {
3463 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003464 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3465 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3466
3467 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3468 isl_union_set_free(StmtDomain);
3469 isl_union_set_free(NewStmtDomain);
3470 continue;
3471 }
3472
3473 Changed = true;
3474
3475 isl_union_set_free(StmtDomain);
3476 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3477
3478 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003479 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003480 isl_union_set_free(NewStmtDomain);
3481 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003482 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003483 }
3484 isl_union_set_free(Domain);
3485 return Changed;
3486}
3487
Tobias Grosser75805372011-04-29 06:27:02 +00003488ScalarEvolution *Scop::getSE() const { return SE; }
3489
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003490bool Scop::isIgnored(RegionNode *RN, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003491 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Michael Kruse6f7721f2016-02-24 22:08:19 +00003492 ScopStmt *Stmt = getStmtFor(RN);
Michael Krusea902ba62015-12-13 19:21:45 +00003493
3494 // If there is no stmt, then it already has been removed.
3495 if (!Stmt)
3496 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00003497
Johannes Doerfertf5673802015-10-01 23:48:18 +00003498 // Check if there are accesses contained.
Michael Krusea902ba62015-12-13 19:21:45 +00003499 if (Stmt->isEmpty())
Johannes Doerfertf5673802015-10-01 23:48:18 +00003500 return true;
3501
3502 // Check for reachability via non-error blocks.
3503 if (!DomainMap.count(BB))
3504 return true;
3505
3506 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003507 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003508 return true;
3509
3510 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003511}
3512
Tobias Grosser808cd692015-07-14 09:33:13 +00003513struct MapToDimensionDataTy {
3514 int N;
3515 isl_union_pw_multi_aff *Res;
3516};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003517
Tobias Grosser808cd692015-07-14 09:33:13 +00003518// @brief Create a function that maps the elements of 'Set' to its N-th
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003519// dimension and add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00003520//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003521// @param Set The input set.
3522// @param User->N The dimension to map to.
3523// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00003524//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003525// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00003526static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3527 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3528 int Dim;
3529 isl_space *Space;
3530 isl_pw_multi_aff *PMA;
3531
3532 Dim = isl_set_dim(Set, isl_dim_set);
3533 Space = isl_set_get_space(Set);
3534 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3535 Dim - Data->N);
3536 if (Data->N > 1)
3537 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3538 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3539
3540 isl_set_free(Set);
3541
3542 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003543}
3544
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003545// @brief Create an isl_multi_union_aff that defines an identity mapping
3546// from the elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003547//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003548// # Example:
3549//
3550// Domain: { A[i,j]; B[i,j,k] }
3551// N: 1
3552//
3553// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
3554//
3555// @param USet A union set describing the elements for which to generate a
3556// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00003557// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003558// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003559static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003560mapToDimension(__isl_take isl_union_set *USet, int N) {
3561 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00003562 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003563 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003564
Tobias Grosser808cd692015-07-14 09:33:13 +00003565 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00003566
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003567 auto *Space = isl_union_set_get_space(USet);
3568 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00003569
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003570 Data = {N, PwAff};
3571
3572 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00003573 (void)Res;
3574
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003575 assert(Res == isl_stat_ok);
3576
3577 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00003578 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3579}
3580
Tobias Grosser316b5b22015-11-11 19:28:14 +00003581void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003582 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003583 Stmts.emplace_back(*this, *BB);
Johannes Doerferta90943d2016-02-21 16:37:25 +00003584 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003585 StmtMap[BB] = Stmt;
3586 } else {
3587 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003588 Stmts.emplace_back(*this, *R);
Johannes Doerferta90943d2016-02-21 16:37:25 +00003589 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003590 for (BasicBlock *BB : R->blocks())
3591 StmtMap[BB] = Stmt;
3592 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003593}
3594
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003595void Scop::buildSchedule(ScopDetection &SD, LoopInfo &LI) {
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003596 Loop *L = getLoopSurroundingRegion(getRegion(), LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003597 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003598 buildSchedule(getRegion().getNode(), LoopStack, SD, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003599 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
3600 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003601}
3602
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003603/// To generate a schedule for the elements in a Region we traverse the Region
3604/// in reverse-post-order and add the contained RegionNodes in traversal order
3605/// to the schedule of the loop that is currently at the top of the LoopStack.
3606/// For loop-free codes, this results in a correct sequential ordering.
3607///
3608/// Example:
3609/// bb1(0)
3610/// / \.
3611/// bb2(1) bb3(2)
3612/// \ / \.
3613/// bb4(3) bb5(4)
3614/// \ /
3615/// bb6(5)
3616///
3617/// Including loops requires additional processing. Whenever a loop header is
3618/// encountered, the corresponding loop is added to the @p LoopStack. Starting
3619/// from an empty schedule, we first process all RegionNodes that are within
3620/// this loop and complete the sequential schedule at this loop-level before
3621/// processing about any other nodes. To implement this
3622/// loop-nodes-first-processing, the reverse post-order traversal is
3623/// insufficient. Hence, we additionally check if the traversal yields
3624/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
3625/// These region-nodes are then queue and only traverse after the all nodes
3626/// within the current loop have been processed.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003627void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, ScopDetection &SD,
3628 LoopInfo &LI) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003629 Loop *OuterScopLoop = getLoopSurroundingRegion(getRegion(), LI);
3630
3631 ReversePostOrderTraversal<Region *> RTraversal(R);
3632 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
3633 std::deque<RegionNode *> DelayList;
3634 bool LastRNWaiting = false;
3635
3636 // Iterate over the region @p R in reverse post-order but queue
3637 // sub-regions/blocks iff they are not part of the last encountered but not
3638 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
3639 // that we queued the last sub-region/block from the reverse post-order
3640 // iterator. If it is set we have to explore the next sub-region/block from
3641 // the iterator (if any) to guarantee progress. If it is not set we first try
3642 // the next queued sub-region/blocks.
3643 while (!WorkList.empty() || !DelayList.empty()) {
3644 RegionNode *RN;
3645
3646 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
3647 RN = WorkList.front();
3648 WorkList.pop_front();
3649 LastRNWaiting = false;
3650 } else {
3651 RN = DelayList.front();
3652 DelayList.pop_front();
3653 }
3654
3655 Loop *L = getRegionNodeLoop(RN, LI);
3656 if (!getRegion().contains(L))
3657 L = OuterScopLoop;
3658
3659 Loop *LastLoop = LoopStack.back().L;
3660 if (LastLoop != L) {
3661 if (!LastLoop->contains(L)) {
3662 LastRNWaiting = true;
3663 DelayList.push_back(RN);
3664 continue;
3665 }
3666 LoopStack.push_back({L, nullptr, 0});
3667 }
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003668 buildSchedule(RN, LoopStack, SD, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003669 }
3670
3671 return;
3672}
3673
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003674void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003675 ScopDetection &SD, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00003676
Tobias Grosser8362c262016-01-06 15:30:06 +00003677 if (RN->isSubRegion()) {
3678 auto *LocalRegion = RN->getNodeAs<Region>();
3679 if (!SD.isNonAffineSubRegion(LocalRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003680 buildSchedule(LocalRegion, LoopStack, SD, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00003681 return;
3682 }
3683 }
Michael Kruse046dde42015-08-10 13:01:57 +00003684
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003685 auto &LoopData = LoopStack.back();
3686 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00003687
Michael Kruse6f7721f2016-02-24 22:08:19 +00003688 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00003689 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3690 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003691 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00003692 }
3693
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003694 // Check if we just processed the last node in this loop. If we did, finalize
3695 // the loop by:
3696 //
3697 // - adding new schedule dimensions
3698 // - folding the resulting schedule into the parent loop schedule
3699 // - dropping the loop schedule from the LoopStack.
3700 //
3701 // Then continue to check surrounding loops, which might also have been
3702 // completed by this node.
3703 while (LoopData.L &&
3704 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00003705 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003706 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00003707
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003708 LoopStack.pop_back();
3709 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00003710
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003711 if (Schedule) {
3712 auto *Domain = isl_schedule_get_domain(Schedule);
3713 auto *MUPA = mapToDimension(Domain, LoopStack.size());
3714 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
3715 NextLoopData.Schedule =
3716 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003717 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003718
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003719 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
3720 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00003721 }
Tobias Grosser75805372011-04-29 06:27:02 +00003722}
3723
Michael Kruse6f7721f2016-02-24 22:08:19 +00003724ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003725 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003726 if (StmtMapIt == StmtMap.end())
3727 return nullptr;
3728 return StmtMapIt->second;
3729}
3730
Michael Kruse6f7721f2016-02-24 22:08:19 +00003731ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
3732 if (RN->isSubRegion())
3733 return getStmtFor(RN->getNodeAs<Region>());
3734 return getStmtFor(RN->getNodeAs<BasicBlock>());
3735}
3736
3737ScopStmt *Scop::getStmtFor(Region *R) const {
3738 ScopStmt *Stmt = getStmtFor(R->getEntry());
3739 assert(!Stmt || Stmt->getRegion() == R);
3740 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00003741}
3742
Johannes Doerfert96425c22015-08-30 21:13:53 +00003743int Scop::getRelativeLoopDepth(const Loop *L) const {
3744 Loop *OuterLoop =
3745 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3746 if (!OuterLoop)
3747 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003748 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3749}
3750
Michael Krused868b5d2015-09-10 15:25:24 +00003751void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003752 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003753
3754 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3755 // true, are not modeled as ordinary PHI nodes as they are not part of the
3756 // region. However, we model the operands in the predecessor blocks that are
3757 // part of the region as regular scalar accesses.
3758
3759 // If we can synthesize a PHI we can skip it, however only if it is in
3760 // the region. If it is not it can only be in the exit block of the region.
3761 // In this case we model the operands but not the PHI itself.
Michael Krusec7e0d9c2016-03-01 21:44:06 +00003762 auto *Scope = LI->getLoopFor(PHI->getParent());
3763 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R, Scope))
Michael Kruse7bf39442015-09-10 12:46:52 +00003764 return;
3765
3766 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3767 // detection. Hence, the PHI is a load of a new memory location in which the
3768 // incoming value was written at the end of the incoming basic block.
3769 bool OnlyNonAffineSubRegionOperands = true;
3770 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3771 Value *Op = PHI->getIncomingValue(u);
3772 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3773
3774 // Do not build scalar dependences inside a non-affine subregion.
3775 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3776 continue;
3777
3778 OnlyNonAffineSubRegionOperands = false;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00003779 ensurePHIWrite(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003780 }
3781
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003782 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3783 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003784 }
3785}
3786
Michael Kruse2e02d562016-02-06 09:19:40 +00003787void ScopInfo::buildScalarDependences(Instruction *Inst) {
3788 assert(!isa<PHINode>(Inst));
Michael Kruse7bf39442015-09-10 12:46:52 +00003789
Michael Kruse2e02d562016-02-06 09:19:40 +00003790 // Pull-in required operands.
3791 for (Use &Op : Inst->operands())
3792 ensureValueRead(Op.get(), Inst->getParent());
3793}
Michael Kruse7bf39442015-09-10 12:46:52 +00003794
Michael Kruse2e02d562016-02-06 09:19:40 +00003795void ScopInfo::buildEscapingDependences(Instruction *Inst) {
3796 Region *R = &scop->getRegion();
Michael Kruse7bf39442015-09-10 12:46:52 +00003797
Michael Kruse2e02d562016-02-06 09:19:40 +00003798 // Check for uses of this instruction outside the scop. Because we do not
3799 // iterate over such instructions and therefore did not "ensure" the existence
3800 // of a write, we must determine such use here.
3801 for (Use &U : Inst->uses()) {
3802 Instruction *UI = dyn_cast<Instruction>(U.getUser());
3803 if (!UI)
Michael Kruse7bf39442015-09-10 12:46:52 +00003804 continue;
3805
Michael Kruse2e02d562016-02-06 09:19:40 +00003806 BasicBlock *UseParent = getUseBlock(U);
3807 BasicBlock *UserParent = UI->getParent();
Michael Kruse7bf39442015-09-10 12:46:52 +00003808
Michael Kruse2e02d562016-02-06 09:19:40 +00003809 // An escaping value is either used by an instruction not within the scop,
3810 // or (when the scop region's exit needs to be simplified) by a PHI in the
3811 // scop's exit block. This is because region simplification before code
3812 // generation inserts new basic blocks before the PHI such that its incoming
3813 // blocks are not in the scop anymore.
3814 if (!R->contains(UseParent) ||
3815 (isa<PHINode>(UI) && UserParent == R->getExit() &&
3816 R->getExitingBlock())) {
3817 // At least one escaping use found.
3818 ensureValueWrite(Inst);
3819 break;
Michael Kruse7bf39442015-09-10 12:46:52 +00003820 }
3821 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003822}
3823
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003824bool ScopInfo::buildAccessMultiDimFixed(
Michael Kruse70131d32016-01-27 17:09:17 +00003825 MemAccInst Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003826 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3827 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse70131d32016-01-27 17:09:17 +00003828 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00003829 Type *ElementType = Val->getType();
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003830 Value *Address = Inst.getPointerOperand();
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003831 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003832 const SCEVUnknown *BasePointer =
3833 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003834 enum MemoryAccess::AccessType Type =
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003835 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003836
Michael Kruse37d136e2016-02-26 16:08:24 +00003837 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3838 auto *Src = BitCast->getOperand(0);
3839 auto *SrcTy = Src->getType();
3840 auto *DstTy = BitCast->getType();
3841 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3842 Address = Src;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003843 }
Michael Kruse37d136e2016-02-26 16:08:24 +00003844
3845 auto *GEP = dyn_cast<GetElementPtrInst>(Address);
3846 if (!GEP)
3847 return false;
3848
3849 std::vector<const SCEV *> Subscripts;
3850 std::vector<int> Sizes;
3851 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3852 auto *BasePtr = GEP->getOperand(0);
3853
3854 std::vector<const SCEV *> SizesSCEV;
3855
3856 for (auto *Subscript : Subscripts) {
3857 InvariantLoadsSetTy AccessILS;
3858 if (!isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS))
3859 return false;
3860
3861 for (LoadInst *LInst : AccessILS)
3862 if (!ScopRIL.count(LInst))
3863 return false;
3864 }
3865
3866 if (Sizes.empty())
3867 return false;
3868
3869 for (auto V : Sizes)
3870 SizesSCEV.push_back(SE->getSCEV(
3871 ConstantInt::get(IntegerType::getInt64Ty(BasePtr->getContext()), V)));
3872
3873 addArrayAccess(Inst, Type, BasePointer->getValue(), ElementType, true,
3874 Subscripts, SizesSCEV, Val);
3875 return true;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003876}
3877
3878bool ScopInfo::buildAccessMultiDimParam(
3879 MemAccInst Inst, Loop *L, Region *R,
3880 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
Hongbin Zheng22623202016-02-15 00:20:58 +00003881 const InvariantLoadsSetTy &ScopRIL, const MapInsnToMemAcc &InsnToMemAcc) {
Michael Kruse37d136e2016-02-26 16:08:24 +00003882 if (!PollyDelinearize)
3883 return false;
3884
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003885 Value *Address = Inst.getPointerOperand();
3886 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00003887 Type *ElementType = Val->getType();
3888 unsigned ElementSize = DL->getTypeAllocSize(ElementType);
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003889 enum MemoryAccess::AccessType Type =
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003890 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003891
3892 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
3893 const SCEVUnknown *BasePointer =
3894 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3895
3896 assert(BasePointer && "Could not find base pointer");
3897 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003898
Michael Kruse7bf39442015-09-10 12:46:52 +00003899 auto AccItr = InsnToMemAcc.find(Inst);
Michael Kruse37d136e2016-02-26 16:08:24 +00003900 if (AccItr == InsnToMemAcc.end())
3901 return false;
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003902
Michael Kruse37d136e2016-02-26 16:08:24 +00003903 std::vector<const SCEV *> Sizes(
3904 AccItr->second.Shape->DelinearizedSizes.begin(),
3905 AccItr->second.Shape->DelinearizedSizes.end());
3906 // Remove the element size. This information is already provided by the
3907 // ElementSize parameter. In case the element size of this access and the
3908 // element size used for delinearization differs the delinearization is
3909 // incorrect. Hence, we invalidate the scop.
3910 //
3911 // TODO: Handle delinearization with differing element sizes.
3912 auto DelinearizedSize =
3913 cast<SCEVConstant>(Sizes.back())->getAPInt().getSExtValue();
3914 Sizes.pop_back();
3915 if (ElementSize != DelinearizedSize)
3916 scop->invalidate(DELINEARIZATION, Inst->getDebugLoc());
3917
3918 addArrayAccess(Inst, Type, BasePointer->getValue(), ElementType, true,
3919 AccItr->second.DelinearizedSubscripts, Sizes, Val);
3920 return true;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003921}
3922
Johannes Doerfertcea61932016-02-21 19:13:19 +00003923bool ScopInfo::buildAccessMemIntrinsic(
3924 MemAccInst Inst, Loop *L, Region *R,
3925 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3926 const InvariantLoadsSetTy &ScopRIL) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003927 auto *MemIntr = dyn_cast_or_null<MemIntrinsic>(Inst);
3928
3929 if (MemIntr == nullptr)
Johannes Doerfertcea61932016-02-21 19:13:19 +00003930 return false;
3931
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003932 auto *LengthVal = SE->getSCEVAtScope(MemIntr->getLength(), L);
Johannes Doerfertcea61932016-02-21 19:13:19 +00003933 assert(LengthVal);
3934
Johannes Doerferta7920982016-02-25 14:08:48 +00003935 // Check if the length val is actually affine or if we overapproximate it
3936 InvariantLoadsSetTy AccessILS;
3937 bool LengthIsAffine = isAffineExpr(R, LengthVal, *SE, nullptr, &AccessILS);
3938 for (LoadInst *LInst : AccessILS)
3939 if (!ScopRIL.count(LInst))
3940 LengthIsAffine = false;
3941 if (!LengthIsAffine)
3942 LengthVal = nullptr;
3943
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003944 auto *DestPtrVal = MemIntr->getDest();
Johannes Doerfertcea61932016-02-21 19:13:19 +00003945 assert(DestPtrVal);
3946 auto *DestAccFunc = SE->getSCEVAtScope(DestPtrVal, L);
3947 assert(DestAccFunc);
3948 auto *DestPtrSCEV = dyn_cast<SCEVUnknown>(SE->getPointerBase(DestAccFunc));
3949 assert(DestPtrSCEV);
3950 DestAccFunc = SE->getMinusSCEV(DestAccFunc, DestPtrSCEV);
3951 addArrayAccess(Inst, MemoryAccess::MUST_WRITE, DestPtrSCEV->getValue(),
3952 IntegerType::getInt8Ty(DestPtrVal->getContext()), false,
3953 {DestAccFunc, LengthVal}, {}, Inst.getValueOperand());
3954
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003955 auto *MemTrans = dyn_cast<MemTransferInst>(MemIntr);
3956 if (!MemTrans)
Johannes Doerfertcea61932016-02-21 19:13:19 +00003957 return true;
3958
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003959 auto *SrcPtrVal = MemTrans->getSource();
Johannes Doerfertcea61932016-02-21 19:13:19 +00003960 assert(SrcPtrVal);
3961 auto *SrcAccFunc = SE->getSCEVAtScope(SrcPtrVal, L);
3962 assert(SrcAccFunc);
3963 auto *SrcPtrSCEV = dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccFunc));
3964 assert(SrcPtrSCEV);
3965 SrcAccFunc = SE->getMinusSCEV(SrcAccFunc, SrcPtrSCEV);
3966 addArrayAccess(Inst, MemoryAccess::READ, SrcPtrSCEV->getValue(),
3967 IntegerType::getInt8Ty(SrcPtrVal->getContext()), false,
3968 {SrcAccFunc, LengthVal}, {}, Inst.getValueOperand());
3969
3970 return true;
3971}
3972
Johannes Doerferta7920982016-02-25 14:08:48 +00003973bool ScopInfo::buildAccessCallInst(
3974 MemAccInst Inst, Loop *L, Region *R,
3975 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3976 const InvariantLoadsSetTy &ScopRIL) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003977 auto *CI = dyn_cast_or_null<CallInst>(Inst);
3978
3979 if (CI == nullptr)
Johannes Doerferta7920982016-02-25 14:08:48 +00003980 return false;
3981
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003982 if (CI->doesNotAccessMemory() || isIgnoredIntrinsic(CI))
Johannes Doerferta7920982016-02-25 14:08:48 +00003983 return true;
3984
3985 bool ReadOnly = false;
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003986 auto *AF = SE->getConstant(IntegerType::getInt64Ty(CI->getContext()), 0);
3987 auto *CalledFunction = CI->getCalledFunction();
Johannes Doerferta7920982016-02-25 14:08:48 +00003988 switch (AA->getModRefBehavior(CalledFunction)) {
3989 case llvm::FMRB_UnknownModRefBehavior:
3990 llvm_unreachable("Unknown mod ref behaviour cannot be represented.");
3991 case llvm::FMRB_DoesNotAccessMemory:
3992 return true;
3993 case llvm::FMRB_OnlyReadsMemory:
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003994 GlobalReads.push_back(CI);
Johannes Doerferta7920982016-02-25 14:08:48 +00003995 return true;
3996 case llvm::FMRB_OnlyReadsArgumentPointees:
3997 ReadOnly = true;
3998 // Fall through
3999 case llvm::FMRB_OnlyAccessesArgumentPointees:
4000 auto AccType = ReadOnly ? MemoryAccess::READ : MemoryAccess::MAY_WRITE;
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004001 for (const auto &Arg : CI->arg_operands()) {
Johannes Doerferta7920982016-02-25 14:08:48 +00004002 if (!Arg->getType()->isPointerTy())
4003 continue;
4004
4005 auto *ArgSCEV = SE->getSCEVAtScope(Arg, L);
4006 if (ArgSCEV->isZero())
4007 continue;
4008
4009 auto *ArgBasePtr = cast<SCEVUnknown>(SE->getPointerBase(ArgSCEV));
4010 addArrayAccess(Inst, AccType, ArgBasePtr->getValue(),
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004011 ArgBasePtr->getType(), false, {AF}, {}, CI);
Johannes Doerferta7920982016-02-25 14:08:48 +00004012 }
4013 return true;
4014 }
4015
4016 return true;
4017}
4018
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004019void ScopInfo::buildAccessSingleDim(
4020 MemAccInst Inst, Loop *L, Region *R,
4021 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
4022 const InvariantLoadsSetTy &ScopRIL) {
4023 Value *Address = Inst.getPointerOperand();
4024 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004025 Type *ElementType = Val->getType();
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004026 enum MemoryAccess::AccessType Type =
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004027 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004028
4029 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
4030 const SCEVUnknown *BasePointer =
4031 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
4032
4033 assert(BasePointer && "Could not find base pointer");
4034 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
Michael Kruse7bf39442015-09-10 12:46:52 +00004035
4036 // Check if the access depends on a loop contained in a non-affine subregion.
4037 bool isVariantInNonAffineLoop = false;
4038 if (BoxedLoops) {
4039 SetVector<const Loop *> Loops;
4040 findLoops(AccessFunction, Loops);
4041 for (const Loop *L : Loops)
4042 if (BoxedLoops->count(L))
4043 isVariantInNonAffineLoop = true;
4044 }
4045
Johannes Doerfert09e36972015-10-07 20:17:36 +00004046 InvariantLoadsSetTy AccessILS;
4047 bool IsAffine =
4048 !isVariantInNonAffineLoop &&
4049 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
4050
4051 for (LoadInst *LInst : AccessILS)
4052 if (!ScopRIL.count(LInst))
4053 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00004054
Michael Krusee2bccbb2015-09-18 19:59:43 +00004055 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
4056 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00004057
Johannes Doerfertcea61932016-02-21 19:13:19 +00004058 addArrayAccess(Inst, Type, BasePointer->getValue(), ElementType, IsAffine,
Tobias Grosser5d51afe2016-02-02 16:46:45 +00004059 {AccessFunction}, {}, Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00004060}
4061
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004062void ScopInfo::buildMemoryAccess(
4063 MemAccInst Inst, Loop *L, Region *R,
4064 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
Hongbin Zheng22623202016-02-15 00:20:58 +00004065 const InvariantLoadsSetTy &ScopRIL, const MapInsnToMemAcc &InsnToMemAcc) {
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004066
Johannes Doerfertcea61932016-02-21 19:13:19 +00004067 if (buildAccessMemIntrinsic(Inst, L, R, BoxedLoops, ScopRIL))
4068 return;
4069
Johannes Doerferta7920982016-02-25 14:08:48 +00004070 if (buildAccessCallInst(Inst, L, R, BoxedLoops, ScopRIL))
4071 return;
4072
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004073 if (buildAccessMultiDimFixed(Inst, L, R, BoxedLoops, ScopRIL))
4074 return;
4075
Hongbin Zheng22623202016-02-15 00:20:58 +00004076 if (buildAccessMultiDimParam(Inst, L, R, BoxedLoops, ScopRIL, InsnToMemAcc))
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004077 return;
4078
4079 buildAccessSingleDim(Inst, L, R, BoxedLoops, ScopRIL);
4080}
4081
Hongbin Zheng22623202016-02-15 00:20:58 +00004082void ScopInfo::buildAccessFunctions(Region &R, Region &SR,
4083 const MapInsnToMemAcc &InsnToMemAcc) {
Michael Kruse7bf39442015-09-10 12:46:52 +00004084
4085 if (SD->isNonAffineSubRegion(&SR, &R)) {
4086 for (BasicBlock *BB : SR.blocks())
Hongbin Zheng22623202016-02-15 00:20:58 +00004087 buildAccessFunctions(R, *BB, InsnToMemAcc, &SR);
Michael Kruse7bf39442015-09-10 12:46:52 +00004088 return;
4089 }
4090
4091 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
4092 if (I->isSubRegion())
Hongbin Zheng22623202016-02-15 00:20:58 +00004093 buildAccessFunctions(R, *I->getNodeAs<Region>(), InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00004094 else
Hongbin Zheng22623202016-02-15 00:20:58 +00004095 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>(), InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00004096}
4097
Johannes Doerferta8781032016-02-02 14:14:40 +00004098void ScopInfo::buildStmts(Region &R, Region &SR) {
Michael Krusecac948e2015-10-02 13:53:07 +00004099
Johannes Doerferta8781032016-02-02 14:14:40 +00004100 if (SD->isNonAffineSubRegion(&SR, &R)) {
Michael Krusecac948e2015-10-02 13:53:07 +00004101 scop->addScopStmt(nullptr, &SR);
4102 return;
4103 }
4104
4105 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
4106 if (I->isSubRegion())
Johannes Doerferta8781032016-02-02 14:14:40 +00004107 buildStmts(R, *I->getNodeAs<Region>());
Michael Krusecac948e2015-10-02 13:53:07 +00004108 else
4109 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
4110}
4111
Michael Krused868b5d2015-09-10 15:25:24 +00004112void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
Hongbin Zheng22623202016-02-15 00:20:58 +00004113 const MapInsnToMemAcc &InsnToMemAcc,
Michael Krused868b5d2015-09-10 15:25:24 +00004114 Region *NonAffineSubRegion,
4115 bool IsExitBlock) {
Tobias Grosser910cf262015-11-11 20:15:49 +00004116 // We do not build access functions for error blocks, as they may contain
4117 // instructions we can not model.
Johannes Doerfertc36d39b2016-02-02 14:14:20 +00004118 if (isErrorBlock(BB, R, *LI, *DT) && !IsExitBlock)
Tobias Grosser910cf262015-11-11 20:15:49 +00004119 return;
4120
Michael Kruse7bf39442015-09-10 12:46:52 +00004121 Loop *L = LI->getLoopFor(&BB);
4122
4123 // The set of loops contained in non-affine subregions that are part of R.
4124 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
4125
Johannes Doerfert09e36972015-10-07 20:17:36 +00004126 // The set of loads that are required to be invariant.
4127 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
4128
Michael Kruse2e02d562016-02-06 09:19:40 +00004129 for (Instruction &Inst : BB) {
4130 PHINode *PHI = dyn_cast<PHINode>(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00004131 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00004132 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00004133
4134 // For the exit block we stop modeling after the last PHI node.
4135 if (!PHI && IsExitBlock)
4136 break;
4137
Johannes Doerfert09e36972015-10-07 20:17:36 +00004138 // TODO: At this point we only know that elements of ScopRIL have to be
4139 // invariant and will be hoisted for the SCoP to be processed. Though,
4140 // there might be other invariant accesses that will be hoisted and
4141 // that would allow to make a non-affine access affine.
Michael Kruse70131d32016-01-27 17:09:17 +00004142 if (auto MemInst = MemAccInst::dyn_cast(Inst))
Hongbin Zheng22623202016-02-15 00:20:58 +00004143 buildMemoryAccess(MemInst, L, &R, BoxedLoops, ScopRIL, InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00004144
Michael Kruse2e02d562016-02-06 09:19:40 +00004145 if (isIgnoredIntrinsic(&Inst))
Michael Kruse7bf39442015-09-10 12:46:52 +00004146 continue;
4147
Michael Kruse2e02d562016-02-06 09:19:40 +00004148 if (!PHI)
4149 buildScalarDependences(&Inst);
4150 if (!IsExitBlock)
4151 buildEscapingDependences(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00004152 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00004153}
Michael Kruse7bf39442015-09-10 12:46:52 +00004154
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004155MemoryAccess *ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004156 MemoryAccess::AccessType AccType,
4157 Value *BaseAddress, Type *ElementType,
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004158 bool Affine, Value *AccessValue,
4159 ArrayRef<const SCEV *> Subscripts,
4160 ArrayRef<const SCEV *> Sizes,
4161 ScopArrayInfo::MemoryKind Kind) {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004162 ScopStmt *Stmt = scop->getStmtFor(BB);
Michael Krusecac948e2015-10-02 13:53:07 +00004163
4164 // Do not create a memory access for anything not in the SCoP. It would be
4165 // ignored anyway.
4166 if (!Stmt)
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004167 return nullptr;
Michael Krusecac948e2015-10-02 13:53:07 +00004168
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00004169 AccFuncSetType &AccList = scop->getOrCreateAccessFunctions(BB);
Michael Krusee2bccbb2015-09-18 19:59:43 +00004170 Value *BaseAddr = BaseAddress;
4171 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
4172
Tobias Grosserf4f68702015-12-14 15:05:37 +00004173 bool isKnownMustAccess = false;
4174
4175 // Accesses in single-basic block statements are always excuted.
4176 if (Stmt->isBlockStmt())
4177 isKnownMustAccess = true;
4178
4179 if (Stmt->isRegionStmt()) {
4180 // Accesses that dominate the exit block of a non-affine region are always
4181 // executed. In non-affine regions there may exist MK_Values that do not
4182 // dominate the exit. MK_Values will always dominate the exit and MK_PHIs
4183 // only if there is at most one PHI_WRITE in the non-affine region.
4184 if (DT->dominates(BB, Stmt->getRegion()->getExit()))
4185 isKnownMustAccess = true;
4186 }
4187
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004188 // Non-affine PHI writes do not "happen" at a particular instruction, but
4189 // after exiting the statement. Therefore they are guaranteed execute and
4190 // overwrite the old value.
4191 if (Kind == ScopArrayInfo::MK_PHI || Kind == ScopArrayInfo::MK_ExitPHI)
4192 isKnownMustAccess = true;
4193
Johannes Doerfertcea61932016-02-21 19:13:19 +00004194 if (!isKnownMustAccess && AccType == MemoryAccess::MUST_WRITE)
4195 AccType = MemoryAccess::MAY_WRITE;
Michael Krusecac948e2015-10-02 13:53:07 +00004196
Johannes Doerfertcea61932016-02-21 19:13:19 +00004197 AccList.emplace_back(Stmt, Inst, AccType, BaseAddress, ElementType, Affine,
Tobias Grossera535dff2015-12-13 19:59:01 +00004198 Subscripts, Sizes, AccessValue, Kind, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00004199 Stmt->addAccess(&AccList.back());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004200 return &AccList.back();
Michael Kruse7bf39442015-09-10 12:46:52 +00004201}
4202
Michael Kruse70131d32016-01-27 17:09:17 +00004203void ScopInfo::addArrayAccess(MemAccInst MemAccInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004204 MemoryAccess::AccessType AccType,
4205 Value *BaseAddress, Type *ElementType,
4206 bool IsAffine, ArrayRef<const SCEV *> Subscripts,
Tobias Grossera535dff2015-12-13 19:59:01 +00004207 ArrayRef<const SCEV *> Sizes,
4208 Value *AccessValue) {
Johannes Doerferta7920982016-02-25 14:08:48 +00004209 ArrayBasePointers.insert(BaseAddress);
Hongbin Zhengf3d66122016-02-26 09:47:11 +00004210 addMemoryAccess(MemAccInst->getParent(), MemAccInst, AccType, BaseAddress,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004211 ElementType, IsAffine, AccessValue, Subscripts, Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00004212 ScopArrayInfo::MK_Array);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004213}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004214
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004215void ScopInfo::ensureValueWrite(Instruction *Inst) {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004216 ScopStmt *Stmt = scop->getStmtFor(Inst);
Michael Kruse436db622016-01-26 13:33:10 +00004217
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004218 // Inst not defined within this SCoP.
Michael Kruse436db622016-01-26 13:33:10 +00004219 if (!Stmt)
4220 return;
4221
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004222 // Do not process further if the instruction is already written.
4223 if (Stmt->lookupValueWriteOf(Inst))
Michael Kruse436db622016-01-26 13:33:10 +00004224 return;
4225
Johannes Doerfertcea61932016-02-21 19:13:19 +00004226 addMemoryAccess(Inst->getParent(), Inst, MemoryAccess::MUST_WRITE, Inst,
4227 Inst->getType(), true, Inst, ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004228 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004229}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004230
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004231void ScopInfo::ensureValueRead(Value *V, BasicBlock *UserBB) {
Michael Krusefd463082016-01-27 22:51:56 +00004232
Michael Kruse2e02d562016-02-06 09:19:40 +00004233 // There cannot be an "access" for literal constants. BasicBlock references
4234 // (jump destinations) also never change.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004235 if ((isa<Constant>(V) && !isa<GlobalVariable>(V)) || isa<BasicBlock>(V))
Michael Kruse2e02d562016-02-06 09:19:40 +00004236 return;
4237
Michael Krusefd463082016-01-27 22:51:56 +00004238 // If the instruction can be synthesized and the user is in the region we do
4239 // not need to add a value dependences.
4240 Region &ScopRegion = scop->getRegion();
Michael Krusec7e0d9c2016-03-01 21:44:06 +00004241 auto *Scope = LI->getLoopFor(UserBB);
4242 if (canSynthesize(V, LI, SE, &ScopRegion, Scope))
Michael Krusefd463082016-01-27 22:51:56 +00004243 return;
4244
Michael Kruse2e02d562016-02-06 09:19:40 +00004245 // Do not build scalar dependences for required invariant loads as we will
4246 // hoist them later on anyway or drop the SCoP if we cannot.
Johannes Doerferta90943d2016-02-21 16:37:25 +00004247 auto *ScopRIL = SD->getRequiredInvariantLoads(&ScopRegion);
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004248 if (ScopRIL->count(dyn_cast<LoadInst>(V)))
Michael Kruse2e02d562016-02-06 09:19:40 +00004249 return;
4250
4251 // Determine the ScopStmt containing the value's definition and use. There is
4252 // no defining ScopStmt if the value is a function argument, a global value,
4253 // or defined outside the SCoP.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004254 Instruction *ValueInst = dyn_cast<Instruction>(V);
Michael Kruse6f7721f2016-02-24 22:08:19 +00004255 ScopStmt *ValueStmt = ValueInst ? scop->getStmtFor(ValueInst) : nullptr;
Michael Kruse2e02d562016-02-06 09:19:40 +00004256
Michael Kruse6f7721f2016-02-24 22:08:19 +00004257 ScopStmt *UserStmt = scop->getStmtFor(UserBB);
Michael Krusead28e5a2016-01-26 13:33:15 +00004258
4259 // We do not model uses outside the scop.
4260 if (!UserStmt)
4261 return;
4262
Michael Kruse2e02d562016-02-06 09:19:40 +00004263 // Add MemoryAccess for invariant values only if requested.
4264 if (!ModelReadOnlyScalars && !ValueStmt)
4265 return;
4266
4267 // Ignore use-def chains within the same ScopStmt.
4268 if (ValueStmt == UserStmt)
4269 return;
4270
Michael Krusead28e5a2016-01-26 13:33:15 +00004271 // Do not create another MemoryAccess for reloading the value if one already
4272 // exists.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004273 if (UserStmt->lookupValueReadOf(V))
Michael Krusead28e5a2016-01-26 13:33:15 +00004274 return;
4275
Johannes Doerfertcea61932016-02-21 19:13:19 +00004276 addMemoryAccess(UserBB, nullptr, MemoryAccess::READ, V, V->getType(), true, V,
Michael Kruse8d0b7342015-09-25 21:21:00 +00004277 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004278 ScopArrayInfo::MK_Value);
Michael Kruse2e02d562016-02-06 09:19:40 +00004279 if (ValueInst)
4280 ensureValueWrite(ValueInst);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004281}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004282
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004283void ScopInfo::ensurePHIWrite(PHINode *PHI, BasicBlock *IncomingBlock,
4284 Value *IncomingValue, bool IsExitBlock) {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004285 ScopStmt *IncomingStmt = scop->getStmtFor(IncomingBlock);
Michael Kruse2e02d562016-02-06 09:19:40 +00004286 if (!IncomingStmt)
4287 return;
4288
4289 // Take care for the incoming value being available in the incoming block.
4290 // This must be done before the check for multiple PHI writes because multiple
4291 // exiting edges from subregion each can be the effective written value of the
4292 // subregion. As such, all of them must be made available in the subregion
4293 // statement.
4294 ensureValueRead(IncomingValue, IncomingBlock);
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004295
4296 // Do not add more than one MemoryAccess per PHINode and ScopStmt.
4297 if (MemoryAccess *Acc = IncomingStmt->lookupPHIWriteOf(PHI)) {
4298 assert(Acc->getAccessInstruction() == PHI);
4299 Acc->addIncoming(IncomingBlock, IncomingValue);
4300 return;
4301 }
4302
4303 MemoryAccess *Acc = addMemoryAccess(
Michael Kruse375cb5f2016-02-24 22:08:24 +00004304 IncomingStmt->getEntryBlock(), PHI, MemoryAccess::MUST_WRITE, PHI,
4305 PHI->getType(), true, PHI, ArrayRef<const SCEV *>(),
4306 ArrayRef<const SCEV *>(),
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004307 IsExitBlock ? ScopArrayInfo::MK_ExitPHI : ScopArrayInfo::MK_PHI);
4308 assert(Acc);
4309 Acc->addIncoming(IncomingBlock, IncomingValue);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004310}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004311
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004312void ScopInfo::addPHIReadAccess(PHINode *PHI) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00004313 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI,
4314 PHI->getType(), true, PHI, ArrayRef<const SCEV *>(),
4315 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004316}
4317
Michael Krusedaf66942015-12-13 22:10:37 +00004318void ScopInfo::buildScop(Region &R, AssumptionCache &AC) {
Michael Kruse9d080092015-09-11 21:41:48 +00004319 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004320 scop.reset(new Scop(R, *SE, MaxLoopDepth));
Michael Kruse7bf39442015-09-10 12:46:52 +00004321
Johannes Doerferta8781032016-02-02 14:14:40 +00004322 buildStmts(R, R);
Hongbin Zheng22623202016-02-15 00:20:58 +00004323 buildAccessFunctions(R, R, *SD->getInsnToMemAccMap(&R));
Michael Kruse7bf39442015-09-10 12:46:52 +00004324
4325 // In case the region does not have an exiting block we will later (during
4326 // code generation) split the exit block. This will move potential PHI nodes
4327 // from the current exit block into the new region exiting block. Hence, PHI
4328 // nodes that are at this point not part of the region will be.
4329 // To handle these PHI nodes later we will now model their operands as scalar
4330 // accesses. Note that we do not model anything in the exit block if we have
4331 // an exiting block in the region, as there will not be any splitting later.
4332 if (!R.getExitingBlock())
Hongbin Zheng22623202016-02-15 00:20:58 +00004333 buildAccessFunctions(R, *R.getExit(), *SD->getInsnToMemAccMap(&R), nullptr,
4334 /* IsExitBlock */ true);
Michael Kruse7bf39442015-09-10 12:46:52 +00004335
Johannes Doerferta7920982016-02-25 14:08:48 +00004336 // Create memory accesses for global reads since all arrays are now known.
4337 auto *AF = SE->getConstant(IntegerType::getInt64Ty(SE->getContext()), 0);
4338 for (auto *GlobalRead : GlobalReads)
4339 for (auto *BP : ArrayBasePointers)
4340 addArrayAccess(MemAccInst(GlobalRead), MemoryAccess::READ, BP,
4341 BP->getType(), false, {AF}, {}, GlobalRead);
4342
Hongbin Zheng192f69a2016-02-13 15:12:54 +00004343 scop->init(*AA, AC, *SD, *DT, *LI);
Michael Kruse7bf39442015-09-10 12:46:52 +00004344}
4345
Michael Krused868b5d2015-09-10 15:25:24 +00004346void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00004347 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00004348 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00004349 return;
4350 }
4351
Michael Kruse9d080092015-09-11 21:41:48 +00004352 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00004353}
4354
Hongbin Zhengfec32802016-02-13 15:13:02 +00004355void ScopInfo::clear() { scop.reset(); }
Michael Kruse7bf39442015-09-10 12:46:52 +00004356
4357//===----------------------------------------------------------------------===//
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004358ScopInfo::ScopInfo() : RegionPass(ID) {}
Tobias Grosserb76f38532011-08-20 11:11:25 +00004359
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004360ScopInfo::~ScopInfo() { clear(); }
Tobias Grosserb76f38532011-08-20 11:11:25 +00004361
Tobias Grosser75805372011-04-29 06:27:02 +00004362void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00004363 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00004364 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00004365 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00004366 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4367 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004368 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004369 AU.addRequired<AssumptionCacheTracker>();
Tobias Grosser75805372011-04-29 06:27:02 +00004370 AU.setPreservesAll();
4371}
4372
4373bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00004374 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00004375
Michael Krused868b5d2015-09-10 15:25:24 +00004376 if (!SD->isMaxRegionInScop(*R))
4377 return false;
4378
4379 Function *F = R->getEntry()->getParent();
4380 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4381 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4382 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Johannes Doerferta1f291e2016-02-02 14:15:13 +00004383 DL = &F->getParent()->getDataLayout();
Michael Krusedaf66942015-12-13 22:10:37 +00004384 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004385 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krused868b5d2015-09-10 15:25:24 +00004386
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004387 DebugLoc Beg, End;
4388 getDebugLocations(R, Beg, End);
4389 std::string Msg = "SCoP begins here.";
4390 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg);
4391
Michael Krusedaf66942015-12-13 22:10:37 +00004392 buildScop(*R, AC);
Tobias Grosser75805372011-04-29 06:27:02 +00004393
Tobias Grosserd6a50b32015-05-30 06:26:21 +00004394 DEBUG(scop->print(dbgs()));
4395
Michael Kruseafe06702015-10-02 16:33:27 +00004396 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004397 Msg = "SCoP ends here but was dismissed.";
Hongbin Zhengfec32802016-02-13 15:13:02 +00004398 scop.reset();
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004399 } else {
4400 Msg = "SCoP ends here.";
4401 ++ScopFound;
4402 if (scop->getMaxLoopDepth() > 0)
4403 ++RichScopFound;
Johannes Doerfert43788c52015-08-20 05:58:56 +00004404 }
4405
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004406 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg);
4407
Tobias Grosser75805372011-04-29 06:27:02 +00004408 return false;
4409}
4410
4411char ScopInfo::ID = 0;
4412
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004413Pass *polly::createScopInfoPass() { return new ScopInfo(); }
4414
Tobias Grosser73600b82011-10-08 00:30:40 +00004415INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
4416 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004417 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004418INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004419INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004420INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004421INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004422INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004423INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004424INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00004425INITIALIZE_PASS_END(ScopInfo, "polly-scops",
4426 "Polly - Create polyhedral description of Scops", false,
4427 false)