Coverage Report

Created: 2018-04-23 18:20

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/polly/lib/Transform/ZoneAlgo.cpp
Line
Count
Source (jump to first uncovered line)
1
//===------ 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
#include "llvm/ADT/Statistic.h"
158
#include "llvm/Support/raw_ostream.h"
159
160
#define DEBUG_TYPE "polly-zone"
161
162
STATISTIC(NumIncompatibleArrays, "Number of not zone-analyzable arrays");
163
STATISTIC(NumCompatibleArrays, "Number of zone-analyzable arrays");
164
STATISTIC(NumRecursivePHIs, "Number of recursive PHIs");
165
STATISTIC(NumNormalizablePHIs, "Number of normalizable PHIs");
166
STATISTIC(NumPHINormialization, "Number of PHI executed normalizations");
167
168
using namespace polly;
169
using namespace llvm;
170
171
static isl::union_map computeReachingDefinition(isl::union_map Schedule,
172
                                                isl::union_map Writes,
173
182
                                                bool InclDef, bool InclRedef) {
174
182
  return computeReachingWrite(Schedule, Writes, false, InclDef, InclRedef);
175
182
}
176
177
/// Compute the reaching definition of a scalar.
178
///
179
/// Compared to computeReachingDefinition, there is just one element which is
180
/// accessed and therefore only a set if instances that accesses that element is
181
/// required.
182
///
183
/// @param Schedule  { DomainWrite[] -> Scatter[] }
184
/// @param Writes    { DomainWrite[] }
185
/// @param InclDef   Include the timepoint of the definition to the result.
186
/// @param InclRedef Include the timepoint of the overwrite into the result.
187
///
188
/// @return { Scatter[] -> DomainWrite[] }
189
static isl::union_map computeScalarReachingDefinition(isl::union_map Schedule,
190
                                                      isl::union_set Writes,
191
                                                      bool InclDef,
192
98
                                                      bool InclRedef) {
193
98
  // { DomainWrite[] -> Element[] }
194
98
  isl::union_map Defs = isl::union_map::from_domain(Writes);
195
98
196
98
  // { [Element[] -> Scatter[]] -> DomainWrite[] }
197
98
  auto ReachDefs =
198
98
      computeReachingDefinition(Schedule, Defs, InclDef, InclRedef);
199
98
200
98
  // { Scatter[] -> DomainWrite[] }
201
98
  return ReachDefs.curry().range().unwrap();
202
98
}
203
204
/// Compute the reaching definition of a scalar.
205
///
206
/// This overload accepts only a single writing statement as an isl_map,
207
/// consequently the result also is only a single isl_map.
208
///
209
/// @param Schedule  { DomainWrite[] -> Scatter[] }
210
/// @param Writes    { DomainWrite[] }
211
/// @param InclDef   Include the timepoint of the definition to the result.
212
/// @param InclRedef Include the timepoint of the overwrite into the result.
213
///
214
/// @return { Scatter[] -> DomainWrite[] }
215
static isl::map computeScalarReachingDefinition(isl::union_map Schedule,
216
                                                isl::set Writes, bool InclDef,
217
98
                                                bool InclRedef) {
218
98
  isl::space DomainSpace = Writes.get_space();
219
98
  isl::space ScatterSpace = getScatterSpace(Schedule);
220
98
221
98
  //  { Scatter[] -> DomainWrite[] }
222
98
  isl::union_map UMap = computeScalarReachingDefinition(
223
98
      Schedule, isl::union_set(Writes), InclDef, InclRedef);
224
98
225
98
  isl::space ResultSpace = ScatterSpace.map_from_domain_and_range(DomainSpace);
226
98
  return singleton(UMap, ResultSpace);
227
98
}
228
229
642
isl::union_map polly::makeUnknownForDomain(isl::union_set Domain) {
230
642
  return give(isl_union_map_from_domain(Domain.take()));
231
642
}
232
233
/// Create a domain-to-unknown value mapping.
234
///
235
/// @see makeUnknownForDomain(isl::union_set)
236
///
237
/// @param Domain { Domain[] }
238
///
239
/// @return { Domain[] -> ValInst[] }
240
17
static isl::map makeUnknownForDomain(isl::set Domain) {
241
17
  return give(isl_map_from_domain(Domain.take()));
242
17
}
243
244
/// Return whether @p Map maps to an unknown value.
245
///
246
/// @param { [] -> ValInst[] }
247
668
static bool isMapToUnknown(const isl::map &Map) {
248
668
  isl::space Space = Map.get_space().range();
249
668
  return Space.has_tuple_id(isl::dim::set).is_false() &&
250
668
         
Space.is_wrapping().is_false()487
&&
Space.dim(isl::dim::set) == 090
;
251
668
}
252
253
629
isl::union_map polly::filterKnownValInst(const isl::union_map &UMap) {
254
629
  isl::union_map Result = isl::union_map::empty(UMap.get_space());
255
668
  isl::stat Success = UMap.foreach_map([=, &Result](isl::map Map) -> isl::stat {
256
668
    if (!isMapToUnknown(Map))
257
578
      Result = Result.add_map(Map);
258
668
    return isl::stat::ok;
259
668
  });
260
629
  if (Success != isl::stat::ok)
261
2
    return {};
262
627
  return Result;
263
627
}
264
265
ZoneAlgorithm::ZoneAlgorithm(const char *PassName, Scop *S, LoopInfo *LI)
266
    : PassName(PassName), IslCtx(S->getSharedIslCtx()), S(S), LI(LI),
