Coverage Report

Created: 2017-11-23 03:11

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/polly/lib/Transform/Simplify.cpp
Line
Count
Source (jump to first uncovered line)
1
//===------ Simplify.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
// Simplify a SCoP by removing unnecessary statements and accesses.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "polly/Simplify.h"
15
#include "polly/ScopInfo.h"
16
#include "polly/ScopPass.h"
17
#include "polly/Support/GICHelper.h"
18
#include "polly/Support/ISLOStream.h"
19
#include "polly/Support/ISLTools.h"
20
#include "polly/Support/VirtualInstruction.h"
21
#include "llvm/ADT/Statistic.h"
22
#include "llvm/Support/Debug.h"
23
#define DEBUG_TYPE "polly-simplify"
24
25
using namespace llvm;
26
using namespace polly;
27
28
namespace {
29
30
#define TWO_STATISTICS(VARNAME, DESC)                                          \
31
  static llvm::Statistic VARNAME[2] = {                                        \
32
      {DEBUG_TYPE, #VARNAME "0", DESC " (first)", {0}, false},                 \
33
      {DEBUG_TYPE, #VARNAME "1", DESC " (second)", {0}, false}}
34
35
/// Number of max disjuncts we allow in removeOverwrites(). This is to avoid
36
/// that the analysis of accesses in a statement is becoming too complex. Chosen
37
/// to be relatively small because all the common cases should access only few
38
/// array elements per statement.
39
static int const SimplifyMaxDisjuncts = 4;
40
41
TWO_STATISTICS(ScopsProcessed, "Number of SCoPs processed");
42
TWO_STATISTICS(ScopsModified, "Number of SCoPs simplified");
43
44
TWO_STATISTICS(TotalOverwritesRemoved, "Number of removed overwritten writes");
45
TWO_STATISTICS(TotalWritesCoalesced, "Number of writes coalesced with another");
46
TWO_STATISTICS(TotalRedundantWritesRemoved,
47
               "Number of writes of same value removed in any SCoP");
48
TWO_STATISTICS(TotalEmptyPartialAccessesRemoved,
49
               "Number of empty partial accesses removed");
50
TWO_STATISTICS(TotalDeadAccessesRemoved, "Number of dead accesses removed");
51
TWO_STATISTICS(TotalDeadInstructionsRemoved,
52
               "Number of unused instructions removed");
53
TWO_STATISTICS(TotalStmtsRemoved, "Number of statements removed in any SCoP");
54
55
TWO_STATISTICS(NumValueWrites, "Number of scalar value writes after Simplify");
56
TWO_STATISTICS(
57
    NumValueWritesInLoops,
58
    "Number of scalar value writes nested in affine loops after Simplify");
59
TWO_STATISTICS(NumPHIWrites,
60
               "Number of scalar phi writes after the first simplification");
61
TWO_STATISTICS(
62
    NumPHIWritesInLoops,
63
    "Number of scalar phi writes nested in affine loops after Simplify");
64
TWO_STATISTICS(NumSingletonWrites, "Number of singleton writes after Simplify");
65
TWO_STATISTICS(
66
    NumSingletonWritesInLoops,
67
    "Number of singleton writes nested in affine loops after Simplify");
68
69
815
static bool isImplicitRead(MemoryAccess *MA) {
70
815
  return MA->isRead() && 
MA->isOriginalScalarKind()342
;
71
815
}
72
73
841
static bool isExplicitAccess(MemoryAccess *MA) {
74
841
  return MA->isOriginalArrayKind();
75
841
}
76
77
815
static bool isImplicitWrite(MemoryAccess *MA) {
78
815
  return MA->isWrite() && 
MA->isOriginalScalarKind()473
;
79
815
}
80
81
/// Like isl::union_map::add_map, but may also return an underapproximated
82
/// result if getting too complex.
83
///
84
/// This is implemented by adding disjuncts to the results until the limit is
85
/// reached.
86
static isl::union_map underapproximatedAddMap(isl::union_map UMap,
87
147
                                              isl::map Map) {
88
147
  if (UMap.is_null() || Map.is_null())
89
0
    return {};
90
147
91
147
  isl::map PrevMap = UMap.extract_map(Map.get_space());
92
147
93
147
  // Fast path: If known that we cannot exceed the disjunct limit, just add
94
147
  // them.
95
147
  if (isl_map_n_basic_map(PrevMap.get()) + isl_map_n_basic_map(Map.get()) <=
96
147
      SimplifyMaxDisjuncts)
97
141
    return UMap.add_map(Map);
98
6
99
6
  isl::map Result = isl::map::empty(PrevMap.get_space());
100
24
  PrevMap.foreach_basic_map([&Result](isl::basic_map BMap) -> isl::stat {
101
24
    if (isl_map_n_basic_map(Result.get()) > SimplifyMaxDisjuncts)
102
0
      return isl::stat::error;
103
24
    Result = Result.unite(BMap);
104
24
    return isl::stat::ok;
105
24
  });
106
6
  Map.foreach_basic_map([&Result](isl::basic_map BMap) -> isl::stat {
107
6
    if (isl_map_n_basic_map(Result.get()) > SimplifyMaxDisjuncts)
108
0
      return isl::stat::error;
109
6
    Result = Result.unite(BMap);
110
6
    return isl::stat::ok;
111
6
  });
112
147
113
147
  isl::union_map UResult =
114
147
      UMap.subtract(isl::map::universe(PrevMap.get_space()));
115
147
  UResult.add_map(Result);
116
147
117
147
  return UResult;
118
147
}
119
120
class Simplify : public ScopPass {
121
private:
122
  /// The invocation id (if there are multiple instances in the pass manager's
123
  /// pipeline) to determine which statistics to update.
124
  int CallNo;
125
126
  /// The last/current SCoP that is/has been processed.
127
  Scop *S;
128
129
  /// Number of writes that are overwritten anyway.
130
  int OverwritesRemoved = 0;
131
132
  /// Number of combined writes.
133
  int WritesCoalesced = 0;
134
135
  /// Number of redundant writes removed from this SCoP.
136
  int RedundantWritesRemoved = 0;
137
138
  /// Number of writes with empty access domain removed.
139
  int EmptyPartialAccessesRemoved = 0;
140
141
  /// Number of unused accesses removed from this SCoP.
142
  int DeadAccessesRemoved = 0;
143
144
  /// Number of unused instructions removed from this SCoP.
145
  int DeadInstructionsRemoved = 0;
146
147
  /// Number of unnecessary statements removed from the SCoP.
148
  int StmtsRemoved = 0;
149
150
  /// Return whether at least one simplification has been applied.
151
86
  bool isModified() const {
152
86
    return OverwritesRemoved > 0 || 
WritesCoalesced > 076
||
153
86
           
RedundantWritesRemoved > 066
||
EmptyPartialAccessesRemoved > 053
||
154
86
           
DeadAccessesRemoved > 051
||
DeadInstructionsRemoved > 036
||
155
86
           
StmtsRemoved > 030
;
156
86
  }
157
158
  /// Remove writes that are overwritten unconditionally later in the same
159
  /// statement.
160
  ///
161
  /// There must be no read of the same value between the write (that is to be
162
  /// removed) and the overwrite.
163
44
  void removeOverwrites() {
164
67
    for (auto &Stmt : *S) {
165
67
      isl::set Domain = Stmt.getDomain();
166
67
      isl::union_map WillBeOverwritten =
167
67
          isl::union_map::empty(S->getParamSpace());
168
67
169
67
      SmallVector<MemoryAccess *, 32> Accesses(getAccessesInOrder(Stmt));
170
67
171
67
      // Iterate in reverse order, so the overwrite comes before the write that
172
67
      // is to be removed.
173
226
      for (auto *MA : reverse(Accesses)) {
174
226
175
226
        // In region statements, the explicit accesses can be in blocks that are
176
226
        // can be executed in any order. We therefore process only the implicit
177
226
        // writes and stop after that.
178
226
        if (Stmt.isRegionStmt() && 
isExplicitAccess(MA)13
)
179
8
          break;
180
218
181
218
        auto AccRel = MA->getAccessRelation();
182
218
        AccRel = AccRel.intersect_domain(Domain);
183
218
        AccRel = AccRel.intersect_params(S->getContext());
184
218
185
218
        // If a value is read in-between, do not consider it as overwritten.
186
218
        if (MA->isRead()) {
187
71
          // Invalidate all overwrites for the array it accesses to avoid too
188
71
          // complex isl sets.
189
71
          isl::map AccRelUniv = isl::map::universe(AccRel.get_space());
190
71
          WillBeOverwritten = WillBeOverwritten.subtract(AccRelUniv);
191
71
          continue;
192
71
        }
193
147
194
147
        // If all of a write's elements are overwritten, remove it.
195
147
        isl::union_map AccRelUnion = AccRel;
196
147
        if (AccRelUnion.is_subset(WillBeOverwritten)) {
197
7
          DEBUG(dbgs() << "Removing " << MA
198
7
                       << " which will be overwritten anyway\n");
199
7
200
7
          Stmt.removeSingleMemoryAccess(MA);
201
7
          OverwritesRemoved++;
202
7
          TotalOverwritesRemoved[CallNo]++;
203
7
        }
204
147
205
147
        // Unconditional writes overwrite other values.
206
147
        if (MA->isMustWrite()) {
207
147
          // Avoid too complex isl sets. If necessary, throw away some of the
208
147
          // knowledge.
209
147
          WillBeOverwritten =
210
147
              underapproximatedAddMap(WillBeOverwritten, AccRel);
211
147
        }
212
226
      }
213
67
    }
214
44
  }
215
216
  /// Combine writes that write the same value if possible.
217
  ///
218
  /// This function is able to combine:
219
  /// - Partial writes with disjoint domain.
220
  /// - Writes that write to the same array element.
221
  ///
222
  /// In all cases, both writes must write the same values.
223
44
  void coalesceWrites() {
224
67
    for (auto &Stmt : *S) {
225
67
      isl::set Domain = Stmt.getDomain().intersect_params(S->getContext());
226
67
227
67
      // We let isl do the lookup for the same-value condition. For this, we
228
67
      // wrap llvm::Value into an isl::set such that isl can do the lookup in
229
67
      // its hashtable implementation. llvm::Values are only compared within a
230
67
      // ScopStmt, so the map can be local to this scope. TODO: Refactor with
231
67
      // ZoneAlgorithm::makeValueSet()
232
67
      SmallDenseMap<Value *, isl::set> ValueSets;
233
140
      auto makeValueSet = [&ValueSets, this](Value *V) -> isl::set {
234
140
        assert(V);
235
140
        isl::set &Result = ValueSets[V];
236
140
        if (Result.is_null()) {
237
96
          isl::ctx Ctx = S->getIslCtx();
238
96
          std::string Name =
239
96
              getIslCompatibleName("Val", V, ValueSets.size() - 1,
240
96
                                   std::string(), UseInstructionNames);
241
96
          isl::id Id = isl::id::alloc(Ctx, Name, V);
242
96
          Result = isl::set::universe(
243
96
              isl::space(Ctx, 0, 0).set_tuple_id(isl::dim::set, Id));
244
96
        }
245
140
        return Result;
246
140
      };
247
67
248
67
      // List of all eligible (for coalescing) writes of the future.
249
67
      // { [Domain[] -> Element[]] -> [Value[] -> MemoryAccess[]] }
250
67
      isl::union_map FutureWrites = isl::union_map::empty(S->getParamSpace());
251
67
252
67
      // Iterate over accesses from the last to the first.
253
67
      SmallVector<MemoryAccess *, 32> Accesses(getAccessesInOrder(Stmt));
254
219
      for (MemoryAccess *MA : reverse(Accesses)) {
255
219
        // In region statements, the explicit accesses can be in blocks that can
256
219
        // be executed in any order. We therefore process only the implicit
257
219
        // writes and stop after that.
258
219
        if (Stmt.isRegionStmt() && 
isExplicitAccess(MA)13
)
259
8
          break;
260
211
261
211
        // { Domain[] -> Element[] }
262
211
        isl::map AccRel =
263
211
            MA->getLatestAccessRelation().intersect_domain(Domain);
264
211
265
211
        // { [Domain[] -> Element[]] }
266
211
        isl::set AccRelWrapped = AccRel.wrap();
267
211
268
211
        // { Value[] }
269
211
        isl::set ValSet;
270
211
271
211
        if (MA->isMustWrite() && 
(140
MA->isOriginalScalarKind()140
||
272
140
                                  
isa<StoreInst>(MA->getAccessInstruction())112
)) {
273
140
          // Normally, tryGetValueStored() should be used to determine which
274
140
          // element is written, but it can return nullptr; For PHI accesses,
275
140
          // getAccessValue() returns the PHI instead of the PHI's incoming
276
140
          // value. In this case, where we only compare values of a single
277
140
          // statement, this is fine, because within a statement, a PHI in a
278
140
          // successor block has always the same value as the incoming write. We
279
140
          // still preferably use the incoming value directly so we also catch
280
140
          // direct uses of that.
281
140
          Value *StoredVal = MA->tryGetValueStored();
282
140
          if (!StoredVal)
283
1
            StoredVal = MA->getAccessValue();
284
140
          ValSet = makeValueSet(StoredVal);
285
140
286
140
          // { Domain[] }
287
140
          isl::set AccDomain = AccRel.domain();
288
140
289
140
          // Parts of the statement's domain that is not written by this access.
290
140
          isl::set UndefDomain = Domain.subtract(AccDomain);
291
140
292
140
          // { Element[] }
293
140
          isl::set ElementUniverse =
294
140
              isl::set::universe(AccRel.get_space().range());
295
140
296
140
          // { Domain[] -> Element[] }
297
140
          isl::map UndefAnything =
298
140
              isl::map::from_domain_and_range(UndefDomain, ElementUniverse);
299
140
300
140
          // We are looking a compatible write access. The other write can
301
140
          // access these elements...
302
140
          isl::map AllowedAccesses = AccRel.unite(UndefAnything);
303
140
304
140
          // ... and must write the same value.
305
140
          // { [Domain[] -> Element[]] -> Value[] }
306
140
          isl::map Filter =
307
140
              isl::map::from_domain_and_range(AllowedAccesses.wrap(), ValSet);
308
140
309
140
          // Lookup future write that fulfills these conditions.
310
140
          // { [[Domain[] -> Element[]] -> Value[]] -> MemoryAccess[] }
311
140
          isl::union_map Filtered =
312
140
              FutureWrites.uncurry().intersect_domain(Filter.wrap());
313
140
314
140
          // Iterate through the candidates.
315
140
          Filtered.foreach_map([&, this](isl::map Map) -> isl::stat {
316
39
            MemoryAccess *OtherMA = (MemoryAccess *)Map.get_space()
317
39
                                        .get_tuple_id(isl::dim::out)
318
39
                                        .get_user();
319
39
320
39
            isl::map OtherAccRel =
321
39
                OtherMA->getLatestAccessRelation().intersect_domain(Domain);
322
39
323
39
            // The filter only guaranteed that some of OtherMA's accessed
324
39
            // elements are allowed. Verify that it only accesses allowed
325
39
            // elements. Otherwise, continue with the next candidate.
326
39
            if (!OtherAccRel.is_subset(AllowedAccesses).is_true())
327
32
              return isl::stat::ok;
328
7
329
7
            // The combined access relation.
330
7
            // { Domain[] -> Element[] }
331
7
            isl::map NewAccRel = AccRel.unite(OtherAccRel);
332
7
            simplify(NewAccRel);
333
7
334
7
            // Carry out the coalescing.
335
7
            Stmt.removeSingleMemoryAccess(MA);
336
7
            OtherMA->setNewAccessRelation(NewAccRel);
337
7
338
7
            // We removed MA, OtherMA takes its role.
339
7
            MA = OtherMA;
340
7
341
7
            TotalWritesCoalesced[CallNo]++;
342
7
            WritesCoalesced++;
343
7
344
7
            // Don't look for more candidates.
345
7
            return isl::stat::error;
346
7
          });
347
140
        }
348
211
349
211
        // Two writes cannot be coalesced if there is another access (to some of
350
211
        // the written elements) between them. Remove all visited write accesses
351
211
        // from the list of eligible writes. Don't just remove the accessed
352
211
        // elements, but any MemoryAccess that touches any of the invalidated
353
211
        // elements.
354
211
        SmallPtrSet<MemoryAccess *, 2> TouchedAccesses;
355
211
        FutureWrites.intersect_domain(AccRelWrapped)
356
211
            .foreach_map([&TouchedAccesses](isl::map Map) -> isl::stat {
357
87
              MemoryAccess *MA = (MemoryAccess *)Map.get_space()
358
87
                                     .range()
359
87
                                     .unwrap()
360
87
                                     .get_tuple_id(isl::dim::out)
361
87
                                     .get_user();
362
87
              TouchedAccesses.insert(MA);
363
87
              return isl::stat::ok;
364
87
            });
365
211
        isl::union_map NewFutureWrites =
366
211
            isl::union_map::empty(FutureWrites.get_space());
367
211
        FutureWrites.foreach_map([&TouchedAccesses, &NewFutureWrites](
368
211
                                     isl::map FutureWrite) -> isl::stat {
369
127
          MemoryAccess *MA = (MemoryAccess *)FutureWrite.get_space()
370
127
                                 .range()
371
127
                                 .unwrap()
372
127
                                 .get_tuple_id(isl::dim::out)
373
127
                                 .get_user();
374
127
          if (!TouchedAccesses.count(MA))
375
40
            NewFutureWrites = NewFutureWrites.add_map(FutureWrite);
376
127
          return isl::stat::ok;
377
127
        });
378
211
        FutureWrites = NewFutureWrites;
379
211
380
211
        if (MA->isMustWrite() && 
!ValSet.is_null()140
) {
381
140
          // { MemoryAccess[] }
382
140
          auto AccSet =
383
140
              isl::set::universe(isl::space(S->getIslCtx(), 0, 0)
384
140
                                     .set_tuple_id(isl::dim::set, MA->getId()));
385
140
386
140
          // { Val[] -> MemoryAccess[] }
387
140
          isl::map ValAccSet = isl::map::from_domain_and_range(ValSet, AccSet);
388
140
389
140
          // { [Domain[] -> Element[]] -> [Value[] -> MemoryAccess[]] }
390
140
          isl::map AccRelValAcc =
391
140
              isl::map::from_domain_and_range(AccRelWrapped, ValAccSet.wrap());
392
140
          FutureWrites = FutureWrites.add_map(AccRelValAcc);
393
140
        }
394
219
      }
395
67
    }
396
44
  }
397
398
  /// Remove writes that just write the same value already stored in the
399
  /// element.
400
44
  void removeRedundantWrites() {
401
67
    for (auto &Stmt : *S) {
402
67
      SmallDenseMap<Value *, isl::set> ValueSets;
403
214
      auto makeValueSet = [&ValueSets, this](Value *V) -> isl::set {
404
214
        assert(V);
405
214
        isl::set &Result = ValueSets[V];
406
214
        if (Result.is_null()) {
407
122
          isl_ctx *Ctx = S->getIslCtx().get();
408
122
          std::string Name =
409
122
              getIslCompatibleName("Val", V, ValueSets.size() - 1,
410
122
                                   std::string(), UseInstructionNames);
411
122
          isl::id Id = give(isl_id_alloc(Ctx, Name.c_str(), V));
412
122
          Result = isl::set::universe(
413
122
              isl::space(Ctx, 0, 0).set_tuple_id(isl::dim::set, Id));
414
122
        }
415
214
        return Result;
416
214
      };
417
67
418
67
      isl::set Domain = Stmt.getDomain();
419
67
      Domain = Domain.intersect_params(S->getContext());
420
67
421
67
      // List of element reads that still have the same value while iterating
422
67
      // through the MemoryAccesses.
423
67
      // { [Domain[] -> Element[]] -> Val[] }
424
67
      isl::union_map Known = isl::union_map::empty(S->getParamSpace());
425
67
426
67
      SmallVector<MemoryAccess *, 32> Accesses(getAccessesInOrder(Stmt));
427
222
      for (MemoryAccess *MA : Accesses) {
428
222
        // Is the memory access in a defined order relative to the other
429
222
        // accesses? In region statements, only the first and the last accesses
430
222
        // have defined order. Execution of those in the middle may depend on
431
222
        // runtime conditions an therefore cannot be modified.
432
222
        bool IsOrdered =
433
222
            Stmt.isBlockStmt() || 
MA->isOriginalScalarKind()23
||
434
222
            
(14
!S->getBoxedLoops().size()14
&&
MA->getAccessInstruction()12
&&
435
14
             
Stmt.getEntryBlock() == MA->getAccessInstruction()->getParent()12
);
436
222
437
222
        isl::map AccRel = MA->getAccessRelation();
438
222
        AccRel = AccRel.intersect_domain(Domain);
439
222
        isl::set AccRelWrapped = AccRel.wrap();
440
222
441
222
        // Determine whether a write is redundant (stores only values that are
442
222
        // already present in the written array elements) and remove it if this
443
222
        // is the case.
444
222
        if (IsOrdered && 
MA->isMustWrite()214
&&
445
222
            
(133
isa<StoreInst>(MA->getAccessInstruction())133
||
446
133
             
MA->isOriginalScalarKind()27
)) {
447
133
          Value *StoredVal = MA->tryGetValueStored();
448
133
          if (!StoredVal)
449
1
            StoredVal = MA->getAccessValue();
450
133
451
133
          if (StoredVal) {
452
133
            // Lookup in the set of known values.
453
133
            isl::map AccRelStoredVal = isl::map::from_domain_and_range(
454
133
                AccRelWrapped, makeValueSet(StoredVal));
455
133
            if (isl::union_map(AccRelStoredVal).is_subset(Known)) {
456
15
              DEBUG(dbgs() << "Cleanup of " << MA << ":\n");
457
15
              DEBUG(dbgs() << "      Scalar: " << *StoredVal << "\n");
458
15
              DEBUG(dbgs() << "      AccRel: " << AccRel << "\n");
459
15
460
15
              Stmt.removeSingleMemoryAccess(MA);
461
15
462
15
              RedundantWritesRemoved++;
463
15
              TotalRedundantWritesRemoved[CallNo]++;
464
15
            }
465
133
          }
466
133
        }
467
222
468
222
        // Update the know values set.
469
222
        if (MA->isRead()) {
470
81
          // Loaded values are the currently known values of the array element
471
81
          // it was loaded from.
472
81
          Value *LoadedVal = MA->getAccessValue();
473
81
          if (LoadedVal && IsOrdered) {
474
81
            isl::map AccRelVal = isl::map::from_domain_and_range(
475
81
                AccRelWrapped, makeValueSet(LoadedVal));
476
81
477
81
            Known = Known.add_map(AccRelVal);
478
81
          }
479
141
        } else if (MA->isWrite()) {
480
141
          // Remove (possibly) overwritten values from the known elements set.
481
141
          // We remove all elements of the accessed array to avoid too complex
482
141
          // isl sets.
483
141
          isl::set AccRelUniv = isl::set::universe(AccRelWrapped.get_space());
484
141
          Known = Known.subtract_domain(AccRelUniv);
485
141
486
141
          // At this point, we could add the written value of must-writes.
487
141
          // However, writing same values is already handled by
488
141
          // coalesceWrites().
489
141
        }
490
222
      }
491
67
    }
492
44
  }
493
494
  /// Remove statements without side effects.
495
44
  void removeUnnecessaryStmts() {
496
44
    auto NumStmtsBefore = S->getSize();
497
44
    S->simplifySCoP(true);
498
44
    assert(NumStmtsBefore >= S->getSize());
499
44
    StmtsRemoved = NumStmtsBefore - S->getSize();
500
44
    DEBUG(dbgs() << "Removed " << StmtsRemoved << " (of " << NumStmtsBefore
501
44
                 << ") statements\n");
502
44
    TotalStmtsRemoved[CallNo] += StmtsRemoved;
503
44
  }
504
505
  /// Remove accesses that have an empty domain.
506
44
  void removeEmptyPartialAccesses() {
507
67
    for (ScopStmt &Stmt : *S) {
508
67
      // Defer the actual removal to not invalidate iterators.
509
67
      SmallVector<MemoryAccess *, 8> DeferredRemove;
510
67
511
237
      for (MemoryAccess *MA : Stmt) {
512
237
        if (!MA->isWrite())
513
81
          continue;
514
156
515
156
        isl::map AccRel = MA->getAccessRelation();
516
156
        if (!AccRel.is_empty().is_true())
517
155
          continue;
518
1
519
1
        DEBUG(dbgs() << "Removing " << MA
520
1
                     << " because it's a partial access that never occurs\n");
521
1
        DeferredRemove.push_back(MA);
522
1
      }
523
67
524
67
      for (MemoryAccess *MA : DeferredRemove) {
525
1
        Stmt.removeSingleMemoryAccess(MA);
526
1
        EmptyPartialAccessesRemoved++;
527
1
        TotalEmptyPartialAccessesRemoved[CallNo]++;
528
1
      }
529
67
    }
530
44
  }
531
532
  /// Mark all reachable instructions and access, and sweep those that are not
533
  /// reachable.
534
44
  void markAndSweep(LoopInfo *LI) {
535
44
    DenseSet<MemoryAccess *> UsedMA;
536
44
    DenseSet<VirtualInstruction> UsedInsts;
537
44
538
44
    // Get all reachable instructions and accesses.
539
44
    markReachable(S, LI, UsedInsts, UsedMA);
540
44
541
44
    // Remove all non-reachable accesses.
542
44
    // We need get all MemoryAccesses first, in order to not invalidate the
543
44
    // iterators when removing them.
544
44
    SmallVector<MemoryAccess *, 64> AllMAs;
545
44
    for (ScopStmt &Stmt : *S)
546
67
      AllMAs.append(Stmt.begin(), Stmt.end());
547
44
548
207
    for (MemoryAccess *MA : AllMAs) {
549
207
      if (UsedMA.count(MA))
550
182
        continue;
551
25
      DEBUG(dbgs() << "Removing " << MA << " because its value is not used\n");
552
25
      ScopStmt *Stmt = MA->getStatement();
553
25
      Stmt->removeSingleMemoryAccess(MA);
554
25
555
25
      DeadAccessesRemoved++;
556
25
      TotalDeadAccessesRemoved[CallNo]++;
557
25
    }
558
44
559
44
    // Remove all non-reachable instructions.
560
67
    for (ScopStmt &Stmt : *S) {
561
67
      // Note that for region statements, we can only remove the non-terminator
562
67
      // instructions of the entry block. All other instructions are not in the
563
67
      // instructions list, but implicitly always part of the statement.
564
67
565
67
      SmallVector<Instruction *, 32> AllInsts(Stmt.insts_begin(),
566
67
                                              Stmt.insts_end());
567
67
      SmallVector<Instruction *, 32> RemainInsts;
568
67
569
216
      for (Instruction *Inst : AllInsts) {
570
216
        auto It = UsedInsts.find({&Stmt, Inst});
571
216
        if (It == UsedInsts.end()) {
572
43
          DEBUG(dbgs() << "Removing "; Inst->print(dbgs());
573
43
                dbgs() << " because it is not used\n");
574
43
          DeadInstructionsRemoved++;
575
43
          TotalDeadInstructionsRemoved[CallNo]++;
576
43
          continue;
577
43
        }
578
173
579
173
        RemainInsts.push_back(Inst);
580
173
581
173
        // If instructions appear multiple times, keep only the first.
582
173
        UsedInsts.erase(It);
583
173
      }
584
67
585
67
      // Set the new instruction list to be only those we did not remove.
586
67
      Stmt.setInstructions(RemainInsts);
587
67
    }
588
44
  }
589
590
  /// Print simplification statistics to @p OS.
591
42
  void printStatistics(llvm::raw_ostream &OS, int Indent = 0) const {
592
42
    OS.indent(Indent) << "Statistics {\n";
593
42
    OS.indent(Indent + 4) << "Overwrites removed: " << OverwritesRemoved
594
42
                          << '\n';
595
42
    OS.indent(Indent + 4) << "Partial writes coalesced: " << WritesCoalesced
596
42
                          << "\n";
597
42
    OS.indent(Indent + 4) << "Redundant writes removed: "
598
42
                          << RedundantWritesRemoved << "\n";
599
42
    OS.indent(Indent + 4) << "Accesses with empty domains removed: "
600
42
                          << EmptyPartialAccessesRemoved << "\n";
601
42
    OS.indent(Indent + 4) << "Dead accesses removed: " << DeadAccessesRemoved
602
42
                          << '\n';
603
42
    OS.indent(Indent + 4) << "Dead instructions removed: "
604
42
                          << DeadInstructionsRemoved << '\n';
605
42
    OS.indent(Indent + 4) << "Stmts removed: " << StmtsRemoved << "\n";
606
42
    OS.indent(Indent) << "}\n";
607
42
  }
608
609
  /// Print the current state of all MemoryAccesses to @p OS.
610
27
  void printAccesses(llvm::raw_ostream &OS, int Indent = 0) const {
611
27
    OS.indent(Indent) << "After accesses {\n";
612
27
    for (auto &Stmt : *S) {
613
27
      OS.indent(Indent + 4) << Stmt.getBaseName() << "\n";
614
27
      for (auto *MA : Stmt)
615
44
        MA->print(OS);
616
27
    }
617
27
    OS.indent(Indent) << "}\n";
618
27
  }
619
620
public:
621
  static char ID;
622
44
  explicit Simplify(int CallNo = 0) : ScopPass(ID), CallNo(CallNo) {}
623
624
44
  virtual void getAnalysisUsage(AnalysisUsage &AU) const override {
625
44
    AU.addRequiredTransitive<ScopInfoRegionPass>();
626
44
    AU.addRequired<LoopInfoWrapperPass>();
627
44
    AU.setPreservesAll();
628
44
  }
629
630
44
  virtual bool runOnScop(Scop &S) override {
631
44
    // Reset statistics of last processed SCoP.
632
44
    releaseMemory();
633
44
    assert(!isModified());
634
44
635
44
    // Prepare processing of this SCoP.
636
44
    this->S = &S;
637
44
    ScopsProcessed[CallNo]++;
638
44
639
44
    DEBUG(dbgs() << "Removing partial writes that never happen...\n");
640
44
    removeEmptyPartialAccesses();
641
44
642
44
    DEBUG(dbgs() << "Removing overwrites...\n");
643
44
    removeOverwrites();
644
44
645
44
    DEBUG(dbgs() << "Coalesce partial writes...\n");
646
44
    coalesceWrites();
647
44
648
44
    DEBUG(dbgs() << "Removing redundant writes...\n");
649
44
    removeRedundantWrites();
650
44
651
44
    DEBUG(dbgs() << "Cleanup unused accesses...\n");
652
44
    LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
653
44
    markAndSweep(LI);
654
44
655
44
    DEBUG(dbgs() << "Removing statements without side effects...\n");
656
44
    removeUnnecessaryStmts();
657
44
658
44
    if (isModified())
659
29
      ScopsModified[CallNo]++;
660
44
    DEBUG(dbgs() << "\nFinal Scop:\n");
661
44
    DEBUG(dbgs() << S);
662
44
663
44
    auto ScopStats = S.getStatistics();
664
44
    NumValueWrites[CallNo] += ScopStats.NumValueWrites;
665
44
    NumValueWritesInLoops[CallNo] += ScopStats.NumValueWritesInLoops;
666
44
    NumPHIWrites[CallNo] += ScopStats.NumPHIWrites;
667
44
    NumPHIWritesInLoops[CallNo] += ScopStats.NumPHIWritesInLoops;
668
44
    NumSingletonWrites[CallNo] += ScopStats.NumSingletonWrites;
669
44
    NumSingletonWritesInLoops[CallNo] += ScopStats.NumSingletonWritesInLoops;
670
44
671
44
    return false;
672
44
  }
673
674
42
  virtual void printScop(raw_ostream &OS, Scop &S) const override {
675
42
    assert(&S == this->S &&
676
42
           "Can only print analysis for the last processed SCoP");
677
42
    printStatistics(OS);
678
42
679
42
    if (!isModified()) {
680
15
      OS << "SCoP could not be simplified\n";
681
15
      return;
682
15
    }
683
27
    printAccesses(OS);
684
27
  }
685
686
194
  virtual void releaseMemory() override {
687
194
    S = nullptr;
688
194
689
194
    OverwritesRemoved = 0;
690
194
    WritesCoalesced = 0;
691
194
    RedundantWritesRemoved = 0;
692
194
    EmptyPartialAccessesRemoved = 0;
693
194
    DeadAccessesRemoved = 0;
694
194
    DeadInstructionsRemoved = 0;
695
194
    StmtsRemoved = 0;
696
194
  }
697
};
698
699
char Simplify::ID;
700
} // anonymous namespace
701
702
namespace polly {
703
230
SmallVector<MemoryAccess *, 32> getAccessesInOrder(ScopStmt &Stmt) {
704
230
705
230
  SmallVector<MemoryAccess *, 32> Accesses;
706
230
707
230
  for (MemoryAccess *MemAcc : Stmt)
708
815
    if (isImplicitRead(MemAcc))
709
97
      Accesses.push_back(MemAcc);
710
230
711
230
  for (MemoryAccess *MemAcc : Stmt)
712
815
    if (isExplicitAccess(MemAcc))
713
632
      Accesses.push_back(MemAcc);
714
230
715
230
  for (MemoryAccess *MemAcc : Stmt)
716
815
    if (isImplicitWrite(MemAcc))
717
86
      Accesses.push_back(MemAcc);
718
230
719
230
  return Accesses;
720
230
}
721
} // namespace polly
722
723
0
Pass *polly::createSimplifyPass(int CallNo) { return new Simplify(CallNo); }
724
725
37.3k
INITIALIZE_PASS_BEGIN(Simplify, "polly-simplify", "Polly - Simplify", false,
726
37.3k
                      false)
727
37.3k
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
728
37.3k
INITIALIZE_PASS_END(Simplify, "polly-simplify", "Polly - Simplify", false,
729
                    false)