blob: d8618a56f8fe141ac4e28527a3ef15a7e325d0d3 [file] [log] [blame]
Michael Kruse138a3fb2017-08-04 22:51:23 +00001//===------ ZoneAlgo.cpp ----------------------------------------*- C++ -*-===//
2//
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// Derive information about array elements between statements ("Zones").
11//
12// The algorithms here work on the scatter space - the image space of the
13// schedule returned by Scop::getSchedule(). We call an element in that space a
14// "timepoint". Timepoints are lexicographically ordered such that we can
15// defined ranges in the scatter space. We use two flavors of such ranges:
16// Timepoint sets and zones. A timepoint set is simply a subset of the scatter
17// space and is directly stored as isl_set.
18//
19// Zones are used to describe the space between timepoints as open sets, i.e.
20// they do not contain the extrema. Using isl rational sets to express these
21// would be overkill. We also cannot store them as the integer timepoints they
22// contain; the (nonempty) zone between 1 and 2 would be empty and
23// indistinguishable from e.g. the zone between 3 and 4. Also, we cannot store
24// the integer set including the extrema; the set ]1,2[ + ]3,4[ could be
25// coalesced to ]1,3[, although we defined the range [2,3] to be not in the set.
26// Instead, we store the "half-open" integer extrema, including the lower bound,
27// but excluding the upper bound. Examples:
28//
29// * The set { [i] : 1 <= i <= 3 } represents the zone ]0,3[ (which contains the
30// integer points 1 and 2, but not 0 or 3)
31//
32// * { [1] } represents the zone ]0,1[
33//
34// * { [i] : i = 1 or i = 3 } represents the zone ]0,1[ + ]2,3[
35//
36// Therefore, an integer i in the set represents the zone ]i-1,i[, i.e. strictly
37// speaking the integer points never belong to the zone. However, depending an
38// the interpretation, one might want to include them. Part of the
39// interpretation may not be known when the zone is constructed.
40//
41// Reads are assumed to always take place before writes, hence we can think of
42// reads taking place at the beginning of a timepoint and writes at the end.
43//
44// Let's assume that the zone represents the lifetime of a variable. That is,
45// the zone begins with a write that defines the value during its lifetime and
46// ends with the last read of that value. In the following we consider whether a
47// read/write at the beginning/ending of the lifetime zone should be within the
48// zone or outside of it.
49//
50// * A read at the timepoint that starts the live-range loads the previous
51// value. Hence, exclude the timepoint starting the zone.
52//
53// * A write at the timepoint that starts the live-range is not defined whether
54// it occurs before or after the write that starts the lifetime. We do not
55// allow this situation to occur. Hence, we include the timepoint starting the
56// zone to determine whether they are conflicting.
57//
58// * A read at the timepoint that ends the live-range reads the same variable.
59// We include the timepoint at the end of the zone to include that read into
60// the live-range. Doing otherwise would mean that the two reads access
61// different values, which would mean that the value they read are both alive
62// at the same time but occupy the same variable.
63//
64// * A write at the timepoint that ends the live-range starts a new live-range.
65// It must not be included in the live-range of the previous definition.
66//
67// All combinations of reads and writes at the endpoints are possible, but most
68// of the time only the write->read (for instance, a live-range from definition
69// to last use) and read->write (for instance, an unused range from last use to
70// overwrite) and combinations are interesting (half-open ranges). write->write
71// zones might be useful as well in some context to represent
72// output-dependencies.
73//
74// @see convertZoneToTimepoints
75//
76//
77// The code makes use of maps and sets in many different spaces. To not loose
78// track in which space a set or map is expected to be in, variables holding an
79// isl reference are usually annotated in the comments. They roughly follow isl
80// syntax for spaces, but only the tuples, not the dimensions. The tuples have a
81// meaning as follows:
82//
83// * Space[] - An unspecified tuple. Used for function parameters such that the
84// function caller can use it for anything they like.
85//
86// * Domain[] - A statement instance as returned by ScopStmt::getDomain()
87// isl_id_get_name: Stmt_<NameOfBasicBlock>
88// isl_id_get_user: Pointer to ScopStmt
89//
90// * Element[] - An array element as in the range part of
91// MemoryAccess::getAccessRelation()
92// isl_id_get_name: MemRef_<NameOfArrayVariable>
93// isl_id_get_user: Pointer to ScopArrayInfo
94//
95// * Scatter[] - Scatter space or space of timepoints
96// Has no tuple id
97//
98// * Zone[] - Range between timepoints as described above
99// Has no tuple id
100//
101// * ValInst[] - An llvm::Value as defined at a specific timepoint.
102//
103// A ValInst[] itself can be structured as one of:
104//
105// * [] - An unknown value.
106// Always zero dimensions
107// Has no tuple id
108//
109// * Value[] - An llvm::Value that is read-only in the SCoP, i.e. its
110// runtime content does not depend on the timepoint.
111// Always zero dimensions
112// isl_id_get_name: Val_<NameOfValue>
113// isl_id_get_user: A pointer to an llvm::Value
114//
115// * SCEV[...] - A synthesizable llvm::SCEV Expression.
116// In contrast to a Value[] is has at least one dimension per
117// SCEVAddRecExpr in the SCEV.
118//
119// * [Domain[] -> Value[]] - An llvm::Value that may change during the
120// Scop's execution.
121// The tuple itself has no id, but it wraps a map space holding a
122// statement instance which defines the llvm::Value as the map's domain
123// and llvm::Value itself as range.
124//
125// @see makeValInst()
126//
127// An annotation "{ Domain[] -> Scatter[] }" therefore means: A map from a
128// statement instance to a timepoint, aka a schedule. There is only one scatter
129// space, but most of the time multiple statements are processed in one set.
130// This is why most of the time isl_union_map has to be used.
131//
132// The basic algorithm works as follows:
133// At first we verify that the SCoP is compatible with this technique. For
134// instance, two writes cannot write to the same location at the same statement
135// instance because we cannot determine within the polyhedral model which one
136// comes first. Once this was verified, we compute zones at which an array
137// element is unused. This computation can fail if it takes too long. Then the
138// main algorithm is executed. Because every store potentially trails an unused
139// zone, we start at stores. We search for a scalar (MemoryKind::Value or
140// MemoryKind::PHI) that we can map to the array element overwritten by the
141// store, preferably one that is used by the store or at least the ScopStmt.
142// When it does not conflict with the lifetime of the values in the array
143// element, the map is applied and the unused zone updated as it is now used. We
144// continue to try to map scalars to the array element until there are no more
145// candidates to map. The algorithm is greedy in the sense that the first scalar
146// not conflicting will be mapped. Other scalars processed later that could have
147// fit the same unused zone will be rejected. As such the result depends on the
148// processing order.
149//
150//===----------------------------------------------------------------------===//
151
152#include "polly/ZoneAlgo.h"
153#include "polly/ScopInfo.h"
154#include "polly/Support/GICHelper.h"
155#include "polly/Support/ISLTools.h"
156#include "polly/Support/VirtualInstruction.h"
157
158#define DEBUG_TYPE "polly-zone"
159
160using namespace polly;
161using namespace llvm;
162
163static isl::union_map computeReachingDefinition(isl::union_map Schedule,
164 isl::union_map Writes,
165 bool InclDef, bool InclRedef) {
166 return computeReachingWrite(Schedule, Writes, false, InclDef, InclRedef);
167}
168
169/// Compute the reaching definition of a scalar.
170///
171/// Compared to computeReachingDefinition, there is just one element which is
172/// accessed and therefore only a set if instances that accesses that element is
173/// required.
174///
175/// @param Schedule { DomainWrite[] -> Scatter[] }
176/// @param Writes { DomainWrite[] }
177/// @param InclDef Include the timepoint of the definition to the result.
178/// @param InclRedef Include the timepoint of the overwrite into the result.
179///
180/// @return { Scatter[] -> DomainWrite[] }
181static isl::union_map computeScalarReachingDefinition(isl::union_map Schedule,
182 isl::union_set Writes,
183 bool InclDef,
184 bool InclRedef) {
185
186 // { DomainWrite[] -> Element[] }
187 auto Defs = give(isl_union_map_from_domain(Writes.take()));
188
189 // { [Element[] -> Scatter[]] -> DomainWrite[] }
190 auto ReachDefs =
191 computeReachingDefinition(Schedule, Defs, InclDef, InclRedef);
192
193 // { Scatter[] -> DomainWrite[] }
194 return give(isl_union_set_unwrap(
195 isl_union_map_range(isl_union_map_curry(ReachDefs.take()))));
196}
197
198/// Compute the reaching definition of a scalar.
199///
200/// This overload accepts only a single writing statement as an isl_map,
201/// consequently the result also is only a single isl_map.
202///
203/// @param Schedule { DomainWrite[] -> Scatter[] }
204/// @param Writes { DomainWrite[] }
205/// @param InclDef Include the timepoint of the definition to the result.
206/// @param InclRedef Include the timepoint of the overwrite into the result.
207///
208/// @return { Scatter[] -> DomainWrite[] }
209static isl::map computeScalarReachingDefinition(isl::union_map Schedule,
210 isl::set Writes, bool InclDef,
211 bool InclRedef) {
212 auto DomainSpace = give(isl_set_get_space(Writes.keep()));
213 auto ScatterSpace = getScatterSpace(Schedule);
214
215 // { Scatter[] -> DomainWrite[] }
216 auto UMap = computeScalarReachingDefinition(
217 Schedule, give(isl_union_set_from_set(Writes.take())), InclDef,
218 InclRedef);
219
220 auto ResultSpace = give(isl_space_map_from_domain_and_range(
221 ScatterSpace.take(), DomainSpace.take()));
222 return singleton(UMap, ResultSpace);
223}
224
225isl::union_map polly::makeUnknownForDomain(isl::union_set Domain) {
226 return give(isl_union_map_from_domain(Domain.take()));
227}
228
229/// Create a domain-to-unknown value mapping.
230///
231/// @see makeUnknownForDomain(isl::union_set)
232///
233/// @param Domain { Domain[] }
234///
235/// @return { Domain[] -> ValInst[] }
236static isl::map makeUnknownForDomain(isl::set Domain) {
237 return give(isl_map_from_domain(Domain.take()));
238}
239
Michael Kruse70af4f52017-08-07 18:40:29 +0000240/// Return whether @p Map maps to an unknown value.
241///
242/// @param { [] -> ValInst[] }
243static bool isMapToUnknown(const isl::map &Map) {
244 isl::space Space = Map.get_space().range();
245 return Space.has_tuple_id(isl::dim::set).is_false() &&
246 Space.is_wrapping().is_false() && Space.dim(isl::dim::set) == 0;
247}
248
249/// Return only the mappings that map to known values.
250///
251/// @param UMap { [] -> ValInst[] }
252///
253/// @return { [] -> ValInst[] }
254static isl::union_map filterKnownValInst(const isl::union_map &UMap) {
255 isl::union_map Result = isl::union_map::empty(UMap.get_space());
256 UMap.foreach_map([=, &Result](isl::map Map) -> isl::stat {
257 if (!isMapToUnknown(Map))
258 Result = Result.add_map(Map);
259 return isl::stat::ok;
260 });
261 return Result;
262}
263
Michael Kruse138a3fb2017-08-04 22:51:23 +0000264static std::string printInstruction(Instruction *Instr,
265 bool IsForDebug = false) {
266 std::string Result;
267 raw_string_ostream OS(Result);
268 Instr->print(OS, IsForDebug);
269 OS.flush();
270 size_t i = 0;
271 while (i < Result.size() && Result[i] == ' ')
272 i += 1;
273 return Result.substr(i);
274}
275
276ZoneAlgorithm::ZoneAlgorithm(const char *PassName, Scop *S, LoopInfo *LI)
277 : PassName(PassName), IslCtx(S->getSharedIslCtx()), S(S), LI(LI),
Tobias Grosser61bd3a42017-08-06 21:42:38 +0000278 Schedule(S->getSchedule()) {
Tobias Grosser31df6f32017-08-06 21:42:25 +0000279 auto Domains = S->getDomains();
Michael Kruse138a3fb2017-08-04 22:51:23 +0000280
281 Schedule =
282 give(isl_union_map_intersect_domain(Schedule.take(), Domains.take()));
283 ParamSpace = give(isl_union_map_get_space(Schedule.keep()));
284 ScatterSpace = getScatterSpace(Schedule);
285}
286
Tobias Grosser2ef37812017-08-07 22:01:29 +0000287/// Check if all stores in @p Stmt store the very same value.
288///
289/// TODO: In the future we may want to extent this to make the checks
290/// specific to different memory locations.
291static bool onlySameValueWrites(ScopStmt *Stmt) {
292 Value *V = nullptr;
293
294 for (auto *MA : *Stmt) {
295 if (!MA->isLatestArrayKind() || !MA->isMustWrite() ||
296 !MA->isOriginalArrayKind())
297 continue;
298
299 if (!V) {
300 V = MA->getAccessValue();
301 continue;
302 }
303
304 if (V != MA->getAccessValue())
305 return false;
306 }
307 return true;
308}
309
Michael Kruse138a3fb2017-08-04 22:51:23 +0000310bool ZoneAlgorithm::isCompatibleStmt(ScopStmt *Stmt) {
311 auto Stores = makeEmptyUnionMap();
312 auto Loads = makeEmptyUnionMap();
313
314 // This assumes that the MemoryKind::Array MemoryAccesses are iterated in
315 // order.
316 for (auto *MA : *Stmt) {
317 if (!MA->isLatestArrayKind())
318 continue;
319
320 auto AccRel = give(isl_union_map_from_map(getAccessRelationFor(MA).take()));
321
322 if (MA->isRead()) {
323 // Reject load after store to same location.
324 if (!isl_union_map_is_disjoint(Stores.keep(), AccRel.keep())) {
325 OptimizationRemarkMissed R(PassName, "LoadAfterStore",
326 MA->getAccessInstruction());
327 R << "load after store of same element in same statement";
328 R << " (previous stores: " << Stores;
329 R << ", loading: " << AccRel << ")";
330 S->getFunction().getContext().diagnose(R);
331 return false;
332 }
333
334 Loads = give(isl_union_map_union(Loads.take(), AccRel.take()));
335
336 continue;
337 }
338
339 if (!isa<StoreInst>(MA->getAccessInstruction())) {
340 DEBUG(dbgs() << "WRITE that is not a StoreInst not supported\n");
341 OptimizationRemarkMissed R(PassName, "UnusualStore",
342 MA->getAccessInstruction());
343 R << "encountered write that is not a StoreInst: "
344 << printInstruction(MA->getAccessInstruction());
345 S->getFunction().getContext().diagnose(R);
346 return false;
347 }
348
349 // In region statements the order is less clear, eg. the load and store
350 // might be in a boxed loop.
351 if (Stmt->isRegionStmt() &&
352 !isl_union_map_is_disjoint(Loads.keep(), AccRel.keep())) {
353 OptimizationRemarkMissed R(PassName, "StoreInSubregion",
354 MA->getAccessInstruction());
355 R << "store is in a non-affine subregion";
356 S->getFunction().getContext().diagnose(R);
357 return false;
358 }
359
360 // Do not allow more than one store to the same location.
361 if (!isl_union_map_is_disjoint(Stores.keep(), AccRel.keep())) {
362 OptimizationRemarkMissed R(PassName, "StoreAfterStore",
363 MA->getAccessInstruction());
Tobias Grosser2ef37812017-08-07 22:01:29 +0000364 if (!onlySameValueWrites(Stmt)) {
365 R << "store after store of same element in same statement";
366 R << " (previous stores: " << Stores;
367 R << ", storing: " << AccRel << ")";
368 S->getFunction().getContext().diagnose(R);
369 return false;
370 }
Michael Kruse138a3fb2017-08-04 22:51:23 +0000371 }
372
373 Stores = give(isl_union_map_union(Stores.take(), AccRel.take()));
374 }
375
376 return true;
377}
378
379void ZoneAlgorithm::addArrayReadAccess(MemoryAccess *MA) {
380 assert(MA->isLatestArrayKind());
381 assert(MA->isRead());
Michael Kruse70af4f52017-08-07 18:40:29 +0000382 ScopStmt *Stmt = MA->getStatement();
Michael Kruse138a3fb2017-08-04 22:51:23 +0000383
384 // { DomainRead[] -> Element[] }
385 auto AccRel = getAccessRelationFor(MA);
386 AllReads = give(isl_union_map_add_map(AllReads.take(), AccRel.copy()));
Michael Kruse70af4f52017-08-07 18:40:29 +0000387
388 if (LoadInst *Load = dyn_cast_or_null<LoadInst>(MA->getAccessInstruction())) {
389 // { DomainRead[] -> ValInst[] }
390 isl::map LoadValInst = makeValInst(
391 Load, Stmt, LI->getLoopFor(Load->getParent()), Stmt->isBlockStmt());
392
393 // { DomainRead[] -> [Element[] -> DomainRead[]] }
394 isl::map IncludeElement =
395 give(isl_map_curry(isl_map_domain_map(AccRel.take())));
396
397 // { [Element[] -> DomainRead[]] -> ValInst[] }
398 isl::map EltLoadValInst =
399 give(isl_map_apply_domain(LoadValInst.take(), IncludeElement.take()));
400
401 AllReadValInst = give(
402 isl_union_map_add_map(AllReadValInst.take(), EltLoadValInst.take()));
403 }
Michael Kruse138a3fb2017-08-04 22:51:23 +0000404}
405
406void ZoneAlgorithm::addArrayWriteAccess(MemoryAccess *MA) {
407 assert(MA->isLatestArrayKind());
408 assert(MA->isWrite());
409 auto *Stmt = MA->getStatement();
410
411 // { Domain[] -> Element[] }
412 auto AccRel = getAccessRelationFor(MA);
413
414 if (MA->isMustWrite())
415 AllMustWrites =
416 give(isl_union_map_add_map(AllMustWrites.take(), AccRel.copy()));
417
418 if (MA->isMayWrite())
419 AllMayWrites =
420 give(isl_union_map_add_map(AllMayWrites.take(), AccRel.copy()));
421
422 // { Domain[] -> ValInst[] }
423 auto WriteValInstance =
424 makeValInst(MA->getAccessValue(), Stmt,
425 LI->getLoopFor(MA->getAccessInstruction()->getParent()),
426 MA->isMustWrite());
427
428 // { Domain[] -> [Element[] -> Domain[]] }
429 auto IncludeElement = give(isl_map_curry(isl_map_domain_map(AccRel.copy())));
430
431 // { [Element[] -> DomainWrite[]] -> ValInst[] }
432 auto EltWriteValInst = give(
433 isl_map_apply_domain(WriteValInstance.take(), IncludeElement.take()));
434
435 AllWriteValInst = give(
436 isl_union_map_add_map(AllWriteValInst.take(), EltWriteValInst.take()));
437}
438
439isl::union_set ZoneAlgorithm::makeEmptyUnionSet() const {
440 return give(isl_union_set_empty(ParamSpace.copy()));
441}
442
443isl::union_map ZoneAlgorithm::makeEmptyUnionMap() const {
444 return give(isl_union_map_empty(ParamSpace.copy()));
445}
446
447bool ZoneAlgorithm::isCompatibleScop() {
448 for (auto &Stmt : *S) {
449 if (!isCompatibleStmt(&Stmt))
450 return false;
451 }
452 return true;
453}
454
455isl::map ZoneAlgorithm::getScatterFor(ScopStmt *Stmt) const {
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000456 isl::space ResultSpace = give(isl_space_map_from_domain_and_range(
457 Stmt->getDomainSpace().release(), ScatterSpace.copy()));
Michael Kruse138a3fb2017-08-04 22:51:23 +0000458 return give(isl_union_map_extract_map(Schedule.keep(), ResultSpace.take()));
459}
460
461isl::map ZoneAlgorithm::getScatterFor(MemoryAccess *MA) const {
462 return getScatterFor(MA->getStatement());
463}
464
465isl::union_map ZoneAlgorithm::getScatterFor(isl::union_set Domain) const {
466 return give(isl_union_map_intersect_domain(Schedule.copy(), Domain.take()));
467}
468
469isl::map ZoneAlgorithm::getScatterFor(isl::set Domain) const {
470 auto ResultSpace = give(isl_space_map_from_domain_and_range(
471 isl_set_get_space(Domain.keep()), ScatterSpace.copy()));
472 auto UDomain = give(isl_union_set_from_set(Domain.copy()));
473 auto UResult = getScatterFor(std::move(UDomain));
474 auto Result = singleton(std::move(UResult), std::move(ResultSpace));
475 assert(!Result || isl_set_is_equal(give(isl_map_domain(Result.copy())).keep(),
476 Domain.keep()) == isl_bool_true);
477 return Result;
478}
479
480isl::set ZoneAlgorithm::getDomainFor(ScopStmt *Stmt) const {
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000481 return Stmt->getDomain().remove_redundancies();
Michael Kruse138a3fb2017-08-04 22:51:23 +0000482}
483
484isl::set ZoneAlgorithm::getDomainFor(MemoryAccess *MA) const {
485 return getDomainFor(MA->getStatement());
486}
487
488isl::map ZoneAlgorithm::getAccessRelationFor(MemoryAccess *MA) const {
489 auto Domain = getDomainFor(MA);
490 auto AccRel = MA->getLatestAccessRelation();
491 return give(isl_map_intersect_domain(AccRel.take(), Domain.take()));
492}
493
494isl::map ZoneAlgorithm::getScalarReachingDefinition(ScopStmt *Stmt) {
495 auto &Result = ScalarReachDefZone[Stmt];
496 if (Result)
497 return Result;
498
499 auto Domain = getDomainFor(Stmt);
500 Result = computeScalarReachingDefinition(Schedule, Domain, false, true);
501 simplify(Result);
502
503 return Result;
504}
505
506isl::map ZoneAlgorithm::getScalarReachingDefinition(isl::set DomainDef) {
507 auto DomId = give(isl_set_get_tuple_id(DomainDef.keep()));
508 auto *Stmt = static_cast<ScopStmt *>(isl_id_get_user(DomId.keep()));
509
510 auto StmtResult = getScalarReachingDefinition(Stmt);
511
512 return give(isl_map_intersect_range(StmtResult.take(), DomainDef.take()));
513}
514
515isl::map ZoneAlgorithm::makeUnknownForDomain(ScopStmt *Stmt) const {
516 return ::makeUnknownForDomain(getDomainFor(Stmt));
517}
518
519isl::id ZoneAlgorithm::makeValueId(Value *V) {
520 if (!V)
521 return nullptr;
522
523 auto &Id = ValueIds[V];
524 if (Id.is_null()) {
525 auto Name = getIslCompatibleName("Val_", V, ValueIds.size() - 1,
526 std::string(), UseInstructionNames);
527 Id = give(isl_id_alloc(IslCtx.get(), Name.c_str(), V));
528 }
529 return Id;
530}
531
532isl::space ZoneAlgorithm::makeValueSpace(Value *V) {
533 auto Result = give(isl_space_set_from_params(ParamSpace.copy()));
534 return give(isl_space_set_tuple_id(Result.take(), isl_dim_set,
535 makeValueId(V).take()));
536}
537
538isl::set ZoneAlgorithm::makeValueSet(Value *V) {
539 auto Space = makeValueSpace(V);
540 return give(isl_set_universe(Space.take()));
541}
542
543isl::map ZoneAlgorithm::makeValInst(Value *Val, ScopStmt *UserStmt, Loop *Scope,
544 bool IsCertain) {
545 // If the definition/write is conditional, the value at the location could
546 // be either the written value or the old value. Since we cannot know which
547 // one, consider the value to be unknown.
548 if (!IsCertain)
549 return makeUnknownForDomain(UserStmt);
550
551 auto DomainUse = getDomainFor(UserStmt);
552 auto VUse = VirtualUse::create(S, UserStmt, Scope, Val, true);
553 switch (VUse.getKind()) {
554 case VirtualUse::Constant:
555 case VirtualUse::Block:
556 case VirtualUse::Hoisted:
557 case VirtualUse::ReadOnly: {
558 // The definition does not depend on the statement which uses it.
559 auto ValSet = makeValueSet(Val);
560 return give(isl_map_from_domain_and_range(DomainUse.take(), ValSet.take()));
561 }
562
563 case VirtualUse::Synthesizable: {
564 auto *ScevExpr = VUse.getScevExpr();
565 auto UseDomainSpace = give(isl_set_get_space(DomainUse.keep()));
566
567 // Construct the SCEV space.
568 // TODO: Add only the induction variables referenced in SCEVAddRecExpr
569 // expressions, not just all of them.
570 auto ScevId = give(isl_id_alloc(UseDomainSpace.get_ctx().get(), nullptr,
571 const_cast<SCEV *>(ScevExpr)));
572 auto ScevSpace =
573 give(isl_space_drop_dims(UseDomainSpace.copy(), isl_dim_set, 0, 0));
574 ScevSpace = give(
575 isl_space_set_tuple_id(ScevSpace.take(), isl_dim_set, ScevId.copy()));
576
577 // { DomainUse[] -> ScevExpr[] }
578 auto ValInst = give(isl_map_identity(isl_space_map_from_domain_and_range(
579 UseDomainSpace.copy(), ScevSpace.copy())));
580 return ValInst;
581 }
582
583 case VirtualUse::Intra: {
584 // Definition and use is in the same statement. We do not need to compute
585 // a reaching definition.
586
587 // { llvm::Value }
588 auto ValSet = makeValueSet(Val);
589
590 // { UserDomain[] -> llvm::Value }
591 auto ValInstSet =
592 give(isl_map_from_domain_and_range(DomainUse.take(), ValSet.take()));
593
594 // { UserDomain[] -> [UserDomain[] - >llvm::Value] }
595 auto Result = give(isl_map_reverse(isl_map_domain_map(ValInstSet.take())));
596 simplify(Result);
597 return Result;
598 }
599
600 case VirtualUse::Inter: {
601 // The value is defined in a different statement.
602
603 auto *Inst = cast<Instruction>(Val);
604 auto *ValStmt = S->getStmtFor(Inst);
605
606 // If the llvm::Value is defined in a removed Stmt, we cannot derive its
607 // domain. We could use an arbitrary statement, but this could result in
608 // different ValInst[] for the same llvm::Value.
609 if (!ValStmt)
610 return ::makeUnknownForDomain(DomainUse);
611
612 // { DomainDef[] }
613 auto DomainDef = getDomainFor(ValStmt);
614
615 // { Scatter[] -> DomainDef[] }
616 auto ReachDef = getScalarReachingDefinition(DomainDef);
617
618 // { DomainUse[] -> Scatter[] }
619 auto UserSched = getScatterFor(DomainUse);
620
621 // { DomainUse[] -> DomainDef[] }
622 auto UsedInstance =
623 give(isl_map_apply_range(UserSched.take(), ReachDef.take()));
624
625 // { llvm::Value }
626 auto ValSet = makeValueSet(Val);
627
628 // { DomainUse[] -> llvm::Value[] }
629 auto ValInstSet =
630 give(isl_map_from_domain_and_range(DomainUse.take(), ValSet.take()));
631
632 // { DomainUse[] -> [DomainDef[] -> llvm::Value] }
633 auto Result =
634 give(isl_map_range_product(UsedInstance.take(), ValInstSet.take()));
635
636 simplify(Result);
637 return Result;
638 }
639 }
640 llvm_unreachable("Unhandled use type");
641}
642
643void ZoneAlgorithm::computeCommon() {
644 AllReads = makeEmptyUnionMap();
645 AllMayWrites = makeEmptyUnionMap();
646 AllMustWrites = makeEmptyUnionMap();
647 AllWriteValInst = makeEmptyUnionMap();
Michael Kruse70af4f52017-08-07 18:40:29 +0000648 AllReadValInst = makeEmptyUnionMap();
Michael Kruse138a3fb2017-08-04 22:51:23 +0000649
650 for (auto &Stmt : *S) {
651 for (auto *MA : Stmt) {
652 if (!MA->isLatestArrayKind())
653 continue;
654
655 if (MA->isRead())
656 addArrayReadAccess(MA);
657
658 if (MA->isWrite())
659 addArrayWriteAccess(MA);
660 }
661 }
662
663 // { DomainWrite[] -> Element[] }
Michael Kruse70af4f52017-08-07 18:40:29 +0000664 AllWrites =
Michael Kruse138a3fb2017-08-04 22:51:23 +0000665 give(isl_union_map_union(AllMustWrites.copy(), AllMayWrites.copy()));
666
667 // { [Element[] -> Zone[]] -> DomainWrite[] }
668 WriteReachDefZone =
669 computeReachingDefinition(Schedule, AllWrites, false, true);
670 simplify(WriteReachDefZone);
671}
672
673void ZoneAlgorithm::printAccesses(llvm::raw_ostream &OS, int Indent) const {
674 OS.indent(Indent) << "After accesses {\n";
675 for (auto &Stmt : *S) {
676 OS.indent(Indent + 4) << Stmt.getBaseName() << "\n";
677 for (auto *MA : Stmt)
678 MA->print(OS);
679 }
680 OS.indent(Indent) << "}\n";
681}
Michael Kruse70af4f52017-08-07 18:40:29 +0000682
683isl::union_map ZoneAlgorithm::computeKnownFromMustWrites() const {
684 // { [Element[] -> Zone[]] -> [Element[] -> DomainWrite[]] }
685 isl::union_map EltReachdDef = distributeDomain(WriteReachDefZone.curry());
686
687 // { [Element[] -> DomainWrite[]] -> ValInst[] }
688 isl::union_map AllKnownWriteValInst = filterKnownValInst(AllWriteValInst);
689
690 // { [Element[] -> Zone[]] -> ValInst[] }
691 return EltReachdDef.apply_range(AllKnownWriteValInst);
692}
693
694isl::union_map ZoneAlgorithm::computeKnownFromLoad() const {
695 // { Element[] }
696 isl::union_set AllAccessedElts = AllReads.range().unite(AllWrites.range());
697
698 // { Element[] -> Scatter[] }
699 isl::union_map EltZoneUniverse = isl::union_map::from_domain_and_range(
700 AllAccessedElts, isl::set::universe(ScatterSpace));
701
702 // This assumes there are no "holes" in
703 // isl_union_map_domain(WriteReachDefZone); alternatively, compute the zone
704 // before the first write or that are not written at all.
705 // { Element[] -> Scatter[] }
706 isl::union_set NonReachDef =
707 EltZoneUniverse.wrap().subtract(WriteReachDefZone.domain());
708
709 // { [Element[] -> Zone[]] -> ReachDefId[] }
710 isl::union_map DefZone =
711 WriteReachDefZone.unite(isl::union_map::from_domain(NonReachDef));
712
713 // { [Element[] -> Scatter[]] -> Element[] }
714 isl::union_map EltZoneElt = EltZoneUniverse.domain_map();
715
716 // { [Element[] -> Zone[]] -> [Element[] -> ReachDefId[]] }
717 isl::union_map DefZoneEltDefId = EltZoneElt.range_product(DefZone);
718
719 // { Element[] -> [Zone[] -> ReachDefId[]] }
720 isl::union_map EltDefZone = DefZone.curry();
721
722 // { [Element[] -> Zone[] -> [Element[] -> ReachDefId[]] }
723 isl::union_map EltZoneEltDefid = distributeDomain(EltDefZone);
724
725 // { [Element[] -> Scatter[]] -> DomainRead[] }
726 isl::union_map Reads = AllReads.range_product(Schedule).reverse();
727
728 // { [Element[] -> Scatter[]] -> [Element[] -> DomainRead[]] }
729 isl::union_map ReadsElt = EltZoneElt.range_product(Reads);
730
731 // { [Element[] -> Scatter[]] -> ValInst[] }
732 isl::union_map ScatterKnown = ReadsElt.apply_range(AllReadValInst);
733
734 // { [Element[] -> ReachDefId[]] -> ValInst[] }
735 isl::union_map DefidKnown =
736 DefZoneEltDefId.apply_domain(ScatterKnown).reverse();
737
738 // { [Element[] -> Zone[]] -> ValInst[] }
739 return DefZoneEltDefId.apply_range(DefidKnown);
740}
741
742isl::union_map ZoneAlgorithm::computeKnown(bool FromWrite,
743 bool FromRead) const {
744 isl::union_map Result = makeEmptyUnionMap();
745
746 if (FromWrite)
747 Result = Result.unite(computeKnownFromMustWrites());
748
749 if (FromRead)
750 Result = Result.unite(computeKnownFromLoad());
751
752 simplify(Result);
753 return Result;
754}