267
84
      Schedule(S->getSchedule()) {
268
84
  auto Domains = S->getDomains();
269
84
270
84
  Schedule =
271
84
      give(isl_union_map_intersect_domain(Schedule.take(), Domains.take()));
272
84
  ParamSpace = give(isl_union_map_get_space(Schedule.keep()));
273
84
  ScatterSpace = getScatterSpace(Schedule);
274
84
}
275
276
/// Check if all stores in @p Stmt store the very same value.
277
///
278
/// This covers a special situation occurring in Polybench's
279
/// covariance/correlation (which is typical for algorithms that cover symmetric
280
/// matrices):
281
///
282
/// for (int i = 0; i < n; i += 1)
283
///   for (int j = 0; j <= i; j += 1) {
284
///     double x = ...;
285
///     C[i][j] = x;
286
///     C[j][i] = x;
287
///   }
288
///
289
/// For i == j, the same value is written twice to the same element.Double
290
/// writes to the same element are not allowed in DeLICM because its algorithm
291
/// does not see which of the writes is effective.But if its the same value
292
/// anyway, it doesn't matter.
293
///
294
/// LLVM passes, however, cannot simplify this because the write is necessary
295
/// for i != j (unless it would add a condition for one of the writes to occur
296
/// only if i != j).
297
///
298
/// TODO: In the future we may want to extent this to make the checks
299
///       specific to different memory locations.
300
5
static bool onlySameValueWrites(ScopStmt *Stmt) {
301
5
  Value *V = nullptr;
302
5
303
16
  for (auto *MA : *Stmt) {
304
16
    if (!MA->isLatestArrayKind() || 
!MA->isMustWrite()10
||
305
16
        
!MA->isOriginalArrayKind()8
)
306
8
      continue;
307
8
308
8
    if (!V) {
309
4
      V = MA->getAccessValue();
310
4
      continue;
311
4
    }
312
4
313
4
    if (V != MA->getAccessValue())
314
2
      return false;
315
4
  }
316
5
  
return true3
;
317
5
}
318
319
void ZoneAlgorithm::collectIncompatibleElts(ScopStmt *Stmt,
320
                                            isl::union_set &IncompatibleElts,
321
320
                                            isl::union_set &AllElts) {
322
320
  auto Stores = makeEmptyUnionMap();
323
320
  auto Loads = makeEmptyUnionMap();
324
320
325
320
  // This assumes that the MemoryKind::Array MemoryAccesses are iterated in
326
320
  // order.
327
633
  for (auto *MA : *Stmt) {
328
633
    if (!MA->isOriginalArrayKind())
329
474
      continue;
330
159
331
159
    isl::map AccRelMap = getAccessRelationFor(MA);
332
159
    isl::union_map AccRel = AccRelMap;
333
159
334
159
    // To avoid solving any ILP problems, always add entire arrays instead of
335
159
    // just the elements that are accessed.
336
159
    auto ArrayElts = isl::set::universe(AccRelMap.get_space().range());
337
159
    AllElts = AllElts.add_set(ArrayElts);
338
159
339
159
    if (MA->isRead()) {
340
43
      // Reject load after store to same location.
341
43
      if (!isl_union_map_is_disjoint(Stores.keep(), AccRel.keep())) {
342
1
        DEBUG(dbgs() << "Load after store of same element in same statement\n");
343
1
        OptimizationRemarkMissed R(PassName, "LoadAfterStore",
344
1
                                   MA->getAccessInstruction());
345
1
        R << "load after store of same element in same statement";
346
1
        R << " (previous stores: " << Stores;
347
1
        R << ", loading: " << AccRel << ")";
348
1
        S->getFunction().getContext().diagnose(R);
349
1
350
1
        IncompatibleElts = IncompatibleElts.add_set(ArrayElts);
351
1
      }
352
43
353
43
      Loads = give(isl_union_map_union(Loads.take(), AccRel.take()));
354
43
355
43
      continue;
356
43
    }
357
116
358
116
    // In region statements the order is less clear, eg. the load and store
359
116
    // might be in a boxed loop.
360
116
    if (Stmt->isRegionStmt() &&
361
116
        
!isl_union_map_is_disjoint(Loads.keep(), AccRel.keep())9
) {
362
2
      DEBUG(dbgs() << "WRITE in non-affine subregion not supported\n");
363
2
      OptimizationRemarkMissed R(PassName, "StoreInSubregion",
364
2
                                 MA->getAccessInstruction());
365
2
      R << "store is in a non-affine subregion";
366
2
      S->getFunction().getContext().diagnose(R);
367
2
368
2
      IncompatibleElts = IncompatibleElts.add_set(ArrayElts);
369
2
    }
370
116
371
116
    // Do not allow more than one store to the same location.
372
116
    if (!isl_union_map_is_disjoint(Stores.keep(), AccRel.keep()) &&
373
116
        
!onlySameValueWrites(Stmt)5
) {
374
2
      DEBUG(dbgs() << "WRITE after WRITE to same element\n");
375
2
      OptimizationRemarkMissed R(PassName, "StoreAfterStore",
376
2
                                 MA->getAccessInstruction());
377
2
      R << "store after store of same element in same statement";
378
2
      R << " (previous stores: " << Stores;
379
2
      R << ", storing: " << AccRel << ")";
380
2
      S->getFunction().getContext().diagnose(R);
381
2
382
2
      IncompatibleElts = IncompatibleElts.add_set(ArrayElts);
383
2
    }
384
116
385
116
    Stores = give(isl_union_map_union(Stores.take(), AccRel.take()));
386
116
  }
387
320
}
388
389
45
void ZoneAlgorithm::addArrayReadAccess(MemoryAccess *MA) {
390
45
  assert(MA->isLatestArrayKind());
391
45
  assert(MA->isRead());
392
45
  ScopStmt *Stmt = MA->getStatement();
393
45
394
45
  // { DomainRead[] -> Element[] }
395
45
  auto AccRel = intersectRange(getAccessRelationFor(MA), CompatibleElts);
396
45
  AllReads = give(isl_union_map_add_map(AllReads.take(), AccRel.copy()));
397
45
398
45
  if (LoadInst *Load = dyn_cast_or_null<LoadInst>(MA->getAccessInstruction())) {
399
43
    // { DomainRead[] -> ValInst[] }
400
43
    isl::map LoadValInst = makeValInst(
401
43
        Load, Stmt, LI->getLoopFor(Load->getParent()), Stmt->isBlockStmt());
402
43
403
43
    // { DomainRead[] -> [Element[] -> DomainRead[]] }
404
43
    isl::map IncludeElement =
405
43
        give(isl_map_curry(isl_map_domain_map(AccRel.take())));
406
43
407
43
    // { [Element[] -> DomainRead[]] -> ValInst[] }
408
43
    isl::map EltLoadValInst =
409
43
        give(isl_map_apply_domain(LoadValInst.take(), IncludeElement.take()));
410
43
411
43
    AllReadValInst = give(
412
43
        isl_union_map_add_map(AllReadValInst.take(), EltLoadValInst.take()));
413
43
  }
414
45
}
415
416
isl::union_map ZoneAlgorithm::getWrittenValue(MemoryAccess *MA,
417
116
                                              isl::map AccRel) {
418
116
  if (!MA->isMustWrite())
419
9
    return {};
420
107
421
107
  Value *AccVal = MA->getAccessValue();
422
107
  ScopStmt *Stmt = MA->getStatement();
423
107
  Instruction *AccInst = MA->getAccessInstruction();
424
107
425
107
  // Write a value to a single element.
426
107
  auto L = MA->isOriginalArrayKind() ? LI->getLoopFor(AccInst->getParent())
427
107
                                     : 
Stmt->getSurroundingLoop()0
;
428
107
  if (AccVal &&
429
107
      
AccVal->getType() == MA->getLatestScopArrayInfo()->getElementType()101
&&
430
107
      
AccRel.is_single_valued().is_true()98
)
431
96
    return makeNormalizedValInst(AccVal, Stmt, L);
432
11
433
11
  // memset(_, '0', ) is equivalent to writing the null value to all touched
434
11
  // elements. isMustWrite() ensures that all of an element's bytes are
435
11
  // overwritten.
436
11
  if (auto *Memset = dyn_cast<MemSetInst>(AccInst)) {
437
6
    auto *WrittenConstant = dyn_cast<Constant>(Memset->getValue());
438
6
    Type *Ty = MA->getLatestScopArrayInfo()->getElementType();
439
6
    if (WrittenConstant && WrittenConstant->isZeroValue()) {
440
6
      Constant *Zero = Constant::getNullValue(Ty);
441
6
      return makeNormalizedValInst(Zero, Stmt, L);
442
6
    }
443
5
  }
444
5
445
5
  return {};
446
5
}
447
448
116
void ZoneAlgorithm::addArrayWriteAccess(MemoryAccess *MA) {
449
116
  assert(MA->isLatestArrayKind());
450
116
  assert(MA->isWrite());
451
116
  auto *Stmt = MA->getStatement();
452
116
453
116
  // { Domain[] -> Element[] }
454
116
  isl::map AccRel = intersectRange(getAccessRelationFor(MA), CompatibleElts);
455
116
456
116
  if (MA->isMustWrite())
457
107
    AllMustWrites = AllMustWrites.add_map(AccRel);
458
116
459
116
  if (MA->isMayWrite())
460
9
    AllMayWrites = AllMayWrites.add_map(AccRel);
461
116
462
116
  // { Domain[] -> ValInst[] }
463
116
  isl::union_map WriteValInstance = getWrittenValue(MA, AccRel);
464
116
  if (!WriteValInstance)
465
14
    WriteValInstance = makeUnknownForDomain(Stmt);
466
116
467
116
  // { Domain[] -> [Element[] -> Domain[]] }
468
116
  isl::map IncludeElement = AccRel.domain_map().curry();
469
116
470
116
  // { [Element[] -> DomainWrite[]] -> ValInst[] }
471
116
  isl::union_map EltWriteValInst =
472
116
      WriteValInstance.apply_domain(IncludeElement);
473
116
474
116
  AllWriteValInst = AllWriteValInst.unite(EltWriteValInst);
475
116
}
476
477
/// Return whether @p PHI refers (also transitively through other PHIs) to
478
/// itself.
479
///
480
/// loop:
481
///   %phi1 = phi [0, %preheader], [%phi1, %loop]
482
///   br i1 %c, label %loop, label %exit
483
///
484
/// exit:
485
///   %phi2 = phi [%phi1, %bb]
486
///
487
/// In this example, %phi1 is recursive, but %phi2 is not.
488
6
static bool isRecursivePHI(const PHINode *PHI) {
489
6
  SmallVector<const PHINode *, 8> Worklist;
490
6
  SmallPtrSet<const PHINode *, 8> Visited;
491
6
  Worklist.push_back(PHI);
492
6
493
12
  while (!Worklist.empty()) {
494
7
    const PHINode *Cur = Worklist.pop_back_val();
495
7
496
7
    if (Visited.count(Cur))
497
0
      continue;
498
7
    Visited.insert(Cur);
499
7
500
13
    for (const Use &Incoming : Cur->incoming_values()) {
501
13
      Value *IncomingVal = Incoming.get();
502
13
      auto *IncomingPHI = dyn_cast<PHINode>(IncomingVal);
503
13
      if (!IncomingPHI)
504
11
        continue;
505
2
506
2
      if (IncomingPHI == PHI)
507
1
        return true;
508
1
      Worklist.push_back(IncomingPHI);
509
1
    }
510
7
  }
511
6
  
return false5
;
512
6
}
513
514
39
isl::union_map ZoneAlgorithm::computePerPHI(const ScopArrayInfo *SAI) {
515
39
  // TODO: If the PHI has an incoming block from before the SCoP, it is not
516
39
  // represented in any ScopStmt.
517
39
518
39
  auto *PHI = cast<PHINode>(SAI->getBasePtr());
519
39
  auto It = PerPHIMaps.find(PHI);
520
39
  if (It != PerPHIMaps.end())
521
0
    return It->second;
522
39
523
39
  assert(SAI->isPHIKind());
524
39
525
39
  // { DomainPHIWrite[] -> Scatter[] }
526
39
  isl::union_map PHIWriteScatter = makeEmptyUnionMap();
527
39
528
39
  // Collect all incoming block timepoints.
529
77
  for (MemoryAccess *MA : S->getPHIIncomings(SAI)) {
530
77
    isl::map Scatter = getScatterFor(MA);
531
77
    PHIWriteScatter = PHIWriteScatter.add_map(Scatter);
532
77
  }
533
39
534
39
  // { DomainPHIRead[] -> Scatter[] }
535
39
  isl::map PHIReadScatter = getScatterFor(S->getPHIRead(SAI));
536
39
537
39
  // { DomainPHIRead[] -> Scatter[] }
538
39
  isl::map BeforeRead = beforeScatter(PHIReadScatter, true);
539
39
540
39
  // { Scatter[] }
541
39
  isl::set WriteTimes = singleton(PHIWriteScatter.range(), ScatterSpace);
542
39
543
39
  // { DomainPHIRead[] -> Scatter[] }
544
39
  isl::map PHIWriteTimes = BeforeRead.intersect_range(WriteTimes);
545
39
  isl::map LastPerPHIWrites = PHIWriteTimes.lexmax();
546
39
547
39
  // { DomainPHIRead[] -> DomainPHIWrite[] }
548
39
  isl::union_map Result =
549
39
      isl::union_map(LastPerPHIWrites).apply_range(PHIWriteScatter.reverse());
550
39
  assert(!Result.is_single_valued().is_false());
551
39
  assert(!Result.is_injective().is_false());
552
39
553
39
  PerPHIMaps.insert({PHI, Result});
554
39
  return Result;
555
39
}
556
557
224
isl::union_set ZoneAlgorithm::makeEmptyUnionSet() const {
558
224
  return give(isl_union_set_empty(ParamSpace.copy()));
559
224
}
560
561
1.30k
isl::union_map ZoneAlgorithm::makeEmptyUnionMap() const {
562
1.30k
  return give(isl_union_map_empty(ParamSpace.copy()));
563
1.30k
}
564
565
84
void ZoneAlgorithm::collectCompatibleElts() {
566
84
  // First find all the incompatible elements, then take the complement.
567
84
  // We compile the list of compatible (rather than incompatible) elements so
568
84
  // users can intersect with the list, not requiring a subtract operation. It
569
84
  // also allows us to define a 'universe' of all elements and makes it more
570
84
  // explicit in which array elements can be used.
571
84
  isl::union_set AllElts = makeEmptyUnionSet();
572
84
  isl::union_set IncompatibleElts = makeEmptyUnionSet();
573
84
574
84
  for (auto &Stmt : *S)
575
320
    collectIncompatibleElts(&Stmt, IncompatibleElts, AllElts);
576
84
577
84
  NumIncompatibleArrays += isl_union_set_n_set(IncompatibleElts.keep());
578
84
  CompatibleElts = AllElts.subtract(IncompatibleElts);
579
84
  NumCompatibleArrays += isl_union_set_n_set(CompatibleElts.keep());
580
84
}
581
582
280
isl::map ZoneAlgorithm::getScatterFor(ScopStmt *Stmt) const {
583
280
  isl::space ResultSpace = give(isl_space_map_from_domain_and_range(
584
280
      Stmt->getDomainSpace().release(), ScatterSpace.copy()));
585
280
  return give(isl_union_map_extract_map(Schedule.keep(), ResultSpace.take()));
586
280
}
587
588
208
isl::map ZoneAlgorithm::getScatterFor(MemoryAccess *MA) const {
589
208
  return getScatterFor(MA->getStatement());
590
208
}
591
592
307
isl::union_map ZoneAlgorithm::getScatterFor(isl::union_set Domain) const {
593
307
  return give(isl_union_map_intersect_domain(Schedule.copy(), Domain.take()));
594
307
}
595
596
186
isl::map ZoneAlgorithm::getScatterFor(isl::set Domain) const {
597
186
  auto ResultSpace = give(isl_space_map_from_domain_and_range(
598
186
      isl_set_get_space(Domain.keep()), ScatterSpace.copy()));
599
186
  auto UDomain = give(isl_union_set_from_set(Domain.copy()));
600
186
  auto UResult = getScatterFor(std::move(UDomain));
601
186
  auto Result = singleton(std::move(UResult), std::move(ResultSpace));
602
186
  assert(!Result || isl_set_is_equal(give(isl_map_domain(Result.copy())).keep(),
603
186
                                     Domain.keep()) == isl_bool_true);
604
186
  return Result;
605
186
}
606
607
1.54k
isl::set ZoneAlgorithm::getDomainFor(ScopStmt *Stmt) const {
608
1.54k
  return Stmt->getDomain().remove_redundancies();
609
1.54k
}
610
611
848
isl::set ZoneAlgorithm::getDomainFor(MemoryAccess *MA) const {
612
848
  return getDomainFor(MA->getStatement());
613
848
}
614
615
418
isl::map ZoneAlgorithm::getAccessRelationFor(MemoryAccess *MA) const {
616
418
  auto Domain = getDomainFor(MA);
617
418
  auto AccRel = MA->getLatestAccessRelation();
618
418
  return give(isl_map_intersect_domain(AccRel.take(), Domain.take()));
619
418
}
620
621
258
isl::map ZoneAlgorithm::getScalarReachingDefinition(ScopStmt *Stmt) {
622
258
  auto &Result = ScalarReachDefZone[Stmt];
623
258
  if (Result)
624
160
    return Result;
625
98
626
98
  auto Domain = getDomainFor(Stmt);
627
98
  Result = computeScalarReachingDefinition(Schedule, Domain, false, true);
628
98
  simplify(Result);
629
98
630
98
  return Result;
631
98
}
632
633
130
isl::map ZoneAlgorithm::getScalarReachingDefinition(isl::set DomainDef) {
634
130
  auto DomId = give(isl_set_get_tuple_id(DomainDef.keep()));
635
130
  auto *Stmt = static_cast<ScopStmt *>(isl_id_get_user(DomId.keep()));
636
130
637
130
  auto StmtResult = getScalarReachingDefinition(Stmt);
638
130
639
130
  return give(isl_map_intersect_range(StmtResult.take(), DomainDef.take()));
640
130
}
641
642
16
isl::map ZoneAlgorithm::makeUnknownForDomain(ScopStmt *Stmt) const {
643
16
  return ::makeUnknownForDomain(getDomainFor(Stmt));
644
16
}
645
646
341
isl::id ZoneAlgorithm::makeValueId(Value *V) {
647
341
  if (!V)
648
0
    return nullptr;
649
341
650
341
  auto &Id = ValueIds[V];
651
341
  if (Id.is_null()) {
652
178
    auto Name = getIslCompatibleName("Val_", V, ValueIds.size() - 1,
653
178
                                     std::string(), UseInstructionNames);
654
178
    Id = give(isl_id_alloc(IslCtx.get(), Name.c_str(), V));
655
178
  }
656
341
  return Id;
657
341
}
658
659
341
isl::space ZoneAlgorithm::makeValueSpace(Value *V) {
660
341
  auto Result = give(isl_space_set_from_params(ParamSpace.copy()));
661
341
  return give(isl_space_set_tuple_id(Result.take(), isl_dim_set,
662
341
                                     makeValueId(V).take()));
663
341
}
664
665
341
isl::set ZoneAlgorithm::makeValueSet(Value *V) {
666
341
  auto Space = makeValueSpace(V);
667
341
  return give(isl_set_universe(Space.take()));
668
341
}
669
670
isl::map ZoneAlgorithm::makeValInst(Value *Val, ScopStmt *UserStmt, Loop *Scope,
671
346
                                    bool IsCertain) {
672
346
  // If the definition/write is conditional, the value at the location could
673
346
  // be either the written value or the old value. Since we cannot know which
674
346
  // one, consider the value to be unknown.
675
346
  if (!IsCertain)
676
2
    return makeUnknownForDomain(UserStmt);
677
344
678
344
  auto DomainUse = getDomainFor(UserStmt);
679
344
  auto VUse = VirtualUse::create(S, UserStmt, Scope, Val, true);
680
344
  switch (VUse.getKind()) {
681
344
  case VirtualUse::Constant:
682
44
  case VirtualUse::Block:
683
44
  case VirtualUse::Hoisted:
684
44
  case VirtualUse::ReadOnly: {
685
44
    // The definition does not depend on the statement which uses it.
686
44
    auto ValSet = makeValueSet(Val);
687
44
    return give(isl_map_from_domain_and_range(DomainUse.take(), ValSet.take()));
688
44
  }
689
44
690
44
  case VirtualUse::Synthesizable: {
691
2
    auto *ScevExpr = VUse.getScevExpr();
692
2
    auto UseDomainSpace = give(isl_set_get_space(DomainUse.keep()));
693
2
694
2
    // Construct the SCEV space.
695
2
    // TODO: Add only the induction variables referenced in SCEVAddRecExpr
696
2
    // expressions, not just all of them.
697
2
    auto ScevId = give(isl_id_alloc(UseDomainSpace.get_ctx().get(), nullptr,
698
2
                                    const_cast<SCEV *>(ScevExpr)));
699
2
    auto ScevSpace =
700
2
        give(isl_space_drop_dims(UseDomainSpace.copy(), isl_dim_set, 0, 0));
701
2
    ScevSpace = give(
702
2
        isl_space_set_tuple_id(ScevSpace.take(), isl_dim_set, ScevId.copy()));
703
2
704
2
    // { DomainUse[] -> ScevExpr[] }
705
2
    auto ValInst = give(isl_map_identity(isl_space_map_from_domain_and_range(
706
2
        UseDomainSpace.copy(), ScevSpace.copy())));
707
2
    return ValInst;
708
44
  }
709
44
710
167
  case VirtualUse::Intra: {
711
167
    // Definition and use is in the same statement. We do not need to compute
712
167
    // a reaching definition.
713
167
714
167
    // { llvm::Value }
715
167
    auto ValSet = makeValueSet(Val);
716
167
717
167
    // {  UserDomain[] -> llvm::Value }
718
167
    auto ValInstSet =
719
167
        give(isl_map_from_domain_and_range(DomainUse.take(), ValSet.take()));
720
167
721
167
    // { UserDomain[] -> [UserDomain[] - >llvm::Value] }
722
167
    auto Result = give(isl_map_reverse(isl_map_domain_map(ValInstSet.take())));
723
167
    simplify(Result);
724
167
    return Result;
725
44
  }
726
44
727
131
  case VirtualUse::Inter: {
728
131
    // The value is defined in a different statement.
729
131
730
131
    auto *Inst = cast<Instruction>(Val);
731
131
    auto *ValStmt = S->getStmtFor(Inst);
732
131
733
131
    // If the llvm::Value is defined in a removed Stmt, we cannot derive its
734
131
    // domain. We could use an arbitrary statement, but this could result in
735
131
    // different ValInst[] for the same llvm::Value.
736
131
    if (!ValStmt)
737
1
      return ::makeUnknownForDomain(DomainUse);
738
130
739
130
    // { DomainDef[] }
740
130
    auto DomainDef = getDomainFor(ValStmt);
741
130
742
130
    // { Scatter[] -> DomainDef[] }
743
130
    auto ReachDef = getScalarReachingDefinition(DomainDef);
744
130
745
130
    // { DomainUse[] -> Scatter[] }
746
130
    auto UserSched = getScatterFor(DomainUse);
747
130
748
130
    // { DomainUse[] -> DomainDef[] }
749
130
    auto UsedInstance =
750
130
        give(isl_map_apply_range(UserSched.take(), ReachDef.take()));
751
130
752
130
    // { llvm::Value }
753
130
    auto ValSet = makeValueSet(Val);
754
130
755
130
    // { DomainUse[] -> llvm::Value[] }
756
130
    auto ValInstSet =
757
130
        give(isl_map_from_domain_and_range(DomainUse.take(), ValSet.take()));
758
130
759
130
    // { DomainUse[] -> [DomainDef[] -> llvm::Value]  }
760
130
    auto Result =
761
130
        give(isl_map_range_product(UsedInstance.take(), ValInstSet.take()));
762
130
763
130
    simplify(Result);
764
130
    return Result;
765
130
  }
766
0
  }
767
0
  llvm_unreachable("Unhandled use type");
768
0
}
769
770
/// Remove all computed PHIs out of @p Input and replace by their incoming
771
/// value.
772
///
773
/// @param Input        { [] -> ValInst[] }
774
/// @param ComputedPHIs Set of PHIs that are replaced. Its ValInst must appear
775
///                     on the LHS of @p NormalizeMap.
776
/// @param NormalizeMap { ValInst[] -> ValInst[] }
777
static isl::union_map normalizeValInst(isl::union_map Input,
778
                                       const DenseSet<PHINode *> &ComputedPHIs,
779
136
                                       isl::union_map NormalizeMap) {
780
136
  isl::union_map Result = isl::union_map::empty(Input.get_space());
781
136
  Input.foreach_map(
782
139
      [&Result, &ComputedPHIs, &NormalizeMap](isl::map Map) -> isl::stat {
783
139
        isl::space Space = Map.get_space();
784
139
        isl::space RangeSpace = Space.range();
785
139
786
139
        // Instructions within the SCoP are always wrapped. Non-wrapped tuples
787
139
        // are therefore invariant in the SCoP and don't need normalization.
788
139
        if (!RangeSpace.is_wrapping()) {
789
23
          Result = Result.add_map(Map);
790
23
          return isl::stat::ok;
791
23
        }
792
116
793
116
        auto *PHI = dyn_cast<PHINode>(static_cast<Value *>(
794
116
            RangeSpace.unwrap().get_tuple_id(isl::dim::out).get_user()));
795
116
796
116
        // If no normalization is necessary, then the ValInst stands for itself.
797
116
        if (!ComputedPHIs.count(PHI)) {
798
102
          Result = Result.add_map(Map);
799
102
          return isl::stat::ok;
800
102
        }
801
14
802
14
        // Otherwise, apply the normalization.
803
14
        isl::union_map Mapped = isl::union_map(Map).apply_range(NormalizeMap);
804
14
        Result = Result.unite(Mapped);
805
14
        NumPHINormialization++;
806
14
        return isl::stat::ok;
807
14
      });
808
136
  return Result;
809
136
}
810
811
isl::union_map ZoneAlgorithm::makeNormalizedValInst(llvm::Value *Val,
812
                                                    ScopStmt *UserStmt,
813
                                                    llvm::Loop *Scope,
814
126
                                                    bool IsCertain) {
815
126
  isl::map ValInst = makeValInst(Val, UserStmt, Scope, IsCertain);
816
126
  isl::union_map Normalized =
817
126
      normalizeValInst(ValInst, ComputedPHIs, NormalizeMap);
818
126
  return Normalized;
819
126
}
820
821
0
bool ZoneAlgorithm::isCompatibleAccess(MemoryAccess *MA) {
822
0
  if (!MA)
823
0
    return false;
824
0
  if (!MA->isLatestArrayKind())
825
0
    return false;
826
0
  Instruction *AccInst = MA->getAccessInstruction();
827
0
  return isa<StoreInst>(AccInst) || isa<LoadInst>(AccInst);
828
0
}
829
830
6
bool ZoneAlgorithm::isNormalizable(MemoryAccess *MA) {
831
6
  assert(MA->isRead());
832
6
833
6
  // Exclude ExitPHIs, we are assuming that a normalizable PHI has a READ
834
6
  // MemoryAccess.
835
6
  if (!MA->isOriginalPHIKind())
836
0
    return false;
837
6
838
6
  // Exclude recursive PHIs, normalizing them would require a transitive
839
6
  // closure.
840
6
  auto *PHI = cast<PHINode>(MA->getAccessInstruction());
841
6
  if (RecursivePHIs.count(PHI))
842
1
    return false;
843
5
844
5
  // Ensure that each incoming value can be represented by a ValInst[].
845
5
  // We do represent values from statements associated to multiple incoming
846
5
  // value by the PHI itself, but we do not handle this case yet (especially
847
5
  // isNormalized()) when normalizing.
848
5
  const ScopArrayInfo *SAI = MA->getOriginalScopArrayInfo();
849
5
  auto Incomings = S->getPHIIncomings(SAI);
850
9
  for (MemoryAccess *Incoming : Incomings) {
851
9
    if (Incoming->getIncoming().size() != 1)
852
0
      return false;
853
9
  }
854
5
855
5
  return true;
856
5
}
857
858
0
bool ZoneAlgorithm::isNormalized(isl::map Map) {
859
0
  isl::space Space = Map.get_space();
860
0
  isl::space RangeSpace = Space.range();
861
0
862
0
  if (!RangeSpace.is_wrapping())
863
0
    return true;
864
0
865
0
  auto *PHI = dyn_cast<PHINode>(static_cast<Value *>(
866
0
      RangeSpace.unwrap().get_tuple_id(isl::dim::out).get_user()));
867
0
  if (!PHI)
868
0
    return true;
869
0
870
0
  auto *IncomingStmt = static_cast<ScopStmt *>(
871
0
      RangeSpace.unwrap().get_tuple_id(isl::dim::in).get_user());
872
0
  MemoryAccess *PHIRead = IncomingStmt->lookupPHIReadOf(PHI);
873
0
  if (!isNormalizable(PHIRead))
874
0
    return true;
875
0
876
0
  return false;
877
0
}
878
879
0
bool ZoneAlgorithm::isNormalized(isl::union_map UMap) {
880
0
  auto Result = UMap.foreach_map([this](isl::map Map) -> isl::stat {
881
0
    if (isNormalized(Map))
882
0
      return isl::stat::ok;
883
0
    return isl::stat::error;
884
0
  });
885
0
  return Result == isl::stat::ok;
886
0
}
887
888
84
void ZoneAlgorithm::computeCommon() {
889
84
  AllReads = makeEmptyUnionMap();
890
84
  AllMayWrites = makeEmptyUnionMap();
891
84
  AllMustWrites = makeEmptyUnionMap();
892
84
  AllWriteValInst = makeEmptyUnionMap();
893
84
  AllReadValInst = makeEmptyUnionMap();
894
84
895
84
  // Default to empty, i.e. no normalization/replacement is taking place. Call
896
84
  // computeNormalizedPHIs() to initialize.
897
84
  NormalizeMap = makeEmptyUnionMap();
898
84
  ComputedPHIs.clear();
899
84
900
320
  for (auto &Stmt : *S) {
901
633
    for (auto *MA : Stmt) {
902
633
      if (!MA->isLatestArrayKind())
903
472
        continue;
904
161
905
161
      if (MA->isRead())
906
45
        addArrayReadAccess(MA);
907
161
908
161
      if (MA->isWrite())
909
116
        addArrayWriteAccess(MA);
910
161
    }
911
320
  }
912
84
913
84
  // { DomainWrite[] -> Element[] }
914
84
  AllWrites =
915
84
      give(isl_union_map_union(AllMustWrites.copy(), AllMayWrites.copy()));
916
84
917
84
  // { [Element[] -> Zone[]] -> DomainWrite[] }
918
84
  WriteReachDefZone =
919
84
      computeReachingDefinition(Schedule, AllWrites, false, true);
920
84
  simplify(WriteReachDefZone);
921
84
}
922
923
4
void ZoneAlgorithm::computeNormalizedPHIs() {
924
4
  // Determine which PHIs can reference themselves. They are excluded from
925
4
  // normalization to avoid problems with transitive closures.
926
13
  for (ScopStmt &Stmt : *S) {
927
38
    for (MemoryAccess *MA : Stmt) {
928
38
      if (!MA->isPHIKind())
929
21
        continue;
930
17
      if (!MA->isRead())
931
11
        continue;
932
6
933
6
      // TODO: Can be more efficient since isRecursivePHI can theoretically
934
6
      // determine recursiveness for multiple values and/or cache results.
935
6
      auto *PHI = cast<PHINode>(MA->getAccessInstruction());
936
6
      if (isRecursivePHI(PHI)) {
937
1
        NumRecursivePHIs++;
938
1
        RecursivePHIs.insert(PHI);
939
1
      }
940
6
    }
941
13
  }
942
4
943
4
  // { PHIValInst[] -> IncomingValInst[] }
944
4
  isl::union_map AllPHIMaps = makeEmptyUnionMap();
945
4
946
4
  // Discover new PHIs and try to normalize them.
947
4
  DenseSet<PHINode *> AllPHIs;
948
13
  for (ScopStmt &Stmt : *S) {
949
38
    for (MemoryAccess *MA : Stmt) {
950
38
      if (!MA->isOriginalPHIKind())
951
21
        continue;
952
17
      if (!MA->isRead())
953
11
        continue;
954
6
      if (!isNormalizable(MA))
955
1
        continue;
956
5
957
5
      auto *PHI = cast<PHINode>(MA->getAccessInstruction());
958
5
      const ScopArrayInfo *SAI = MA->getOriginalScopArrayInfo();
959
5
960
5
      // { PHIDomain[] -> PHIValInst[] }
961
5
      isl::map PHIValInst = makeValInst(PHI, &Stmt, Stmt.getSurroundingLoop());
962
5
963
5
      // { IncomingDomain[] -> IncomingValInst[] }
964
5
      isl::union_map IncomingValInsts = makeEmptyUnionMap();
965
5
966
5
      // Get all incoming values.
967
9
      for (MemoryAccess *MA : S->getPHIIncomings(SAI)) {
968
9
        ScopStmt *IncomingStmt = MA->getStatement();
969
9
970
9
        auto Incoming = MA->getIncoming();
971
9
        assert(Incoming.size() == 1 && "The incoming value must be "
972
9
                                       "representable by something else than "
973
9
                                       "the PHI itself");
974
9
        Value *IncomingVal = Incoming[0].second;
975
9
976
9
        // { IncomingDomain[] -> IncomingValInst[] }
977
9
        isl::map IncomingValInst = makeValInst(
978
9
            IncomingVal, IncomingStmt, IncomingStmt->getSurroundingLoop());
979
9
980
9
        IncomingValInsts = IncomingValInsts.add_map(IncomingValInst);
981
9
      }
982
5
983
5
      // Determine which instance of the PHI statement corresponds to which
984
5
      // incoming value.
985
5
      // { PHIDomain[] -> IncomingDomain[] }
986
5
      isl::union_map PerPHI = computePerPHI(SAI);
987
5
988
5
      // { PHIValInst[] -> IncomingValInst[] }
989
5
      isl::union_map PHIMap =
990
5
          PerPHI.apply_domain(PHIValInst).apply_range(IncomingValInsts);
991
5
      assert(!PHIMap.is_single_valued().is_false());
992
5
993
5
      // Resolve transitiveness: The incoming value of the newly discovered PHI
994
5
      // may reference a previously normalized PHI. At the same time, already
995
5
      // normalized PHIs might be normalized to the new PHI. At the end, none of
996
5
      // the PHIs may appear on the right-hand-side of the normalization map.
997
5
      PHIMap = normalizeValInst(PHIMap, AllPHIs, AllPHIMaps);
998
5
      AllPHIs.insert(PHI);
999
5
      AllPHIMaps = normalizeValInst(AllPHIMaps, AllPHIs, PHIMap);
1000
5
1001
5
      AllPHIMaps = AllPHIMaps.unite(PHIMap);
1002
5
      NumNormalizablePHIs++;
1003
5
    }
1004
13
  }
1005
4
  simplify(AllPHIMaps);
1006
4
1007
4
  // Apply the normalization.
1008
4
  ComputedPHIs = AllPHIs;
1009
4
  NormalizeMap = AllPHIMaps;
1010
4
1011
4
  assert(!NormalizeMap || isNormalized(NormalizeMap));
1012
4
}
1013
1014
28
void ZoneAlgorithm::printAccesses(llvm::raw_ostream &OS, int Indent) const {
1015
28
  OS.indent(Indent) << "After accesses {\n";
1016
139
  for (auto &Stmt : *S) {
1017
139
    OS.indent(Indent + 4) << Stmt.getBaseName() << "\n";
1018
139
    for (auto *MA : Stmt)
1019
278
      MA->print(OS);
1020
139
  }
1021
28
  OS.indent(Indent) << "}\n";
1022
28
}
1023
1024
84
isl::union_map ZoneAlgorithm::computeKnownFromMustWrites() const {
1025
84
  // { [Element[] -> Zone[]] -> [Element[] -> DomainWrite[]] }
1026
84
  isl::union_map EltReachdDef = distributeDomain(WriteReachDefZone.curry());
1027
84
1028
84
  // { [Element[] -> DomainWrite[]] -> ValInst[] }
1029
84
  isl::union_map AllKnownWriteValInst = filterKnownValInst(AllWriteValInst);
1030
84
1031
84
  // { [Element[] -> Zone[]] -> ValInst[] }
1032
84
  return EltReachdDef.apply_range(AllKnownWriteValInst);
1033
84
}
1034
1035
34
isl::union_map ZoneAlgorithm::computeKnownFromLoad() const {
1036
34
  // { Element[] }
1037
34
  isl::union_set AllAccessedElts = AllReads.range().unite(AllWrites.range());
1038
34
1039
34
  // { Element[] -> Scatter[] }
1040
34
  isl::union_map EltZoneUniverse = isl::union_map::from_domain_and_range(
1041
34
      AllAccessedElts, isl::set::universe(ScatterSpace));
1042
34
1043
34
  // This assumes there are no "holes" in
1044
34
  // isl_union_map_domain(WriteReachDefZone); alternatively, compute the zone
1045
34
  // before the first write or that are not written at all.
1046
34
  // { Element[] -> Scatter[] }
1047
34
  isl::union_set NonReachDef =
1048
34
      EltZoneUniverse.wrap().subtract(WriteReachDefZone.domain());
1049
34
1050
34
  // { [Element[] -> Zone[]] -> ReachDefId[] }
1051
34
  isl::union_map DefZone =
1052
34
      WriteReachDefZone.unite(isl::union_map::from_domain(NonReachDef));
1053
34
1054
34
  // { [Element[] -> Scatter[]] -> Element[] }
1055
34
  isl::union_map EltZoneElt = EltZoneUniverse.domain_map();
1056
34
1057
34
  // { [Element[] -> Zone[]] -> [Element[] -> ReachDefId[]] }
1058
34
  isl::union_map DefZoneEltDefId = EltZoneElt.range_product(DefZone);
1059
34
1060
34
  // { Element[] -> [Zone[] -> ReachDefId[]] }
1061
34
  isl::union_map EltDefZone = DefZone.curry();
1062
34
1063
34
  // { [Element[] -> Zone[] -> [Element[] -> ReachDefId[]] }
1064
34
  isl::union_map EltZoneEltDefid = distributeDomain(EltDefZone);
1065
34
1066
34
  // { [Element[] -> Scatter[]] -> DomainRead[] }
1067
34
  isl::union_map Reads = AllReads.range_product(Schedule).reverse();
1068
34
1069
34
  // { [Element[] -> Scatter[]] -> [Element[] -> DomainRead[]] }
1070
34
  isl::union_map ReadsElt = EltZoneElt.range_product(Reads);
1071
34
1072
34
  // { [Element[] -> Scatter[]] -> ValInst[] }
1073
34
  isl::union_map ScatterKnown = ReadsElt.apply_range(AllReadValInst);
1074
34
1075
34
  // { [Element[] -> ReachDefId[]] -> ValInst[] }
1076
34
  isl::union_map DefidKnown =
1077
34
      DefZoneEltDefId.apply_domain(ScatterKnown).reverse();
1078
34
1079
34
  // { [Element[] -> Zone[]] -> ValInst[] }
1080
34
  return DefZoneEltDefId.apply_range(DefidKnown);
1081
34
}
1082
1083
isl::union_map ZoneAlgorithm::computeKnown(bool FromWrite,
1084
84
                                           bool FromRead) const {
1085
84
  isl::union_map Result = makeEmptyUnionMap();
1086
84
1087
84
  if (FromWrite)
1088
84
    Result = Result.unite(computeKnownFromMustWrites());
1089
84
1090
84
  if (FromRead)
1091
34
    Result = Result.unite(computeKnownFromLoad());
1092
84
1093
84
  simplify(Result);
1094
84
  return Result;
1095
84
}