Coverage Report

Created: 2018-04-23 18:20

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