Coverage Report

Created: 2018-06-24 14:39

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/polly/lib/Transform/DeLICM.cpp
Line
Count
Source (jump to first uncovered line)
1
//===------ DeLICM.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
// Undo the effect of Loop Invariant Code Motion (LICM) and
11
// GVN Partial Redundancy Elimination (PRE) on SCoP-level.
12
//
13
// Namely, remove register/scalar dependencies by mapping them back to array
14
// elements.
15
//
16
//===----------------------------------------------------------------------===//
17
18
#include "polly/DeLICM.h"
19
#include "polly/Options.h"
20
#include "polly/ScopInfo.h"
21
#include "polly/ScopPass.h"
22
#include "polly/Support/ISLOStream.h"
23
#include "polly/Support/ISLTools.h"
24
#include "polly/ZoneAlgo.h"
25
#include "llvm/ADT/Statistic.h"
26
30
#define DEBUG_TYPE "polly-delicm"
27
28
using namespace polly;
29
using namespace llvm;
30
31
namespace {
32
33
cl::opt<int>
34
    DelicmMaxOps("polly-delicm-max-ops",
35
                 cl::desc("Maximum number of isl operations to invest for "
36
                          "lifetime analysis; 0=no limit"),
37
                 cl::init(1000000), cl::cat(PollyCategory));
38
39
cl::opt<bool> DelicmOverapproximateWrites(
40
    "polly-delicm-overapproximate-writes",
41
    cl::desc(
42
        "Do more PHI writes than necessary in order to avoid partial accesses"),
43
    cl::init(false), cl::Hidden, cl::cat(PollyCategory));
44
45
cl::opt<bool> DelicmPartialWrites("polly-delicm-partial-writes",
46
                                  cl::desc("Allow partial writes"),
47
                                  cl::init(true), cl::Hidden,
48
                                  cl::cat(PollyCategory));
49
50
cl::opt<bool>
51
    DelicmComputeKnown("polly-delicm-compute-known",
52
                       cl::desc("Compute known content of array elements"),
53
                       cl::init(true), cl::Hidden, cl::cat(PollyCategory));
54
55
STATISTIC(DeLICMAnalyzed, "Number of successfully analyzed SCoPs");
56
STATISTIC(DeLICMOutOfQuota,
57
          "Analyses aborted because max_operations was reached");
58
STATISTIC(MappedValueScalars, "Number of mapped Value scalars");
59
STATISTIC(MappedPHIScalars, "Number of mapped PHI scalars");
60
STATISTIC(TargetsMapped, "Number of stores used for at least one mapping");
61
STATISTIC(DeLICMScopsModified, "Number of SCoPs optimized");
62
63
STATISTIC(NumValueWrites, "Number of scalar value writes after DeLICM");
64
STATISTIC(NumValueWritesInLoops,
65
          "Number of scalar value writes nested in affine loops after DeLICM");
66
STATISTIC(NumPHIWrites, "Number of scalar phi writes after DeLICM");
67
STATISTIC(NumPHIWritesInLoops,
68
          "Number of scalar phi writes nested in affine loops after DeLICM");
69
STATISTIC(NumSingletonWrites, "Number of singleton writes after DeLICM");
70
STATISTIC(NumSingletonWritesInLoops,
71
          "Number of singleton writes nested in affine loops after DeLICM");
72
73
isl::union_map computeReachingOverwrite(isl::union_map Schedule,
74
                                        isl::union_map Writes,
75
                                        bool InclPrevWrite,
76
40
                                        bool InclOverwrite) {
77
40
  return computeReachingWrite(Schedule, Writes, true, InclPrevWrite,
78
40
                              InclOverwrite);
79
40
}
80
81
/// Compute the next overwrite for a scalar.
82
///
83
/// @param Schedule      { DomainWrite[] -> Scatter[] }
84
///                      Schedule of (at least) all writes. Instances not in @p
85
///                      Writes are ignored.
86
/// @param Writes        { DomainWrite[] }
87
///                      The element instances that write to the scalar.
88
/// @param InclPrevWrite Whether to extend the timepoints to include
89
///                      the timepoint where the previous write happens.
90
/// @param InclOverwrite Whether the reaching overwrite includes the timepoint
91
///                      of the overwrite itself.
92
///
93
/// @return { Scatter[] -> DomainDef[] }
94
isl::union_map computeScalarReachingOverwrite(isl::union_map Schedule,
95
                                              isl::union_set Writes,
96
                                              bool InclPrevWrite,
97
40
                                              bool InclOverwrite) {
98
40
99
40
  // { DomainWrite[] }
100
40
  auto WritesMap = isl::union_map::from_domain(Writes);
101
40
102
40
  // { [Element[] -> Scatter[]] -> DomainWrite[] }
103
40
  auto Result = computeReachingOverwrite(
104
40
      std::move(Schedule), std::move(WritesMap), InclPrevWrite, InclOverwrite);
105
40
106
40
  return Result.domain_factor_range();
107
40
}
108
109
/// Overload of computeScalarReachingOverwrite, with only one writing statement.
110
/// Consequently, the result consists of only one map space.
111
///
112
/// @param Schedule      { DomainWrite[] -> Scatter[] }
113
/// @param Writes        { DomainWrite[] }
114
/// @param InclPrevWrite Include the previous write to result.
115
/// @param InclOverwrite Include the overwrite to the result.
116
///
117
/// @return { Scatter[] -> DomainWrite[] }
118
isl::map computeScalarReachingOverwrite(isl::union_map Schedule,
119
                                        isl::set Writes, bool InclPrevWrite,
120
40
                                        bool InclOverwrite) {
121
40
  isl::space ScatterSpace = getScatterSpace(Schedule);
122
40
  isl::space DomSpace = Writes.get_space();
123
40
124
40
  isl::union_map ReachOverwrite = computeScalarReachingOverwrite(
125
40
      Schedule, isl::union_set(Writes), InclPrevWrite, InclOverwrite);
126
40
127
40
  isl::space ResultSpace = ScatterSpace.map_from_domain_and_range(DomSpace);
128
40
  return singleton(std::move(ReachOverwrite), ResultSpace);
129
40
}
130
131
/// Try to find a 'natural' extension of a mapped to elements outside its
132
/// domain.
133
///
134
/// @param Relevant The map with mapping that may not be modified.
135
/// @param Universe The domain to which @p Relevant needs to be extended.
136
///
137
/// @return A map with that associates the domain elements of @p Relevant to the
138
///         same elements and in addition the elements of @p Universe to some
139
///         undefined elements. The function prefers to return simple maps.
140
11
isl::union_map expandMapping(isl::union_map Relevant, isl::union_set Universe) {
141
11
  Relevant = Relevant.coalesce();
142
11
  isl::union_set RelevantDomain = Relevant.domain();
143
11
  isl::union_map Simplified = Relevant.gist_domain(RelevantDomain);
144
11
  Simplified = Simplified.coalesce();
145
11
  return Simplified.intersect_domain(Universe);
146
11
}
147
148
/// Represent the knowledge of the contents of any array elements in any zone or
149
/// the knowledge we would add when mapping a scalar to an array element.
150
///
151
/// Every array element at every zone unit has one of two states:
152
///
153
/// - Unused: Not occupied by any value so a transformation can change it to
154
///   other values.
155
///
156
/// - Occupied: The element contains a value that is still needed.
157
///
158
/// The union of Unused and Unknown zones forms the universe, the set of all
159
/// elements at every timepoint. The universe can easily be derived from the
160
/// array elements that are accessed someway. Arrays that are never accessed
161
/// also never play a role in any computation and can hence be ignored. With a
162
/// given universe, only one of the sets needs to stored implicitly. Computing
163
/// the complement is also an expensive operation, hence this class has been
164
/// designed that only one of sets is needed while the other is assumed to be
165
/// implicit. It can still be given, but is mostly ignored.
166
///
167
/// There are two use cases for the Knowledge class:
168
///
169
/// 1) To represent the knowledge of the current state of ScopInfo. The unused
170
///    state means that an element is currently unused: there is no read of it
171
///    before the next overwrite. Also called 'Existing'.
172
///
173
/// 2) To represent the requirements for mapping a scalar to array elements. The
174
///    unused state means that there is no change/requirement. Also called
175
///    'Proposed'.
176
///
177
/// In addition to these states at unit zones, Knowledge needs to know when
178
/// values are written. This is because written values may have no lifetime (one
179
/// reason is that the value is never read). Such writes would therefore never
180
/// conflict, but overwrite values that might still be required. Another source
181
/// of problems are multiple writes to the same element at the same timepoint,
182
/// because their order is undefined.
183
class Knowledge {
184
private:
185
  /// { [Element[] -> Zone[]] }
186
  /// Set of array elements and when they are alive.
187
  /// Can contain a nullptr; in this case the set is implicitly defined as the
188
  /// complement of #Unused.
189
  ///
190
  /// The set of alive array elements is represented as zone, as the set of live
191
  /// values can differ depending on how the elements are interpreted.
192
  /// Assuming a value X is written at timestep [0] and read at timestep [1]
193
  /// without being used at any later point, then the value is alive in the
194
  /// interval ]0,1[. This interval cannot be represented by an integer set, as
195
  /// it does not contain any integer point. Zones allow us to represent this
196
  /// interval and can be converted to sets of timepoints when needed (e.g., in
197
  /// isConflicting when comparing to the write sets).
198
  /// @see convertZoneToTimepoints and this file's comment for more details.
199
  isl::union_set Occupied;
200
201
  /// { [Element[] -> Zone[]] }
202
  /// Set of array elements when they are not alive, i.e. their memory can be
203
  /// used for other purposed. Can contain a nullptr; in this case the set is
204
  /// implicitly defined as the complement of #Occupied.
205
  isl::union_set Unused;
206
207
  /// { [Element[] -> Zone[]] -> ValInst[] }
208
  /// Maps to the known content for each array element at any interval.
209
  ///
210
  /// Any element/interval can map to multiple known elements. This is due to
211
  /// multiple llvm::Value referring to the same content. Examples are
212
  ///
213
  /// - A value stored and loaded again. The LoadInst represents the same value
214
  /// as the StoreInst's value operand.
215
  ///
216
  /// - A PHINode is equal to any one of the incoming values. In case of
217
  /// LCSSA-form, it is always equal to its single incoming value.
218
  ///
219
  /// Two Knowledges are considered not conflicting if at least one of the known
220
  /// values match. Not known values are not stored as an unnamed tuple (as
221
  /// #Written does), but maps to nothing.
222
  ///
223
  ///  Known values are usually just defined for #Occupied elements. Knowing
224
  ///  #Unused contents has no advantage as it can be overwritten.
225
  isl::union_map Known;
226
227
  /// { [Element[] -> Scatter[]] -> ValInst[] }
228
  /// The write actions currently in the scop or that would be added when
229
  /// mapping a scalar. Maps to the value that is written.
230
  ///
231
  /// Written values that cannot be identified are represented by an unknown
232
  /// ValInst[] (an unnamed tuple of 0 dimension). It conflicts with itself.
233
  isl::union_map Written;
234
235
  /// Check whether this Knowledge object is well-formed.
236
685
  void checkConsistency() const {
237
#ifndef NDEBUG
238
    // Default-initialized object
239
    if (!Occupied && !Unused && !Known && !Written)
240
      return;
241
242
    assert(Occupied || Unused);
243
    assert(Known);
244
    assert(Written);
245
246
    // If not all fields are defined, we cannot derived the universe.
247
    if (!Occupied || !Unused)
248
      return;
249
250
    assert(Occupied.is_disjoint(Unused));
251
    auto Universe = Occupied.unite(Unused);
252
253
    assert(!Known.domain().is_subset(Universe).is_false());
254
    assert(!Written.domain().is_subset(Universe).is_false());
255
#endif
256
  }
257
258
public:
259
  /// Initialize a nullptr-Knowledge. This is only provided for convenience; do
260
  /// not use such an object.
261
102
  Knowledge() {}
262
263
  /// Create a new object with the given members.
264
  Knowledge(isl::union_set Occupied, isl::union_set Unused,
265
            isl::union_map Known, isl::union_map Written)
266
      : Occupied(std::move(Occupied)), Unused(std::move(Unused)),
267
601
        Known(std::move(Known)), Written(std::move(Written)) {
268
601
    checkConsistency();
269
601
  }
270
271
  /// Return whether this object was not default-constructed.
272
47
  bool isUsable() const { return (Occupied || Unused) && 
Known44
&&
Written44
; }
273
274
  /// Print the content of this object to @p OS.
275
0
  void print(llvm::raw_ostream &OS, unsigned Indent = 0) const {
276
0
    if (isUsable()) {
277
0
      if (Occupied)
278
0
        OS.indent(Indent) << "Occupied: " << Occupied << "\n";
279
0
      else
280
0
        OS.indent(Indent) << "Occupied: <Everything else not in Unused>\n";
281
0
      if (Unused)
282
0
        OS.indent(Indent) << "Unused:   " << Unused << "\n";
283
0
      else
284
0
        OS.indent(Indent) << "Unused:   <Everything else not in Occupied>\n";
285
0
      OS.indent(Indent) << "Known:    " << Known << "\n";
286
0
      OS.indent(Indent) << "Written : " << Written << '\n';
287
0
    } else {
288
0
      OS.indent(Indent) << "Invalid knowledge\n";
289
0
    }
290
0
  }
291
292
  /// Combine two knowledges, this and @p That.
293
84
  void learnFrom(Knowledge That) {
294
84
    assert(!isConflicting(*this, That));
295
84
    assert(Unused && That.Occupied);
296
84
    assert(
297
84
        !That.Unused &&
298
84
        "This function is only prepared to learn occupied elements from That");
299
84
    assert(!Occupied && "This function does not implement "
300
84
                        "`this->Occupied = "
301
84
                        "this->Occupied.unite(That.Occupied);`");
302
84
303
84
    Unused = Unused.subtract(That.Occupied);
304
84
    Known = Known.unite(That.Known);
305
84
    Written = Written.unite(That.Written);
306
84
307
84
    checkConsistency();
308
84
  }
309
310
  /// Determine whether two Knowledges conflict with each other.
311
  ///
312
  /// In theory @p Existing and @p Proposed are symmetric, but the
313
  /// implementation is constrained by the implicit interpretation. That is, @p
314
  /// Existing must have #Unused defined (use case 1) and @p Proposed must have
315
  /// #Occupied defined (use case 1).
316
  ///
317
  /// A conflict is defined as non-preserved semantics when they are merged. For
318
  /// instance, when for the same array and zone they assume different
319
  /// llvm::Values.
320
  ///
321
  /// @param Existing One of the knowledges with #Unused defined.
322
  /// @param Proposed One of the knowledges with #Occupied defined.
323
  /// @param OS       Dump the conflict reason to this output stream; use
324
  ///                 nullptr to not output anything.
325
  /// @param Indent   Indention for the conflict reason.
326
  ///
327
  /// @return True, iff the two knowledges are conflicting.
328
  static bool isConflicting(const Knowledge &Existing,
329
                            const Knowledge &Proposed,
330
                            llvm::raw_ostream *OS = nullptr,
331
321
                            unsigned Indent = 0) {
332
321
    assert(Existing.Unused);
333
321
    assert(Proposed.Occupied);
334
321
335
#ifndef NDEBUG
336
    if (Existing.Occupied && Proposed.Unused) {
337
      auto ExistingUniverse = Existing.Occupied.unite(Existing.Unused);
338
      auto ProposedUniverse = Proposed.Occupied.unite(Proposed.Unused);
339
      assert(ExistingUniverse.is_equal(ProposedUniverse) &&
340
             "Both inputs' Knowledges must be over the same universe");
341
    }
342
#endif
343
344
321
    // Do the Existing and Proposed lifetimes conflict?
345
321
    //
346
321
    // Lifetimes are described as the cross-product of array elements and zone
347
321
    // intervals in which they are alive (the space { [Element[] -> Zone[]] }).
348
321
    // In the following we call this "element/lifetime interval".
349
321
    //
350
321
    // In order to not conflict, one of the following conditions must apply for
351
321
    // each element/lifetime interval:
352
321
    //
353
321
    // 1. If occupied in one of the knowledges, it is unused in the other.
354
321
    //
355
321
    //   - or -
356
321
    //
357
321
    // 2. Both contain the same value.
358
321
    //
359
321
    // Instead of partitioning the element/lifetime intervals into a part that
360
321
    // both Knowledges occupy (which requires an expensive subtraction) and for
361
321
    // these to check whether they are known to be the same value, we check only
362
321
    // the second condition and ensure that it also applies when then first
363
321
    // condition is true. This is done by adding a wildcard value to
364
321
    // Proposed.Known and Existing.Unused such that they match as a common known
365
321
    // value. We use the "unknown ValInst" for this purpose. Every
366
321
    // Existing.Unused may match with an unknown Proposed.Occupied because these
367
321
    // never are in conflict with each other.
368
321
    auto ProposedOccupiedAnyVal = makeUnknownForDomain(Proposed.Occupied);
369
321
    auto ProposedValues = Proposed.Known.unite(ProposedOccupiedAnyVal);
370
321
371
321
    auto ExistingUnusedAnyVal = makeUnknownForDomain(Existing.Unused);
372
321
    auto ExistingValues = Existing.Known.unite(ExistingUnusedAnyVal);
373
321
374
321
    auto MatchingVals = ExistingValues.intersect(ProposedValues);
375
321
    auto Matches = MatchingVals.domain();
376
321
377
321
    // Any Proposed.Occupied must either have a match between the known values
378
321
    // of Existing and Occupied, or be in Existing.Unused. In the latter case,
379
321
    // the previously added "AnyVal" will match each other.
380
321
    if (!Proposed.Occupied.is_subset(Matches)) {
381
43
      if (OS) {
382
0
        auto Conflicting = Proposed.Occupied.subtract(Matches);
383
0
        auto ExistingConflictingKnown =
384
0
            Existing.Known.intersect_domain(Conflicting);
385
0
        auto ProposedConflictingKnown =
386
0
            Proposed.Known.intersect_domain(Conflicting);
387
0
388
0
        OS->indent(Indent) << "Proposed lifetime conflicting with Existing's\n";
389
0
        OS->indent(Indent) << "Conflicting occupied: " << Conflicting << "\n";
390
0
        if (!ExistingConflictingKnown.is_empty())
391
0
          OS->indent(Indent)
392
0
              << "Existing Known:       " << ExistingConflictingKnown << "\n";
393
0
        if (!ProposedConflictingKnown.is_empty())
394
0
          OS->indent(Indent)
395
0
              << "Proposed Known:       " << ProposedConflictingKnown << "\n";
396
0
      }
397
43
      return true;
398
43
    }
399
278
400
278
    // Do the writes in Existing conflict with occupied values in Proposed?
401
278
    //
402
278
    // In order to not conflict, it must either write to unused lifetime or
403
278
    // write the same value. To check, we remove the writes that write into
404
278
    // Proposed.Unused (they never conflict) and then see whether the written
405
278
    // value is already in Proposed.Known. If there are multiple known values
406
278
    // and a written value is known under different names, it is enough when one
407
278
    // of the written values (assuming that they are the same value under
408
278
    // different names, e.g. a PHINode and one of the incoming values) matches
409
278
    // one of the known names.
410
278
    //
411
278
    // We convert here the set of lifetimes to actual timepoints. A lifetime is
412
278
    // in conflict with a set of write timepoints, if either a live timepoint is
413
278
    // clearly within the lifetime or if a write happens at the beginning of the
414
278
    // lifetime (where it would conflict with the value that actually writes the
415
278
    // value alive). There is no conflict at the end of a lifetime, as the alive
416
278
    // value will always be read, before it is overwritten again. The last
417
278
    // property holds in Polly for all scalar values and we expect all users of
418
278
    // Knowledge to check this property also for accesses to MemoryKind::Array.
419
278
    auto ProposedFixedDefs =
420
278
        convertZoneToTimepoints(Proposed.Occupied, true, false);
421
278
    auto ProposedFixedKnown =
422
278
        convertZoneToTimepoints(Proposed.Known, isl::dim::in, true, false);
423
278
424
278
    auto ExistingConflictingWrites =
425
278
        Existing.Written.intersect_domain(ProposedFixedDefs);
426
278
    auto ExistingConflictingWritesDomain = ExistingConflictingWrites.domain();
427
278
428
278
    auto CommonWrittenVal =
429
278
        ProposedFixedKnown.intersect(ExistingConflictingWrites);
430
278
    auto CommonWrittenValDomain = CommonWrittenVal.domain();
431
278
432
278
    if (!ExistingConflictingWritesDomain.is_subset(CommonWrittenValDomain)) {
433
26
      if (OS) {
434
0
        auto ExistingConflictingWritten =
435
0
            ExistingConflictingWrites.subtract_domain(CommonWrittenValDomain);
436
0
        auto ProposedConflictingKnown = ProposedFixedKnown.subtract_domain(
437
0
            ExistingConflictingWritten.domain());
438
0
439
0
        OS->indent(Indent)
440
0
            << "Proposed a lifetime where there is an Existing write into it\n";
441
0
        OS->indent(Indent) << "Existing conflicting writes: "
442
0
                           << ExistingConflictingWritten << "\n";
443
0
        if (!ProposedConflictingKnown.is_empty())
444
0
          OS->indent(Indent)
445
0
              << "Proposed conflicting known:  " << ProposedConflictingKnown
446
0
              << "\n";
447
0
      }
448
26
      return true;
449
26
    }
450
252
451
252
    // Do the writes in Proposed conflict with occupied values in Existing?
452
252
    auto ExistingAvailableDefs =
453
252
        convertZoneToTimepoints(Existing.Unused, true, false);
454
252
    auto ExistingKnownDefs =
455
252
        convertZoneToTimepoints(Existing.Known, isl::dim::in, true, false);
456
252
457
252
    auto ProposedWrittenDomain = Proposed.Written.domain();
458
252
    auto KnownIdentical = ExistingKnownDefs.intersect(Proposed.Written);
459
252
    auto IdenticalOrUnused =
460
252
        ExistingAvailableDefs.unite(KnownIdentical.domain());
461
252
    if (!ProposedWrittenDomain.is_subset(IdenticalOrUnused)) {
462
24
      if (OS) {
463
0
        auto Conflicting = ProposedWrittenDomain.subtract(IdenticalOrUnused);
464
0
        auto ExistingConflictingKnown =
465
0
            ExistingKnownDefs.intersect_domain(Conflicting);
466
0
        auto ProposedConflictingWritten =
467
0
            Proposed.Written.intersect_domain(Conflicting);
468
0
469
0
        OS->indent(Indent) << "Proposed writes into range used by Existing\n";
470
0
        OS->indent(Indent) << "Proposed conflicting writes: "
471
0
                           << ProposedConflictingWritten << "\n";
472
0
        if (!ExistingConflictingKnown.is_empty())
473
0
          OS->indent(Indent)
474
0
              << "Existing conflicting known: " << ExistingConflictingKnown
475
0
              << "\n";
476
0
      }
477
24
      return true;
478
24
    }
479
228
480
228
    // Does Proposed write at the same time as Existing already does (order of
481
228
    // writes is undefined)? Writing the same value is permitted.
482
228
    auto ExistingWrittenDomain = Existing.Written.domain();
483
228
    auto BothWritten =
484
228
        Existing.Written.domain().intersect(Proposed.Written.domain());
485
228
    auto ExistingKnownWritten = filterKnownValInst(Existing.Written);
486
228
    auto ProposedKnownWritten = filterKnownValInst(Proposed.Written);
487
228
    auto CommonWritten =
488
228
        ExistingKnownWritten.intersect(ProposedKnownWritten).domain();
489
228
490
228
    if (!BothWritten.is_subset(CommonWritten)) {
491
24
      if (OS) {
492
0
        auto Conflicting = BothWritten.subtract(CommonWritten);
493
0
        auto ExistingConflictingWritten =
494
0
            Existing.Written.intersect_domain(Conflicting);
495
0
        auto ProposedConflictingWritten =
496
0
            Proposed.Written.intersect_domain(Conflicting);
497
0
498
0
        OS->indent(Indent) << "Proposed writes at the same time as an already "
499
0
                              "Existing write\n";
500
0
        OS->indent(Indent) << "Conflicting writes: " << Conflicting << "\n";
501
0
        if (!ExistingConflictingWritten.is_empty())
502
0
          OS->indent(Indent)
503
0
              << "Exiting write:      " << ExistingConflictingWritten << "\n";
504
0
        if (!ProposedConflictingWritten.is_empty())
505
0
          OS->indent(Indent)
506
0
              << "Proposed write:     " << ProposedConflictingWritten << "\n";
507
0
      }
508
24
      return true;
509
24
    }
510
204
511
204
    return false;
512
204
  }
513
};
514
515
/// Implementation of the DeLICM/DePRE transformation.
516
class DeLICMImpl : public ZoneAlgorithm {
517
private:
518
  /// Knowledge before any transformation took place.
519
  Knowledge OriginalZone;
520
521
  /// Current knowledge of the SCoP including all already applied
522
  /// transformations.
523
  Knowledge Zone;
524
525
  /// Number of StoreInsts something can be mapped to.
526
  int NumberOfCompatibleTargets = 0;
527
528
  /// The number of StoreInsts to which at least one value or PHI has been
529
  /// mapped to.
530
  int NumberOfTargetsMapped = 0;
531
532
  /// The number of llvm::Value mapped to some array element.
533
  int NumberOfMappedValueScalars = 0;
534
535
  /// The number of PHIs mapped to some array element.
536
  int NumberOfMappedPHIScalars = 0;
537
538
  /// Determine whether two knowledges are conflicting with each other.
539
  ///
540
  /// @see Knowledge::isConflicting
541
89
  bool isConflicting(const Knowledge &Proposed) {
542
89
    raw_ostream *OS = nullptr;
543
89
    LLVM_DEBUG(OS = &llvm::dbgs());
544
89
    return Knowledge::isConflicting(Zone, Proposed, OS, 4);
545
89
  }
546
547
  /// Determine whether @p SAI is a scalar that can be mapped to an array
548
  /// element.
549
97
  bool isMappable(const ScopArrayInfo *SAI) {
550
97
    assert(SAI);
551
97
552
97
    if (SAI->isValueKind()) {
553
63
      auto *MA = S->getValueDef(SAI);
554
63
      if (!MA) {
555
2
        LLVM_DEBUG(
556
2
            dbgs()
557
2
            << "    Reject because value is read-only within the scop\n");
558
2
        return false;
559
2
      }
560
61
561
61
      // Mapping if value is used after scop is not supported. The code
562
61
      // generator would need to reload the scalar after the scop, but it
563
61
      // does not have the information to where it is mapped to. Only the
564
61
      // MemoryAccesses have that information, not the ScopArrayInfo.
565
61
      auto Inst = MA->getAccessInstruction();
566
100
      for (auto User : Inst->users()) {
567
100
        if (!isa<Instruction>(User))
568
0
          return false;
569
100
        auto UserInst = cast<Instruction>(User);
570
100
571
100
        if (!S->contains(UserInst)) {
572
1
          LLVM_DEBUG(dbgs() << "    Reject because value is escaping\n");
573
1
          return false;
574
1
        }
575
100
      }
576
61
577
61
      
return true60
;
578
34
    }
579
34
580
34
    if (SAI->isPHIKind()) {
581
34
      auto *MA = S->getPHIRead(SAI);
582
34
      assert(MA);
583
34
584
34
      // Mapping of an incoming block from before the SCoP is not supported by
585
34
      // the code generator.
586
34
      auto PHI = cast<PHINode>(MA->getAccessInstruction());
587
68
      for (auto Incoming : PHI->blocks()) {
588
68
        if (!S->contains(Incoming)) {
589
0
          LLVM_DEBUG(dbgs()
590
0
                     << "    Reject because at least one incoming block is "
591
0
                        "not in the scop region\n");
592
0
          return false;
593
0
        }
594
68
      }
595
34
596
34
      return true;
597
0
    }
598
0
599
0
    LLVM_DEBUG(dbgs() << "    Reject ExitPHI or other non-value\n");
600
0
    return false;
601
0
  }
602
603
  /// Compute the uses of a MemoryKind::Value and its lifetime (from its
604
  /// definition to the last use).
605
  ///
606
  /// @param SAI The ScopArrayInfo representing the value's storage.
607
  ///
608
  /// @return { DomainDef[] -> DomainUse[] }, { DomainDef[] -> Zone[] }
609
  ///         First element is the set of uses for each definition.
610
  ///         The second is the lifetime of each definition.
611
  std::tuple<isl::union_map, isl::map>
612
56
  computeValueUses(const ScopArrayInfo *SAI) {
613
56
    assert(SAI->isValueKind());
614
56
615
56
    // { DomainRead[] }
616
56
    auto Reads = makeEmptyUnionSet();
617
56
618
56
    // Find all uses.
619
56
    for (auto *MA : S->getValueUses(SAI))
620
79
      Reads = Reads.add_set(getDomainFor(MA));
621
56
622
56
    // { DomainRead[] -> Scatter[] }
623
56
    auto ReadSchedule = getScatterFor(Reads);
624
56
625
56
    auto *DefMA = S->getValueDef(SAI);
626
56
    assert(DefMA);
627
56
628
56
    // { DomainDef[] }
629
56
    auto Writes = getDomainFor(DefMA);
630
56
631
56
    // { DomainDef[] -> Scatter[] }
632
56
    auto WriteScatter = getScatterFor(Writes);
633
56
634
56
    // { Scatter[] -> DomainDef[] }
635
56
    auto ReachDef = getScalarReachingDefinition(DefMA->getStatement());
636
56
637
56
    // { [DomainDef[] -> Scatter[]] -> DomainUse[] }
638
56
    auto Uses = isl::union_map(ReachDef.reverse().range_map())
639
56
                    .apply_range(ReadSchedule.reverse());
640
56
641
56
    // { DomainDef[] -> Scatter[] }
642
56
    auto UseScatter =
643
56
        singleton(Uses.domain().unwrap(),
644
56
                  Writes.get_space().map_from_domain_and_range(ScatterSpace));
645
56
646
56
    // { DomainDef[] -> Zone[] }
647
56
    auto Lifetime = betweenScatter(WriteScatter, UseScatter, false, true);
648
56
649
56
    // { DomainDef[] -> DomainRead[] }
650
56
    auto DefUses = Uses.domain_factor_domain();
651
56
652
56
    return std::make_pair(DefUses, Lifetime);
653
56
  }
654
655
  /// Try to map a MemoryKind::Value to a given array element.
656
  ///
657
  /// @param SAI       Representation of the scalar's memory to map.
658
  /// @param TargetElt { Scatter[] -> Element[] }
659
  ///                  Suggestion where to map a scalar to when at a timepoint.
660
  ///
661
  /// @return true if the scalar was successfully mapped.
662
59
  bool tryMapValue(const ScopArrayInfo *SAI, isl::map TargetElt) {
663
59
    assert(SAI->isValueKind());
664
59
665
59
    auto *DefMA = S->getValueDef(SAI);
666
59
    assert(DefMA->isValueKind());
667
59
    assert(DefMA->isMustWrite());
668
59
    auto *V = DefMA->getAccessValue();
669
59
    auto *DefInst = DefMA->getAccessInstruction();
670
59
671
59
    // Stop if the scalar has already been mapped.
672
59
    if (!DefMA->getLatestScopArrayInfo()->isValueKind())
673
1
      return false;
674
58
675
58
    // { DomainDef[] -> Scatter[] }
676
58
    auto DefSched = getScatterFor(DefMA);
677
58
678
58
    // Where each write is mapped to, according to the suggestion.
679
58
    // { DomainDef[] -> Element[] }
680
58
    auto DefTarget = TargetElt.apply_domain(DefSched.reverse());
681
58
    simplify(DefTarget);
682
58
    LLVM_DEBUG(dbgs() << "    Def Mapping: " << DefTarget << '\n');
683
58
684
58
    auto OrigDomain = getDomainFor(DefMA);
685
58
    auto MappedDomain = DefTarget.domain();
686
58
    if (!OrigDomain.is_subset(MappedDomain)) {
687
2
      LLVM_DEBUG(
688
2
          dbgs()
689
2
          << "    Reject because mapping does not encompass all instances\n");
690
2
      return false;
691
2
    }
692
56
693
56
    // { DomainDef[] -> Zone[] }
694
56
    isl::map Lifetime;
695
56
696
56
    // { DomainDef[] -> DomainUse[] }
697
56
    isl::union_map DefUses;
698
56
699
56
    std::tie(DefUses, Lifetime) = computeValueUses(SAI);
700
56
    LLVM_DEBUG(dbgs() << "    Lifetime: " << Lifetime << '\n');
701
56
702
56
    /// { [Element[] -> Zone[]] }
703
56
    auto EltZone = Lifetime.apply_domain(DefTarget).wrap();
704
56
    simplify(EltZone);
705
56
706
56
    // When known knowledge is disabled, just return the unknown value. It will
707
56
    // either get filtered out or conflict with itself.
708
56
    // { DomainDef[] -> ValInst[] }
709
56
    isl::map ValInst;
710
56
    if (DelicmComputeKnown)
711
56
      ValInst = makeValInst(V, DefMA->getStatement(),
712
56
                            LI->getLoopFor(DefInst->getParent()));
713
0
    else
714
0
      ValInst = makeUnknownForDomain(DefMA->getStatement());
715
56
716
56
    // { DomainDef[] -> [Element[] -> Zone[]] }
717
56
    auto EltKnownTranslator = DefTarget.range_product(Lifetime);
718
56
719
56
    // { [Element[] -> Zone[]] -> ValInst[] }
720
56
    auto EltKnown = ValInst.apply_domain(EltKnownTranslator);
721
56
    simplify(EltKnown);
722
56
723
56
    // { DomainDef[] -> [Element[] -> Scatter[]] }
724
56
    auto WrittenTranslator = DefTarget.range_product(DefSched);
725
56
726
56
    // { [Element[] -> Scatter[]] -> ValInst[] }
727
56
    auto DefEltSched = ValInst.apply_domain(WrittenTranslator);
728
56
    simplify(DefEltSched);
729
56
730
56
    Knowledge Proposed(EltZone, nullptr, filterKnownValInst(EltKnown),
731
56
                       DefEltSched);
732
56
    if (isConflicting(Proposed))
733
5
      return false;
734
51
735
51
    // { DomainUse[] -> Element[] }
736
51
    auto UseTarget = DefUses.reverse().apply_range(DefTarget);
737
51
738
51
    mapValue(SAI, std::move(DefTarget), std::move(UseTarget),
739
51
             std::move(Lifetime), std::move(Proposed));
740
51
    return true;
741
51
  }
742
743
  /// After a scalar has been mapped, update the global knowledge.
744
84
  void applyLifetime(Knowledge Proposed) {
745
84
    Zone.learnFrom(std::move(Proposed));
746
84
  }
747
748
  /// Map a MemoryKind::Value scalar to an array element.
749
  ///
750
  /// Callers must have ensured that the mapping is valid and not conflicting.
751
  ///
752
  /// @param SAI       The ScopArrayInfo representing the scalar's memory to
753
  ///                  map.
754
  /// @param DefTarget { DomainDef[] -> Element[] }
755
  ///                  The array element to map the scalar to.
756
  /// @param UseTarget { DomainUse[] -> Element[] }
757
  ///                  The array elements the uses are mapped to.
758
  /// @param Lifetime  { DomainDef[] -> Zone[] }
759
  ///                  The lifetime of each llvm::Value definition for
760
  ///                  reporting.
761
  /// @param Proposed  Mapping constraints for reporting.
762
  void mapValue(const ScopArrayInfo *SAI, isl::map DefTarget,
763
                isl::union_map UseTarget, isl::map Lifetime,
764
51
                Knowledge Proposed) {
765
51
    // Redirect the read accesses.
766
69
    for (auto *MA : S->getValueUses(SAI)) {
767
69
      // { DomainUse[] }
768
69
      auto Domain = getDomainFor(MA);
769
69
770
69
      // { DomainUse[] -> Element[] }
771
69
      auto NewAccRel = UseTarget.intersect_domain(Domain);
772
69
      simplify(NewAccRel);
773
69
774
69
      assert(isl_union_map_n_map(NewAccRel.get()) == 1);
775
69
      MA->setNewAccessRelation(isl::map::from_union_map(NewAccRel));
776
69
    }
777
51
778
51
    auto *WA = S->getValueDef(SAI);
779
51
    WA->setNewAccessRelation(DefTarget);
780
51
    applyLifetime(Proposed);
781
51
782
51
    MappedValueScalars++;
783
51
    NumberOfMappedValueScalars += 1;
784
51
  }
785
786
  isl::map makeValInst(Value *Val, ScopStmt *UserStmt, Loop *Scope,
787
122
                       bool IsCertain = true) {
788
122
    // When known knowledge is disabled, just return the unknown value. It will
789
122
    // either get filtered out or conflict with itself.
790
122
    if (!DelicmComputeKnown)
791
0
      return makeUnknownForDomain(UserStmt);
792
122
    return ZoneAlgorithm::makeValInst(Val, UserStmt, Scope, IsCertain);
793
122
  }
794
795
  /// Express the incoming values of a PHI for each incoming statement in an
796
  /// isl::union_map.
797
  ///
798
  /// @param SAI The PHI scalar represented by a ScopArrayInfo.
799
  ///
800
  /// @return { PHIWriteDomain[] -> ValInst[] }
801
33
  isl::union_map determinePHIWrittenValues(const ScopArrayInfo *SAI) {
802
33
    auto Result = makeEmptyUnionMap();
803
33
804
33
    // Collect the incoming values.
805
66
    for (auto *MA : S->getPHIIncomings(SAI)) {
806
66
      // { DomainWrite[] -> ValInst[] }
807
66
      isl::union_map ValInst;
808
66
      auto *WriteStmt = MA->getStatement();
809
66
810
66
      auto Incoming = MA->getIncoming();
811
66
      assert(!Incoming.empty());
812
66
      if (Incoming.size() == 1) {
813
66
        ValInst = makeValInst(Incoming[0].second, WriteStmt,
814
66
                              LI->getLoopFor(Incoming[0].first));
815
66
      } else {
816
0
        // If the PHI is in a subregion's exit node it can have multiple
817
0
        // incoming values (+ maybe another incoming edge from an unrelated
818
0
        // block). We cannot directly represent it as a single llvm::Value.
819
0
        // We currently model it as unknown value, but modeling as the PHIInst
820
0
        // itself could be OK, too.
821
0
        ValInst = makeUnknownForDomain(WriteStmt);
822
0
      }
823
66
824
66
      Result = Result.unite(ValInst);
825
66
    }
826
33
827
33
    assert(Result.is_single_valued() &&
828
33
           "Cannot have multiple incoming values for same incoming statement");
829
33
    return Result;
830
33
  }
831
832
  /// Try to map a MemoryKind::PHI scalar to a given array element.
833
  ///
834
  /// @param SAI       Representation of the scalar's memory to map.
835
  /// @param TargetElt { Scatter[] -> Element[] }
836
  ///                  Suggestion where to map the scalar to when at a
837
  ///                  timepoint.
838
  ///
839
  /// @return true if the PHI scalar has been mapped.
840
34
  bool tryMapPHI(const ScopArrayInfo *SAI, isl::map TargetElt) {
841
34
    auto *PHIRead = S->getPHIRead(SAI);
842
34
    assert(PHIRead->isPHIKind());
843
34
    assert(PHIRead->isRead());
844
34
845
34
    // Skip if already been mapped.
846
34
    if (!PHIRead->getLatestScopArrayInfo()->isPHIKind())
847
0
      return false;
848
34
849
34
    // { DomainRead[] -> Scatter[] }
850
34
    auto PHISched = getScatterFor(PHIRead);
851
34
852
34
    // { DomainRead[] -> Element[] }
853
34
    auto PHITarget = PHISched.apply_range(TargetElt);
854
34
    simplify(PHITarget);
855
34
    LLVM_DEBUG(dbgs() << "    Mapping: " << PHITarget << '\n');
856
34
857
34
    auto OrigDomain = getDomainFor(PHIRead);
858
34
    auto MappedDomain = PHITarget.domain();
859
34
    if (!OrigDomain.is_subset(MappedDomain)) {
860
0
      LLVM_DEBUG(
861
0
          dbgs()
862
0
          << "    Reject because mapping does not encompass all instances\n");
863
0
      return false;
864
0
    }
865
34
866
34
    // { DomainRead[] -> DomainWrite[] }
867
34
    auto PerPHIWrites = computePerPHI(SAI);
868
34
869
34
    // { DomainWrite[] -> Element[] }
870
34
    auto WritesTarget = PerPHIWrites.apply_domain(PHITarget).reverse();
871
34
    simplify(WritesTarget);
872
34
873
34
    // { DomainWrite[] }
874
34
    auto UniverseWritesDom = isl::union_set::empty(ParamSpace);
875
34
876
34
    for (auto *MA : S->getPHIIncomings(SAI))
877
68
      UniverseWritesDom = UniverseWritesDom.add_set(getDomainFor(MA));
878
34
879
34
    auto RelevantWritesTarget = WritesTarget;
880
34
    if (DelicmOverapproximateWrites)
881
11
      WritesTarget = expandMapping(WritesTarget, UniverseWritesDom);
882
34
883
34
    auto ExpandedWritesDom = WritesTarget.domain();
884
34
    if (!DelicmPartialWrites &&
885
34
        
!UniverseWritesDom.is_subset(ExpandedWritesDom)3
) {
886
1
      LLVM_DEBUG(
887
1
          dbgs() << "    Reject because did not find PHI write mapping for "
888
1
                    "all instances\n");
889
1
      if (DelicmOverapproximateWrites)
890
1
        LLVM_DEBUG(dbgs() << "      Relevant Mapping:    "
891
1
                          << RelevantWritesTarget << '\n');
892
1
      LLVM_DEBUG(dbgs() << "      Deduced Mapping:     " << WritesTarget
893
1
                        << '\n');
894
1
      LLVM_DEBUG(dbgs() << "      Missing instances:    "
895
1
                        << UniverseWritesDom.subtract(ExpandedWritesDom)
896
1
                        << '\n');
897
1
      return false;
898
1
    }
899
33
900
33
    //  { DomainRead[] -> Scatter[] }
901
33
    auto PerPHIWriteScatter =
902
33
        isl::map::from_union_map(PerPHIWrites.apply_range(Schedule));
903
33
904
33
    // { DomainRead[] -> Zone[] }
905
33
    auto Lifetime = betweenScatter(PerPHIWriteScatter, PHISched, false, true);
906
33
    simplify(Lifetime);
907
33
    LLVM_DEBUG(dbgs() << "    Lifetime: " << Lifetime << "\n");
908
33
909
33
    // { DomainWrite[] -> Zone[] }
910
33
    auto WriteLifetime = isl::union_map(Lifetime).apply_domain(PerPHIWrites);
911
33
912
33
    // { DomainWrite[] -> ValInst[] }
913
33
    auto WrittenValue = determinePHIWrittenValues(SAI);
914
33
915
33
    // { DomainWrite[] -> [Element[] -> Scatter[]] }
916
33
    auto WrittenTranslator = WritesTarget.range_product(Schedule);
917
33
918
33
    // { [Element[] -> Scatter[]] -> ValInst[] }
919
33
    auto Written = WrittenValue.apply_domain(WrittenTranslator);
920
33
    simplify(Written);
921
33
922
33
    // { DomainWrite[] -> [Element[] -> Zone[]] }
923
33
    auto LifetimeTranslator = WritesTarget.range_product(WriteLifetime);
924
33
925
33
    // { DomainWrite[] -> ValInst[] }
926
33
    auto WrittenKnownValue = filterKnownValInst(WrittenValue);
927
33
928
33
    // { [Element[] -> Zone[]] -> ValInst[] }
929
33
    auto EltLifetimeInst = WrittenKnownValue.apply_domain(LifetimeTranslator);
930
33
    simplify(EltLifetimeInst);
931
33
932
33
    // { [Element[] -> Zone[] }
933
33
    auto Occupied = LifetimeTranslator.range();
934
33
    simplify(Occupied);
935
33
936
33
    Knowledge Proposed(Occupied, nullptr, EltLifetimeInst, Written);
937
33
    if (isConflicting(Proposed))
938
0
      return false;
939
33
940
33
    mapPHI(SAI, std::move(PHITarget), std::move(WritesTarget),
941
33
           std::move(Lifetime), std::move(Proposed));
942
33
    return true;
943
33
  }
944
945
  /// Map a MemoryKind::PHI scalar to an array element.
946
  ///
947
  /// Callers must have ensured that the mapping is valid and not conflicting
948
  /// with the common knowledge.
949
  ///
950
  /// @param SAI         The ScopArrayInfo representing the scalar's memory to
951
  ///                    map.
952
  /// @param ReadTarget  { DomainRead[] -> Element[] }
953
  ///                    The array element to map the scalar to.
954
  /// @param WriteTarget { DomainWrite[] -> Element[] }
955
  ///                    New access target for each PHI incoming write.
956
  /// @param Lifetime    { DomainRead[] -> Zone[] }
957
  ///                    The lifetime of each PHI for reporting.
958
  /// @param Proposed    Mapping constraints for reporting.
959
  void mapPHI(const ScopArrayInfo *SAI, isl::map ReadTarget,
960
              isl::union_map WriteTarget, isl::map Lifetime,
961
33
              Knowledge Proposed) {
962
33
    // { Element[] }
963
33
    isl::space ElementSpace = ReadTarget.get_space().range();
964
33
965
33
    // Redirect the PHI incoming writes.
966
66
    for (auto *MA : S->getPHIIncomings(SAI)) {
967
66
      // { DomainWrite[] }
968
66
      auto Domain = getDomainFor(MA);
969
66
970
66
      // { DomainWrite[] -> Element[] }
971
66
      auto NewAccRel = WriteTarget.intersect_domain(Domain);
972
66
      simplify(NewAccRel);
973
66
974
66
      isl::space NewAccRelSpace =
975
66
          Domain.get_space().map_from_domain_and_range(ElementSpace);
976
66
      isl::map NewAccRelMap = singleton(NewAccRel, NewAccRelSpace);
977
66
      MA->setNewAccessRelation(NewAccRelMap);
978
66
    }
979
33
980
33
    // Redirect the PHI read.
981
33
    auto *PHIRead = S->getPHIRead(SAI);
982
33
    PHIRead->setNewAccessRelation(ReadTarget);
983
33
    applyLifetime(Proposed);
984
33
985
33
    MappedPHIScalars++;
986
33
    NumberOfMappedPHIScalars++;
987
33
  }
988
989
  /// Search and map scalars to memory overwritten by @p TargetStoreMA.
990
  ///
991
  /// Start trying to map scalars that are used in the same statement as the
992
  /// store. For every successful mapping, try to also map scalars of the
993
  /// statements where those are written. Repeat, until no more mapping
994
  /// opportunity is found.
995
  ///
996
  /// There is currently no preference in which order scalars are tried.
997
  /// Ideally, we would direct it towards a load instruction of the same array
998
  /// element.
999
40
  bool collapseScalarsToStore(MemoryAccess *TargetStoreMA) {
1000
40
    assert(TargetStoreMA->isLatestArrayKind());
1001
40
    assert(TargetStoreMA->isMustWrite());
1002
40
1003
40
    auto TargetStmt = TargetStoreMA->getStatement();
1004
40
1005
40
    // { DomTarget[] }
1006
40
    auto TargetDom = getDomainFor(TargetStmt);
1007
40
1008
40
    // { DomTarget[] -> Element[] }
1009
40
    auto TargetAccRel = getAccessRelationFor(TargetStoreMA);
1010
40
1011
40
    // { Zone[] -> DomTarget[] }
1012
40
    // For each point in time, find the next target store instance.
1013
40
    auto Target =
1014
40
        computeScalarReachingOverwrite(Schedule, TargetDom, false, true);
1015
40
1016
40
    // { Zone[] -> Element[] }
1017
40
    // Use the target store's write location as a suggestion to map scalars to.
1018
40
    auto EltTarget = Target.apply_range(TargetAccRel);
1019
40
    simplify(EltTarget);
1020
40
    LLVM_DEBUG(dbgs() << "    Target mapping is " << EltTarget << '\n');
1021
40
1022
40
    // Stack of elements not yet processed.
1023
40
    SmallVector<MemoryAccess *, 16> Worklist;
1024
40
1025
40
    // Set of scalars already tested.
1026
40
    SmallPtrSet<const ScopArrayInfo *, 16> Closed;
1027
40
1028
40
    // Lambda to add all scalar reads to the work list.
1029
98
    auto ProcessAllIncoming = [&](ScopStmt *Stmt) {
1030
198
      for (auto *MA : *Stmt) {
1031
198
        if (!MA->isLatestScalarKind())
1032
137
          continue;
1033
61
        if (!MA->isRead())
1034
9
          continue;
1035
52
1036
52
        Worklist.push_back(MA);
1037
52
      }
1038
98
    };
1039
40
1040
40
    auto *WrittenVal = TargetStoreMA->getAccessInstruction()->getOperand(0);
1041
40
    if (auto *WrittenValInputMA = TargetStmt->lookupInputAccessOf(WrittenVal))
1042
29
      Worklist.push_back(WrittenValInputMA);
1043
11
    else
1044
11
      ProcessAllIncoming(TargetStmt);
1045
40
1046
40
    auto AnyMapped = false;
1047
40
    auto &DL = S->getRegion().getEntry()->getModule()->getDataLayout();
1048
40
    auto StoreSize =
1049
40
        DL.getTypeAllocSize(TargetStoreMA->getAccessValue()->getType());
1050
40
1051
151
    while (!Worklist.empty()) {
1052
111
      auto *MA = Worklist.pop_back_val();
1053
111
1054
111
      auto *SAI = MA->getScopArrayInfo();
1055
111
      if (Closed.count(SAI))
1056
14
        continue;
1057
97
      Closed.insert(SAI);
1058
97
      LLVM_DEBUG(dbgs() << "\n    Trying to map " << MA << " (SAI: " << SAI
1059
97
                        << ")\n");
1060
97
1061
97
      // Skip non-mappable scalars.
1062
97
      if (!isMappable(SAI))
1063
3
        continue;
1064
94
1065
94
      auto MASize = DL.getTypeAllocSize(MA->getAccessValue()->getType());
1066
94
      if (MASize > StoreSize) {
1067
1
        LLVM_DEBUG(
1068
1
            dbgs() << "    Reject because storage size is insufficient\n");
1069
1
        continue;
1070
1
      }
1071
93
1072
93
      // Try to map MemoryKind::Value scalars.
1073
93
      if (SAI->isValueKind()) {
1074
59
        if (!tryMapValue(SAI, EltTarget))
1075
8
          continue;
1076
51
1077
51
        auto *DefAcc = S->getValueDef(SAI);
1078
51
        ProcessAllIncoming(DefAcc->getStatement());
1079
51
1080
51
        AnyMapped = true;
1081
51
        continue;
1082
51
      }
1083
34
1084
34
      // Try to map MemoryKind::PHI scalars.
1085
34
      if (SAI->isPHIKind()) {
1086
34
        if (!tryMapPHI(SAI, EltTarget))
1087
1
          continue;
1088
33
        // Add inputs of all incoming statements to the worklist. Prefer the
1089
33
        // input accesses of the incoming blocks.
1090
66
        
for (auto *PHIWrite : S->getPHIIncomings(SAI))33
{
1091
66
          auto *PHIWriteStmt = PHIWrite->getStatement();
1092
66
          bool FoundAny = false;
1093
66
          for (auto Incoming : PHIWrite->getIncoming()) {
1094
66
            auto *IncomingInputMA =
1095
66
                PHIWriteStmt->lookupInputAccessOf(Incoming.second);
1096
66
            if (!IncomingInputMA)
1097
36
              continue;
1098
30
1099
30
            Worklist.push_back(IncomingInputMA);
1100
30
            FoundAny = true;
1101
30
          }
1102
66
1103
66
          if (!FoundAny)
1104
36
            ProcessAllIncoming(PHIWrite->getStatement());
1105
66
        }
1106
33
1107
33
        AnyMapped = true;
1108
33
        continue;
1109
33
      }
1110
34
    }
1111
40
1112
40
    if (AnyMapped) {
1113
30
      TargetsMapped++;
1114
30
      NumberOfTargetsMapped++;
1115
30
    }
1116
40
    return AnyMapped;
1117
40
  }
1118
1119
  /// Compute when an array element is unused.
1120
  ///
1121
  /// @return { [Element[] -> Zone[]] }
1122
51
  isl::union_set computeLifetime() const {
1123
51
    // { Element[] -> Zone[] }
1124
51
    auto ArrayUnused = computeArrayUnused(Schedule, AllMustWrites, AllReads,
1125
51
                                          false, false, true);
1126
51
1127
51
    auto Result = ArrayUnused.wrap();
1128
51
1129
51
    simplify(Result);
1130
51
    return Result;
1131
51
  }
1132
1133
  /// Determine when an array element is written to, and which value instance is
1134
  /// written.
1135
  ///
1136
  /// @return { [Element[] -> Scatter[]] -> ValInst[] }
1137
51
  isl::union_map computeWritten() const {
1138
51
    // { [Element[] -> Scatter[]] -> ValInst[] }
1139
51
    auto EltWritten = applyDomainRange(AllWriteValInst, Schedule);
1140
51
1141
51
    simplify(EltWritten);
1142
51
    return EltWritten;
1143
51
  }
1144
1145
  /// Determine whether an access touches at most one element.
1146
  ///
1147
  /// The accessed element could be a scalar or accessing an array with constant
1148
  /// subscript, such that all instances access only that element.
1149
  ///
1150
  /// @param MA The access to test.
1151
  ///
1152
  /// @return True, if zero or one elements are accessed; False if at least two
1153
  ///         different elements are accessed.
1154
58
  bool isScalarAccess(MemoryAccess *MA) {
1155
58
    auto Map = getAccessRelationFor(MA);
1156
58
    auto Set = Map.range();
1157
58
    return Set.is_singleton();
1158
58
  }
1159
1160
  /// Print mapping statistics to @p OS.
1161
44
  void printStatistics(llvm::raw_ostream &OS, int Indent = 0) const {
1162
44
    OS.indent(Indent) << "Statistics {\n";
1163
44
    OS.indent(Indent + 4) << "Compatible overwrites: "
1164
44
                          << NumberOfCompatibleTargets << "\n";
1165
44
    OS.indent(Indent + 4) << "Overwrites mapped to:  " << NumberOfTargetsMapped
1166
44
                          << '\n';
1167
44
    OS.indent(Indent + 4) << "Value scalars mapped:  "
1168
44
                          << NumberOfMappedValueScalars << '\n';
1169
44
    OS.indent(Indent + 4) << "PHI scalars mapped:    "
1170
44
                          << NumberOfMappedPHIScalars << '\n';
1171
44
    OS.indent(Indent) << "}\n";
1172
44
  }
1173
1174
  /// Return whether at least one transformation been applied.
1175
44
  bool isModified() const { return NumberOfTargetsMapped > 0; }
1176
1177
public:
1178
51
  DeLICMImpl(Scop *S, LoopInfo *LI) : ZoneAlgorithm("polly-delicm", S, LI) {}
1179
1180
  /// Calculate the lifetime (definition to last use) of every array element.
1181
  ///
1182
  /// @return True if the computed lifetimes (#Zone) is usable.
1183
51
  bool computeZone() {
1184
51
    // Check that nothing strange occurs.
1185
51
    collectCompatibleElts();
1186
51
1187
51
    isl::union_set EltUnused;
1188
51
    isl::union_map EltKnown, EltWritten;
1189
51
1190
51
    {
1191
51
      IslMaxOperationsGuard MaxOpGuard(IslCtx.get(), DelicmMaxOps);
1192
51
1193
51
      computeCommon();
1194
51
1195
51
      EltUnused = computeLifetime();
1196
51
      EltKnown = computeKnown(true, false);
1197
51
      EltWritten = computeWritten();
1198
51
    }
1199
51
    DeLICMAnalyzed++;
1200
51
1201
51
    if (!EltUnused || 
!EltKnown48
||
!EltWritten48
) {
1202
3
      assert(isl_ctx_last_error(IslCtx.get()) == isl_error_quota &&
1203
3
             "The only reason that these things have not been computed should "
1204
3
             "be if the max-operations limit hit");
1205
3
      DeLICMOutOfQuota++;
1206
3
      LLVM_DEBUG(dbgs() << "DeLICM analysis exceeded max_operations\n");
1207
3
      DebugLoc Begin, End;
1208
3
      getDebugLocations(getBBPairForRegion(&S->getRegion()), Begin, End);
1209
3
      OptimizationRemarkAnalysis R(DEBUG_TYPE, "OutOfQuota", Begin,
1210
3
                                   S->getEntry());
1211
3
      R << "maximal number of operations exceeded during zone analysis";
1212
3
      S->getFunction().getContext().diagnose(R);
1213
3
      return false;
1214
3
    }
1215
48
1216
48
    Zone = OriginalZone = Knowledge(nullptr, EltUnused, EltKnown, EltWritten);
1217
48
    LLVM_DEBUG(dbgs() << "Computed Zone:\n"; OriginalZone.print(dbgs(), 4));
1218
48
1219
48
    assert(Zone.isUsable() && OriginalZone.isUsable());
1220
48
    return true;
1221
48
  }
1222
1223
  /// Try to map as many scalars to unused array elements as possible.
1224
  ///
1225
  /// Multiple scalars might be mappable to intersecting unused array element
1226
  /// zones, but we can only chose one. This is a greedy algorithm, therefore
1227
  /// the first processed element claims it.
1228
48
  void greedyCollapse() {
1229
48
    bool Modified = false;
1230
48
1231
222
    for (auto &Stmt : *S) {
1232
436
      for (auto *MA : Stmt) {
1233
436
        if (!MA->isLatestArrayKind())
1234
326
          continue;
1235
110
        if (!MA->isWrite())
1236
43
          continue;
1237
67
1238
67
        if (MA->isMayWrite()) {
1239
4
          LLVM_DEBUG(dbgs() << "Access " << MA
1240
4
                            << " pruned because it is a MAY_WRITE\n");
1241
4
          OptimizationRemarkMissed R(DEBUG_TYPE, "TargetMayWrite",
1242
4
                                     MA->getAccessInstruction());
1243
4
          R << "Skipped possible mapping target because it is not an "
1244
4
               "unconditional overwrite";
1245
4
          S->getFunction().getContext().diagnose(R);
1246
4
          continue;
1247
4
        }
1248
63
1249
63
        if (Stmt.getNumIterators() == 0) {
1250
5
          LLVM_DEBUG(dbgs() << "Access " << MA
1251
5
                            << " pruned because it is not in a loop\n");
1252
5
          OptimizationRemarkMissed R(DEBUG_TYPE, "WriteNotInLoop",
1253
5
                                     MA->getAccessInstruction());
1254
5
          R << "skipped possible mapping target because it is not in a loop";
1255
5
          S->getFunction().getContext().diagnose(R);
1256
5
          continue;
1257
5
        }
1258
58
1259
58
        if (isScalarAccess(MA)) {
1260
5
          LLVM_DEBUG(dbgs()
1261
5
                     << "Access " << MA
1262
5
                     << " pruned because it writes only a single element\n");
1263
5
          OptimizationRemarkMissed R(DEBUG_TYPE, "ScalarWrite",
1264
5
                                     MA->getAccessInstruction());
1265
5
          R << "skipped possible mapping target because the memory location "
1266
5
               "written to does not depend on its outer loop";
1267
5
          S->getFunction().getContext().diagnose(R);
1268
5
          continue;
1269
5
        }
1270
53
1271
53
        if (!isa<StoreInst>(MA->getAccessInstruction())) {
1272
8
          LLVM_DEBUG(dbgs() << "Access " << MA
1273
8
                            << " pruned because it is not a StoreInst\n");
1274
8
          OptimizationRemarkMissed R(DEBUG_TYPE, "NotAStore",
1275
8
                                     MA->getAccessInstruction());
1276
8
          R << "skipped possible mapping target because non-store instructions "
1277
8
               "are not supported";
1278
8
          S->getFunction().getContext().diagnose(R);
1279
8
          continue;
1280
8
        }
1281
45
1282
45
        // Check for more than one element acces per statement instance.
1283
45
        // Currently we expect write accesses to be functional, eg. disallow
1284
45
        //
1285
45
        //   { Stmt[0] -> [i] : 0 <= i < 2 }
1286
45
        //
1287
45
        // This may occur when some accesses to the element write/read only
1288
45
        // parts of the element, eg. a single byte. Polly then divides each
1289
45
        // element into subelements of the smallest access length, normal access
1290
45
        // then touch multiple of such subelements. It is very common when the
1291
45
        // array is accesses with memset, memcpy or memmove which take i8*
1292
45
        // arguments.
1293
45
        isl::union_map AccRel = MA->getLatestAccessRelation();
1294
45
        if (!AccRel.is_single_valued().is_true()) {
1295
1
          LLVM_DEBUG(dbgs() << "Access " << MA
1296
1
                            << " is incompatible because it writes multiple "
1297
1
                               "elements per instance\n");
1298
1
          OptimizationRemarkMissed R(DEBUG_TYPE, "NonFunctionalAccRel",
1299
1
                                     MA->getAccessInstruction());
1300
1
          R << "skipped possible mapping target because it writes more than "
1301
1
               "one element";
1302
1
          S->getFunction().getContext().diagnose(R);
1303
1
          continue;
1304
1
        }
1305
44
1306
44
        isl::union_set TouchedElts = AccRel.range();
1307
44
        if (!TouchedElts.is_subset(CompatibleElts)) {
1308
4
          LLVM_DEBUG(
1309
4
              dbgs()
1310
4
              << "Access " << MA
1311
4
              << " is incompatible because it touches incompatible elements\n");
1312
4
          OptimizationRemarkMissed R(DEBUG_TYPE, "IncompatibleElts",
1313
4
                                     MA->getAccessInstruction());
1314
4
          R << "skipped possible mapping target because a target location "
1315
4
               "cannot be reliably analyzed";
1316
4
          S->getFunction().getContext().diagnose(R);
1317
4
          continue;
1318
4
        }
1319
40
1320
40
        assert(isCompatibleAccess(MA));
1321
40
        NumberOfCompatibleTargets++;
1322
40
        LLVM_DEBUG(dbgs() << "Analyzing target access " << MA << "\n");
1323
40
        if (collapseScalarsToStore(MA))
1324
30
          Modified = true;
1325
40
      }
1326
222
    }
1327
48
1328
48
    if (Modified)
1329
30
      DeLICMScopsModified++;
1330
48
  }
1331
1332
  /// Dump the internal information about a performed DeLICM to @p OS.
1333
47
  void print(llvm::raw_ostream &OS, int Indent = 0) {
1334
47
    if (!Zone.isUsable()) {
1335
3
      OS.indent(Indent) << "Zone not computed\n";
1336
3
      return;
1337
3
    }
1338
44
1339
44
    printStatistics(OS, Indent);
1340
44
    if (!isModified()) {
1341
16
      OS.indent(Indent) << "No modification has been made\n";
1342
16
      return;
1343
16
    }
1344
28
    printAccesses(OS, Indent);
1345
28
  }
1346
};
1347
1348
class DeLICM : public ScopPass {
1349
private:
1350
  DeLICM(const DeLICM &) = delete;
1351
  const DeLICM &operator=(const DeLICM &) = delete;
1352
1353
  /// The pass implementation, also holding per-scop data.
1354
  std::unique_ptr<DeLICMImpl> Impl;
1355
1356
51
  void collapseToUnused(Scop &S) {
1357
51
    auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1358
51
    Impl = make_unique<DeLICMImpl>(&S, &LI);
1359
51
1360
51
    if (!Impl->computeZone()) {
1361
3
      LLVM_DEBUG(dbgs() << "Abort because cannot reliably compute lifetimes\n");
1362
3
      return;
1363
3
    }
1364
48
1365
48
    LLVM_DEBUG(dbgs() << "Collapsing scalars to unused array elements...\n");
1366
48
    Impl->greedyCollapse();
1367
48
1368
48
    LLVM_DEBUG(dbgs() << "\nFinal Scop:\n");
1369
48
    LLVM_DEBUG(dbgs() << S);
1370
48
  }
1371
1372
public:
1373
  static char ID;
1374
51
  explicit DeLICM() : ScopPass(ID) {}
1375
1376
51
  virtual void getAnalysisUsage(AnalysisUsage &AU) const override {
1377
51
    AU.addRequiredTransitive<ScopInfoRegionPass>();
1378
51
    AU.addRequired<LoopInfoWrapperPass>();
1379
51
    AU.setPreservesAll();
1380
51
  }
1381
1382
51
  virtual bool runOnScop(Scop &S) override {
1383
51
    // Free resources for previous scop's computation, if not yet done.
1384
51
    releaseMemory();
1385
51
1386
51
    collapseToUnused(S);
1387
51
1388
51
    auto ScopStats = S.getStatistics();
1389
51
    NumValueWrites += ScopStats.NumValueWrites;
1390
51
    NumValueWritesInLoops += ScopStats.NumValueWritesInLoops;
1391
51
    NumPHIWrites += ScopStats.NumPHIWrites;
1392
51
    NumPHIWritesInLoops += ScopStats.NumPHIWritesInLoops;
1393
51
    NumSingletonWrites += ScopStats.NumSingletonWrites;
1394
51
    NumSingletonWritesInLoops += ScopStats.NumSingletonWritesInLoops;
1395
51
1396
51
    return false;
1397
51
  }
1398
1399
47
  virtual void printScop(raw_ostream &OS, Scop &S) const override {
1400
47
    if (!Impl)
1401
0
      return;
1402
47
    assert(Impl->getScop() == &S);
1403
47
1404
47
    OS << "DeLICM result:\n";
1405
47
    Impl->print(OS);
1406
47
  }
1407
1408
279
  virtual void releaseMemory() override { Impl.reset(); }
1409
};
1410
1411
char DeLICM::ID;
1412
} // anonymous namespace
1413
1414
0
Pass *polly::createDeLICMPass() { return new DeLICM(); }
1415
1416
43.8k
INITIALIZE_PASS_BEGIN(DeLICM, "polly-delicm", "Polly - DeLICM/DePRE", false,
1417
43.8k
                      false)
1418
43.8k
INITIALIZE_PASS_DEPENDENCY(ScopInfoWrapperPass)
1419
43.8k
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
1420
43.8k
INITIALIZE_PASS_END(DeLICM, "polly-delicm", "Polly - DeLICM/DePRE", false,
1421
                    false)
1422
1423
bool polly::isConflicting(
1424
    isl::union_set ExistingOccupied, isl::union_set ExistingUnused,
1425
    isl::union_map ExistingKnown, isl::union_map ExistingWrites,
1426
    isl::union_set ProposedOccupied, isl::union_set ProposedUnused,
1427
    isl::union_map ProposedKnown, isl::union_map ProposedWrites,
1428
232
    llvm::raw_ostream *OS, unsigned Indent) {
1429
232
  Knowledge Existing(std::move(ExistingOccupied), std::move(ExistingUnused),
1430
232
                     std::move(ExistingKnown), std::move(ExistingWrites));
1431
232
  Knowledge Proposed(std::move(ProposedOccupied), std::move(ProposedUnused),
1432
232
                     std::move(ProposedKnown), std::move(ProposedWrites));
1433
232
1434
232
  return Knowledge::isConflicting(Existing, Proposed, OS, Indent);
1435
232
}