Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/Analysis/MemorySSA.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- MemorySSA.cpp - Memory SSA Builder ---------------------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This file implements the MemorySSA class.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "llvm/Analysis/MemorySSA.h"
14
#include "llvm/ADT/DenseMap.h"
15
#include "llvm/ADT/DenseMapInfo.h"
16
#include "llvm/ADT/DenseSet.h"
17
#include "llvm/ADT/DepthFirstIterator.h"
18
#include "llvm/ADT/Hashing.h"
19
#include "llvm/ADT/None.h"
20
#include "llvm/ADT/Optional.h"
21
#include "llvm/ADT/STLExtras.h"
22
#include "llvm/ADT/SmallPtrSet.h"
23
#include "llvm/ADT/SmallVector.h"
24
#include "llvm/ADT/iterator.h"
25
#include "llvm/ADT/iterator_range.h"
26
#include "llvm/Analysis/AliasAnalysis.h"
27
#include "llvm/Analysis/IteratedDominanceFrontier.h"
28
#include "llvm/Analysis/MemoryLocation.h"
29
#include "llvm/Config/llvm-config.h"
30
#include "llvm/IR/AssemblyAnnotationWriter.h"
31
#include "llvm/IR/BasicBlock.h"
32
#include "llvm/IR/Dominators.h"
33
#include "llvm/IR/Function.h"
34
#include "llvm/IR/Instruction.h"
35
#include "llvm/IR/Instructions.h"
36
#include "llvm/IR/IntrinsicInst.h"
37
#include "llvm/IR/Intrinsics.h"
38
#include "llvm/IR/LLVMContext.h"
39
#include "llvm/IR/PassManager.h"
40
#include "llvm/IR/Use.h"
41
#include "llvm/Pass.h"
42
#include "llvm/Support/AtomicOrdering.h"
43
#include "llvm/Support/Casting.h"
44
#include "llvm/Support/CommandLine.h"
45
#include "llvm/Support/Compiler.h"
46
#include "llvm/Support/Debug.h"
47
#include "llvm/Support/ErrorHandling.h"
48
#include "llvm/Support/FormattedStream.h"
49
#include "llvm/Support/raw_ostream.h"
50
#include <algorithm>
51
#include <cassert>
52
#include <iterator>
53
#include <memory>
54
#include <utility>
55
56
using namespace llvm;
57
58
#define DEBUG_TYPE "memoryssa"
59
60
49.7k
INITIALIZE_PASS_BEGIN(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
61
49.7k
                      true)
62
49.7k
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
63
49.7k
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
64
49.7k
INITIALIZE_PASS_END(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
65
                    true)
66
67
11.0k
INITIALIZE_PASS_BEGIN(MemorySSAPrinterLegacyPass, "print-memoryssa",
68
11.0k
                      "Memory SSA Printer", false, false)
69
11.0k
INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
70
11.0k
INITIALIZE_PASS_END(MemorySSAPrinterLegacyPass, "print-memoryssa",
71
                    "Memory SSA Printer", false, false)
72
73
static cl::opt<unsigned> MaxCheckLimit(
74
    "memssa-check-limit", cl::Hidden, cl::init(100),
75
    cl::desc("The maximum number of stores/phis MemorySSA"
76
             "will consider trying to walk past (default = 100)"));
77
78
// Always verify MemorySSA if expensive checking is enabled.
79
#ifdef EXPENSIVE_CHECKS
80
bool llvm::VerifyMemorySSA = true;
81
#else
82
bool llvm::VerifyMemorySSA = false;
83
#endif
84
/// Enables memory ssa as a dependency for loop passes in legacy pass manager.
85
cl::opt<bool> llvm::EnableMSSALoopDependency(
86
    "enable-mssa-loop-dependency", cl::Hidden, cl::init(false),
87
    cl::desc("Enable MemorySSA dependency for loop pass manager"));
88
89
static cl::opt<bool, true>
90
    VerifyMemorySSAX("verify-memoryssa", cl::location(VerifyMemorySSA),
91
                     cl::Hidden, cl::desc("Enable verification of MemorySSA."));
92
93
namespace llvm {
94
95
/// An assembly annotator class to print Memory SSA information in
96
/// comments.
97
class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter {
98
  friend class MemorySSA;
99
100
  const MemorySSA *MSSA;
101
102
public:
103
100
  MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {}
104
105
  void emitBasicBlockStartAnnot(const BasicBlock *BB,
106
288
                                formatted_raw_ostream &OS) override {
107
288
    if (MemoryAccess *MA = MSSA->getMemoryAccess(BB))
108
97
      OS << "; " << *MA << "\n";
109
288
  }
110
111
  void emitInstructionAnnot(const Instruction *I,
112
909
                            formatted_raw_ostream &OS) override {
113
909
    if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
114
465
      OS << "; " << *MA << "\n";
115
909
  }
116
};
117
118
} // end namespace llvm
119
120
namespace {
121
122
/// Our current alias analysis API differentiates heavily between calls and
123
/// non-calls, and functions called on one usually assert on the other.
124
/// This class encapsulates the distinction to simplify other code that wants
125
/// "Memory affecting instructions and related data" to use as a key.
126
/// For example, this class is used as a densemap key in the use optimizer.
127
class MemoryLocOrCall {
128
public:
129
  bool IsCall = false;
130
131
  MemoryLocOrCall(MemoryUseOrDef *MUD)
132
3.09M
      : MemoryLocOrCall(MUD->getMemoryInst()) {}
133
  MemoryLocOrCall(const MemoryUseOrDef *MUD)
134
1
      : MemoryLocOrCall(MUD->getMemoryInst()) {}
135
136
3.09M
  MemoryLocOrCall(Instruction *Inst) {
137
3.09M
    if (auto *C = dyn_cast<CallBase>(Inst)) {
138
70.7k
      IsCall = true;
139
70.7k
      Call = C;
140
3.02M
    } else {
141
3.02M
      IsCall = false;
142
3.02M
      // There is no such thing as a memorylocation for a fence inst, and it is
143
3.02M
      // unique in that regard.
144
3.02M
      if (!isa<FenceInst>(Inst))
145
3.02M
        Loc = MemoryLocation::get(Inst);
146
3.02M
    }
147
3.09M
  }
148
149
11.2M
  explicit MemoryLocOrCall(const MemoryLocation &Loc) : Loc(Loc) {}
150
151
177k
  const CallBase *getCall() const {
152
177k
    assert(IsCall);
153
177k
    return Call;
154
177k
  }
155
156
8.20M
  MemoryLocation getLoc() const {
157
8.20M
    assert(!IsCall);
158
8.20M
    return Loc;
159
8.20M
  }
160
161
43.4M
  bool operator==(const MemoryLocOrCall &Other) const {
162
43.4M
    if (IsCall != Other.IsCall)
163
331k
      return false;
164
43.1M
165
43.1M
    if (!IsCall)
166
43.0M
      return Loc == Other.Loc;
167
21.9k
168
21.9k
    if (Call->getCalledValue() != Other.Call->getCalledValue())
169
800
      return false;
170
21.1k
171
21.1k
    return Call->arg_size() == Other.Call->arg_size() &&
172
21.1k
           std::equal(Call->arg_begin(), Call->arg_end(),
173
21.1k
                      Other.Call->arg_begin());
174
21.1k
  }
175
176
private:
177
  union {
178
    const CallBase *Call;
179
    MemoryLocation Loc;
180
  };
181
};
182
183
} // end anonymous namespace
184
185
namespace llvm {
186
187
template <> struct DenseMapInfo<MemoryLocOrCall> {
188
7.14M
  static inline MemoryLocOrCall getEmptyKey() {
189
7.14M
    return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getEmptyKey());
190
7.14M
  }
191
192
4.11M
  static inline MemoryLocOrCall getTombstoneKey() {
193
4.11M
    return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getTombstoneKey());
194
4.11M
  }
195
196
3.72M
  static unsigned getHashValue(const MemoryLocOrCall &MLOC) {
197
3.72M
    if (!MLOC.IsCall)
198
3.63M
      return hash_combine(
199
3.63M
          MLOC.IsCall,
200
3.63M
          DenseMapInfo<MemoryLocation>::getHashValue(MLOC.getLoc()));
201
88.7k
202
88.7k
    hash_code hash =
203
88.7k
        hash_combine(MLOC.IsCall, DenseMapInfo<const Value *>::getHashValue(
204
88.7k
                                      MLOC.getCall()->getCalledValue()));
205
88.7k
206
88.7k
    for (const Value *Arg : MLOC.getCall()->args())
207
138k
      hash = hash_combine(hash, DenseMapInfo<const Value *>::getHashValue(Arg));
208
88.7k
    return hash;
209
88.7k
  }
210
211
43.4M
  static bool isEqual(const MemoryLocOrCall &LHS, const MemoryLocOrCall &RHS) {
212
43.4M
    return LHS == RHS;
213
43.4M
  }
214
};
215
216
} // end namespace llvm
217
218
/// This does one-way checks to see if Use could theoretically be hoisted above
219
/// MayClobber. This will not check the other way around.
220
///
221
/// This assumes that, for the purposes of MemorySSA, Use comes directly after
222
/// MayClobber, with no potentially clobbering operations in between them.
223
/// (Where potentially clobbering ops are memory barriers, aliased stores, etc.)
224
static bool areLoadsReorderable(const LoadInst *Use,
225
16.5k
                                const LoadInst *MayClobber) {
226
16.5k
  bool VolatileUse = Use->isVolatile();
227
16.5k
  bool VolatileClobber = MayClobber->isVolatile();
228
16.5k
  // Volatile operations may never be reordered with other volatile operations.
229
16.5k
  if (VolatileUse && 
VolatileClobber0
)
230
0
    return false;
231
16.5k
  // Otherwise, volatile doesn't matter here. From the language reference:
232
16.5k
  // 'optimizers may change the order of volatile operations relative to
233
16.5k
  // non-volatile operations.'"
234
16.5k
235
16.5k
  // If a load is seq_cst, it cannot be moved above other loads. If its ordering
236
16.5k
  // is weaker, it can be moved above other loads. We just need to be sure that
237
16.5k
  // MayClobber isn't an acquire load, because loads can't be moved above
238
16.5k
  // acquire loads.
239
16.5k
  //
240
16.5k
  // Note that this explicitly *does* allow the free reordering of monotonic (or
241
16.5k
  // weaker) loads of the same address.
242
16.5k
  bool SeqCstUse = Use->getOrdering() == AtomicOrdering::SequentiallyConsistent;
243
16.5k
  bool MayClobberIsAcquire = isAtLeastOrStrongerThan(MayClobber->getOrdering(),
244
16.5k
                                                     AtomicOrdering::Acquire);
245
16.5k
  return !(SeqCstUse || MayClobberIsAcquire);
246
16.5k
}
247
248
namespace {
249
250
struct ClobberAlias {
251
  bool IsClobber;
252
  Optional<AliasResult> AR;
253
};
254
255
} // end anonymous namespace
256
257
// Return a pair of {IsClobber (bool), AR (AliasResult)}. It relies on AR being
258
// ignored if IsClobber = false.
259
template <typename AliasAnalysisType>
260
static ClobberAlias
261
instructionClobbersQuery(const MemoryDef *MD, const MemoryLocation &UseLoc,
262
6.25M
                         const Instruction *UseInst, AliasAnalysisType &AA) {
263
6.25M
  Instruction *DefInst = MD->getMemoryInst();
264
6.25M
  assert(DefInst && "Defining instruction not actually an instruction");
265
6.25M
  const auto *UseCall = dyn_cast<CallBase>(UseInst);
266
6.25M
  Optional<AliasResult> AR;
267
6.25M
268
6.25M
  if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) {
269
403k
    // These intrinsics will show up as affecting memory, but they are just
270
403k
    // markers, mostly.
271
403k
    //
272
403k
    // FIXME: We probably don't actually want MemorySSA to model these at all
273
403k
    // (including creating MemoryAccesses for them): we just end up inventing
274
403k
    // clobbers where they don't really exist at all. Please see D43269 for
275
403k
    // context.
276
403k
    switch (II->getIntrinsicID()) {
277
403k
    case Intrinsic::lifetime_start:
278
152k
      if (UseCall)
279
2.12k
        return {false, NoAlias};
280
149k
      AR = AA.alias(MemoryLocation(II->getArgOperand(1)), UseLoc);
281
149k
      return {AR != NoAlias, AR};
282
149k
    case Intrinsic::lifetime_end:
283
121k
    case Intrinsic::invariant_start:
284
121k
    case Intrinsic::invariant_end:
285
121k
    case Intrinsic::assume:
286
121k
      return {false, NoAlias};
287
129k
    default:
288
129k
      break;
289
5.97M
    }
290
5.97M
  }
291
5.97M
292
5.97M
  if (UseCall) {
293
44.1k
    ModRefInfo I = AA.getModRefInfo(DefInst, UseCall);
294
44.1k
    AR = isMustSet(I) ? 
MustAlias84
:
MayAlias44.0k
;
295
44.1k
    return {isModOrRefSet(I), AR};
296
44.1k
  }
297
5.93M
298
5.93M
  if (auto *DefLoad = dyn_cast<LoadInst>(DefInst))
299
16.5k
    if (auto *UseLoad = dyn_cast<LoadInst>(UseInst))
300
16.5k
      return {!areLoadsReorderable(UseLoad, DefLoad), MayAlias};
301
5.91M
302
5.91M
  ModRefInfo I = AA.getModRefInfo(DefInst, UseLoc);
303
5.91M
  AR = isMustSet(I) ? 
MustAlias65.2k
:
MayAlias5.85M
;
304
5.91M
  return {isModSet(I), AR};
305
5.91M
}
MemorySSA.cpp:(anonymous namespace)::ClobberAlias instructionClobbersQuery<llvm::BatchAAResults>(llvm::MemoryDef const*, llvm::MemoryLocation const&, llvm::Instruction const*, llvm::BatchAAResults&)
Line
Count
Source
262
6.08M
                         const Instruction *UseInst, AliasAnalysisType &AA) {
263
6.08M
  Instruction *DefInst = MD->getMemoryInst();
264
6.08M
  assert(DefInst && "Defining instruction not actually an instruction");
265
6.08M
  const auto *UseCall = dyn_cast<CallBase>(UseInst);
266
6.08M
  Optional<AliasResult> AR;
267
6.08M
268
6.08M
  if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) {
269
392k
    // These intrinsics will show up as affecting memory, but they are just
270
392k
    // markers, mostly.
271
392k
    //
272
392k
    // FIXME: We probably don't actually want MemorySSA to model these at all
273
392k
    // (including creating MemoryAccesses for them): we just end up inventing
274
392k
    // clobbers where they don't really exist at all. Please see D43269 for
275
392k
    // context.
276
392k
    switch (II->getIntrinsicID()) {
277
392k
    case Intrinsic::lifetime_start:
278
147k
      if (UseCall)
279
2.10k
        return {false, NoAlias};
280
144k
      AR = AA.alias(MemoryLocation(II->getArgOperand(1)), UseLoc);
281
144k
      return {AR != NoAlias, AR};
282
144k
    case Intrinsic::lifetime_end:
283
117k
    case Intrinsic::invariant_start:
284
117k
    case Intrinsic::invariant_end:
285
117k
    case Intrinsic::assume:
286
117k
      return {false, NoAlias};
287
127k
    default:
288
127k
      break;
289
5.81M
    }
290
5.81M
  }
291
5.81M
292
5.81M
  if (UseCall) {
293
44.0k
    ModRefInfo I = AA.getModRefInfo(DefInst, UseCall);
294
44.0k
    AR = isMustSet(I) ? 
MustAlias84
:
MayAlias43.9k
;
295
44.0k
    return {isModOrRefSet(I), AR};
296
44.0k
  }
297
5.77M
298
5.77M
  if (auto *DefLoad = dyn_cast<LoadInst>(DefInst))
299
16.5k
    if (auto *UseLoad = dyn_cast<LoadInst>(UseInst))
300
16.5k
      return {!areLoadsReorderable(UseLoad, DefLoad), MayAlias};
301
5.75M
302
5.75M
  ModRefInfo I = AA.getModRefInfo(DefInst, UseLoc);
303
5.75M
  AR = isMustSet(I) ? 
MustAlias64.4k
:
MayAlias5.69M
;
304
5.75M
  return {isModSet(I), AR};
305
5.75M
}
MemorySSA.cpp:(anonymous namespace)::ClobberAlias instructionClobbersQuery<llvm::AAResults>(llvm::MemoryDef const*, llvm::MemoryLocation const&, llvm::Instruction const*, llvm::AAResults&)
Line
Count
Source
262
170k
                         const Instruction *UseInst, AliasAnalysisType &AA) {
263
170k
  Instruction *DefInst = MD->getMemoryInst();
264
170k
  assert(DefInst && "Defining instruction not actually an instruction");
265
170k
  const auto *UseCall = dyn_cast<CallBase>(UseInst);
266
170k
  Optional<AliasResult> AR;
267
170k
268
170k
  if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) {
269
10.5k
    // These intrinsics will show up as affecting memory, but they are just
270
10.5k
    // markers, mostly.
271
10.5k
    //
272
10.5k
    // FIXME: We probably don't actually want MemorySSA to model these at all
273
10.5k
    // (including creating MemoryAccesses for them): we just end up inventing
274
10.5k
    // clobbers where they don't really exist at all. Please see D43269 for
275
10.5k
    // context.
276
10.5k
    switch (II->getIntrinsicID()) {
277
10.5k
    case Intrinsic::lifetime_start:
278
4.98k
      if (UseCall)
279
13
        return {false, NoAlias};
280
4.97k
      AR = AA.alias(MemoryLocation(II->getArgOperand(1)), UseLoc);
281
4.97k
      return {AR != NoAlias, AR};
282
4.97k
    case Intrinsic::lifetime_end:
283
3.52k
    case Intrinsic::invariant_start:
284
3.52k
    case Intrinsic::invariant_end:
285
3.52k
    case Intrinsic::assume:
286
3.52k
      return {false, NoAlias};
287
3.52k
    default:
288
2.07k
      break;
289
162k
    }
290
162k
  }
291
162k
292
162k
  if (UseCall) {
293
117
    ModRefInfo I = AA.getModRefInfo(DefInst, UseCall);
294
117
    AR = isMustSet(I) ? 
MustAlias0
: MayAlias;
295
117
    return {isModOrRefSet(I), AR};
296
117
  }
297
162k
298
162k
  if (auto *DefLoad = dyn_cast<LoadInst>(DefInst))
299
1
    if (auto *UseLoad = dyn_cast<LoadInst>(UseInst))
300
1
      return {!areLoadsReorderable(UseLoad, DefLoad), MayAlias};
301
162k
302
162k
  ModRefInfo I = AA.getModRefInfo(DefInst, UseLoc);
303
162k
  AR = isMustSet(I) ? 
MustAlias779
:
MayAlias161k
;
304
162k
  return {isModSet(I), AR};
305
162k
}
306
307
template <typename AliasAnalysisType>
308
static ClobberAlias instructionClobbersQuery(MemoryDef *MD,
309
                                             const MemoryUseOrDef *MU,
310
                                             const MemoryLocOrCall &UseMLOC,
311
2.31M
                                             AliasAnalysisType &AA) {
312
2.31M
  // FIXME: This is a temporary hack to allow a single instructionClobbersQuery
313
2.31M
  // to exist while MemoryLocOrCall is pushed through places.
314
2.31M
  if (UseMLOC.IsCall)
315
28.1k
    return instructionClobbersQuery(MD, MemoryLocation(), MU->getMemoryInst(),
316
28.1k
                                    AA);
317
2.28M
  return instructionClobbersQuery(MD, UseMLOC.getLoc(), MU->getMemoryInst(),
318
2.28M
                                  AA);
319
2.28M
}
MemorySSA.cpp:(anonymous namespace)::ClobberAlias instructionClobbersQuery<llvm::BatchAAResults>(llvm::MemoryDef*, llvm::MemoryUseOrDef const*, (anonymous namespace)::MemoryLocOrCall const&, llvm::BatchAAResults&)
Line
Count
Source
311
2.31M
                                             AliasAnalysisType &AA) {
312
2.31M
  // FIXME: This is a temporary hack to allow a single instructionClobbersQuery
313
2.31M
  // to exist while MemoryLocOrCall is pushed through places.
314
2.31M
  if (UseMLOC.IsCall)
315
28.1k
    return instructionClobbersQuery(MD, MemoryLocation(), MU->getMemoryInst(),
316
28.1k
                                    AA);
317
2.28M
  return instructionClobbersQuery(MD, UseMLOC.getLoc(), MU->getMemoryInst(),
318
2.28M
                                  AA);
319
2.28M
}
MemorySSA.cpp:(anonymous namespace)::ClobberAlias instructionClobbersQuery<llvm::AAResults>(llvm::MemoryDef*, llvm::MemoryUseOrDef const*, (anonymous namespace)::MemoryLocOrCall const&, llvm::AAResults&)
Line
Count
Source
311
1
                                             AliasAnalysisType &AA) {
312
1
  // FIXME: This is a temporary hack to allow a single instructionClobbersQuery
313
1
  // to exist while MemoryLocOrCall is pushed through places.
314
1
  if (UseMLOC.IsCall)
315
0
    return instructionClobbersQuery(MD, MemoryLocation(), MU->getMemoryInst(),
316
0
                                    AA);
317
1
  return instructionClobbersQuery(MD, UseMLOC.getLoc(), MU->getMemoryInst(),
318
1
                                  AA);
319
1
}
320
321
// Return true when MD may alias MU, return false otherwise.
322
bool MemorySSAUtil::defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU,
323
1
                                        AliasAnalysis &AA) {
324
1
  return instructionClobbersQuery(MD, MU, MemoryLocOrCall(MU), AA).IsClobber;
325
1
}
326
327
namespace {
328
329
struct UpwardsMemoryQuery {
330
  // True if our original query started off as a call
331
  bool IsCall = false;
332
  // The pointer location we started the query with. This will be empty if
333
  // IsCall is true.
334
  MemoryLocation StartingLoc;
335
  // This is the instruction we were querying about.
336
  const Instruction *Inst = nullptr;
337
  // The MemoryAccess we actually got called with, used to test local domination
338
  const MemoryAccess *OriginalAccess = nullptr;
339
  Optional<AliasResult> AR = MayAlias;
340
  bool SkipSelfAccess = false;
341
342
2
  UpwardsMemoryQuery() = default;
343
344
  UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access)
345
1.12M
      : IsCall(isa<CallBase>(Inst)), Inst(Inst), OriginalAccess(Access) {
346
1.12M
    if (!IsCall)
347
1.12M
      StartingLoc = MemoryLocation::get(Inst);
348
1.12M
  }
349
};
350
351
} // end anonymous namespace
352
353
static bool lifetimeEndsAt(MemoryDef *MD, const MemoryLocation &Loc,
354
2.28M
                           BatchAAResults &AA) {
355
2.28M
  Instruction *Inst = MD->getMemoryInst();
356
2.28M
  if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
357
186k
    switch (II->getIntrinsicID()) {
358
186k
    case Intrinsic::lifetime_end:
359
35.9k
      return AA.alias(MemoryLocation(II->getArgOperand(1)), Loc) == MustAlias;
360
186k
    default:
361
150k
      return false;
362
2.09M
    }
363
2.09M
  }
364
2.09M
  return false;
365
2.09M
}
366
367
template <typename AliasAnalysisType>
368
static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysisType &AA,
369
4.24M
                                                   const Instruction *I) {
370
4.24M
  // If the memory can't be changed, then loads of the memory can't be
371
4.24M
  // clobbered.
372
4.24M
  return isa<LoadInst>(I) && 
(4.15M
I->getMetadata(LLVMContext::MD_invariant_load)4.15M
||
373
4.15M
                              AA.pointsToConstantMemory(MemoryLocation(
374
4.15M
                                  cast<LoadInst>(I)->getPointerOperand())));
375
4.24M
}
MemorySSA.cpp:bool isUseTriviallyOptimizableToLiveOnEntry<llvm::BatchAAResults>(llvm::BatchAAResults&, llvm::Instruction const*)
Line
Count
Source
369
4.22M
                                                   const Instruction *I) {
370
4.22M
  // If the memory can't be changed, then loads of the memory can't be
371
4.22M
  // clobbered.
372
4.22M
  return isa<LoadInst>(I) && 
(4.14M
I->getMetadata(LLVMContext::MD_invariant_load)4.14M
||
373
4.14M
                              AA.pointsToConstantMemory(MemoryLocation(
374
4.14M
                                  cast<LoadInst>(I)->getPointerOperand())));
375
4.22M
}
MemorySSA.cpp:bool isUseTriviallyOptimizableToLiveOnEntry<llvm::AAResults>(llvm::AAResults&, llvm::Instruction const*)
Line
Count
Source
369
14.5k
                                                   const Instruction *I) {
370
14.5k
  // If the memory can't be changed, then loads of the memory can't be
371
14.5k
  // clobbered.
372
14.5k
  return isa<LoadInst>(I) && 
(8.30k
I->getMetadata(LLVMContext::MD_invariant_load)8.30k
||
373
8.30k
                              AA.pointsToConstantMemory(MemoryLocation(
374
8.29k
                                  cast<LoadInst>(I)->getPointerOperand())));
375
14.5k
}
376
377
/// Verifies that `Start` is clobbered by `ClobberAt`, and that nothing
378
/// inbetween `Start` and `ClobberAt` can clobbers `Start`.
379
///
380
/// This is meant to be as simple and self-contained as possible. Because it
381
/// uses no cache, etc., it can be relatively expensive.
382
///
383
/// \param Start     The MemoryAccess that we want to walk from.
384
/// \param ClobberAt A clobber for Start.
385
/// \param StartLoc  The MemoryLocation for Start.
386
/// \param MSSA      The MemorySSA instance that Start and ClobberAt belong to.
387
/// \param Query     The UpwardsMemoryQuery we used for our search.
388
/// \param AA        The AliasAnalysis we used for our search.
389
/// \param AllowImpreciseClobber Always false, unless we do relaxed verify.
390
391
template <typename AliasAnalysisType>
392
LLVM_ATTRIBUTE_UNUSED static void
393
checkClobberSanity(const MemoryAccess *Start, MemoryAccess *ClobberAt,
394
                   const MemoryLocation &StartLoc, const MemorySSA &MSSA,
395
                   const UpwardsMemoryQuery &Query, AliasAnalysisType &AA,
396
                   bool AllowImpreciseClobber = false) {
397
  assert(MSSA.dominates(ClobberAt, Start) && "Clobber doesn't dominate start?");
398
399
  if (MSSA.isLiveOnEntryDef(Start)) {
400
    assert(MSSA.isLiveOnEntryDef(ClobberAt) &&
401
           "liveOnEntry must clobber itself");
402
    return;
403
  }
404
405
  bool FoundClobber = false;
406
  DenseSet<ConstMemoryAccessPair> VisitedPhis;
407
  SmallVector<ConstMemoryAccessPair, 8> Worklist;
408
  Worklist.emplace_back(Start, StartLoc);
409
  // Walk all paths from Start to ClobberAt, while looking for clobbers. If one
410
  // is found, complain.
411
  while (!Worklist.empty()) {
412
    auto MAP = Worklist.pop_back_val();
413
    // All we care about is that nothing from Start to ClobberAt clobbers Start.
414
    // We learn nothing from revisiting nodes.
415
    if (!VisitedPhis.insert(MAP).second)
416
      continue;
417
418
    for (const auto *MA : def_chain(MAP.first)) {
419
      if (MA == ClobberAt) {
420
        if (const auto *MD = dyn_cast<MemoryDef>(MA)) {
421
          // instructionClobbersQuery isn't essentially free, so don't use `|=`,
422
          // since it won't let us short-circuit.
423
          //
424
          // Also, note that this can't be hoisted out of the `Worklist` loop,
425
          // since MD may only act as a clobber for 1 of N MemoryLocations.
426
          FoundClobber = FoundClobber || MSSA.isLiveOnEntryDef(MD);
427
          if (!FoundClobber) {
428
            ClobberAlias CA =
429
                instructionClobbersQuery(MD, MAP.second, Query.Inst, AA);
430
            if (CA.IsClobber) {
431
              FoundClobber = true;
432
              // Not used: CA.AR;
433
            }
434
          }
435
        }
436
        break;
437
      }
438
439
      // We should never hit liveOnEntry, unless it's the clobber.
440
      assert(!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?");
441
442
      if (const auto *MD = dyn_cast<MemoryDef>(MA)) {
443
        // If Start is a Def, skip self.
444
        if (MD == Start)
445
          continue;
446
447
        assert(!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA)
448
                    .IsClobber &&
449
               "Found clobber before reaching ClobberAt!");
450
        continue;
451
      }
452
453
      if (const auto *MU = dyn_cast<MemoryUse>(MA)) {
454
        (void)MU;
455
        assert (MU == Start &&
456
                "Can only find use in def chain if Start is a use");
457
        continue;
458
      }
459
460
      assert(isa<MemoryPhi>(MA));
461
      Worklist.append(
462
          upward_defs_begin({const_cast<MemoryAccess *>(MA), MAP.second}),
463
          upward_defs_end());
464
    }
465
  }
466
467
  // If the verify is done following an optimization, it's possible that
468
  // ClobberAt was a conservative clobbering, that we can now infer is not a
469
  // true clobbering access. Don't fail the verify if that's the case.
470
  // We do have accesses that claim they're optimized, but could be optimized
471
  // further. Updating all these can be expensive, so allow it for now (FIXME).
472
  if (AllowImpreciseClobber)
473
    return;
474
475
  // If ClobberAt is a MemoryPhi, we can assume something above it acted as a
476
  // clobber. Otherwise, `ClobberAt` should've acted as a clobber at some point.
477
  assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&
478
         "ClobberAt never acted as a clobber");
479
}
480
481
namespace {
482
483
/// Our algorithm for walking (and trying to optimize) clobbers, all wrapped up
484
/// in one class.
485
template <class AliasAnalysisType> class ClobberWalker {
486
  /// Save a few bytes by using unsigned instead of size_t.
487
  using ListIndex = unsigned;
488
489
  /// Represents a span of contiguous MemoryDefs, potentially ending in a
490
  /// MemoryPhi.
491
  struct DefPath {
492
    MemoryLocation Loc;
493
    // Note that, because we always walk in reverse, Last will always dominate
494
    // First. Also note that First and Last are inclusive.
495
    MemoryAccess *First;
496
    MemoryAccess *Last;
497
    Optional<ListIndex> Previous;
498
499
    DefPath(const MemoryLocation &Loc, MemoryAccess *First, MemoryAccess *Last,
500
            Optional<ListIndex> Previous)
501
8.49M
        : Loc(Loc), First(First), Last(Last), Previous(Previous) {}
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::DefPath::DefPath(llvm::MemoryLocation const&, llvm::MemoryAccess*, llvm::MemoryAccess*, llvm::Optional<unsigned int>)
Line
Count
Source
501
8.43M
        : Loc(Loc), First(First), Last(Last), Previous(Previous) {}
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::AAResults>::DefPath::DefPath(llvm::MemoryLocation const&, llvm::MemoryAccess*, llvm::MemoryAccess*, llvm::Optional<unsigned int>)
Line
Count
Source
501
57.2k
        : Loc(Loc), First(First), Last(Last), Previous(Previous) {}
502
503
    DefPath(const MemoryLocation &Loc, MemoryAccess *Init,
504
            Optional<ListIndex> Previous)
505
6.23M
        : DefPath(Loc, Init, Init, Previous) {}
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::DefPath::DefPath(llvm::MemoryLocation const&, llvm::MemoryAccess*, llvm::Optional<unsigned int>)
Line
Count
Source
505
6.20M
        : DefPath(Loc, Init, Init, Previous) {}
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::AAResults>::DefPath::DefPath(llvm::MemoryLocation const&, llvm::MemoryAccess*, llvm::Optional<unsigned int>)
Line
Count
Source
505
32.4k
        : DefPath(Loc, Init, Init, Previous) {}
506
  };
507
508
  const MemorySSA &MSSA;
509
  AliasAnalysisType &AA;
510
  DominatorTree &DT;
511
  UpwardsMemoryQuery *Query;
512
  unsigned *UpwardWalkLimit;
513
514
  // Phi optimization bookkeeping
515
  SmallVector<DefPath, 32> Paths;
516
  DenseSet<ConstMemoryAccessPair> VisitedPhis;
517
518
  /// Find the nearest def or phi that `From` can legally be optimized to.
519
1.41M
  const MemoryAccess *getWalkTarget(const MemoryPhi *From) const {
520
1.41M
    assert(From->getNumOperands() && "Phi with no operands?");
521
1.41M
522
1.41M
    BasicBlock *BB = From->getBlock();
523
1.41M
    MemoryAccess *Result = MSSA.getLiveOnEntryDef();
524
1.41M
    DomTreeNode *Node = DT.getNode(BB);
525
2.71M
    while ((Node = Node->getIDom())) {
526
2.50M
      auto *Defs = MSSA.getBlockDefs(Node->getBlock());
527
2.50M
      if (Defs)
528
1.20M
        return &*Defs->rbegin();
529
2.50M
    }
530
1.41M
    
return Result208k
;
531
1.41M
  }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::getWalkTarget(llvm::MemoryPhi const*) const
Line
Count
Source
519
1.39M
  const MemoryAccess *getWalkTarget(const MemoryPhi *From) const {
520
1.39M
    assert(From->getNumOperands() && "Phi with no operands?");
521
1.39M
522
1.39M
    BasicBlock *BB = From->getBlock();
523
1.39M
    MemoryAccess *Result = MSSA.getLiveOnEntryDef();
524
1.39M
    DomTreeNode *Node = DT.getNode(BB);
525
2.63M
    while ((Node = Node->getIDom())) {
526
2.43M
      auto *Defs = MSSA.getBlockDefs(Node->getBlock());
527
2.43M
      if (Defs)
528
1.19M
        return &*Defs->rbegin();
529
2.43M
    }
530
1.39M
    
return Result202k
;
531
1.39M
  }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::AAResults>::getWalkTarget(llvm::MemoryPhi const*) const
Line
Count
Source
519
12.3k
  const MemoryAccess *getWalkTarget(const MemoryPhi *From) const {
520
12.3k
    assert(From->getNumOperands() && "Phi with no operands?");
521
12.3k
522
12.3k
    BasicBlock *BB = From->getBlock();
523
12.3k
    MemoryAccess *Result = MSSA.getLiveOnEntryDef();
524
12.3k
    DomTreeNode *Node = DT.getNode(BB);
525
77.4k
    while ((Node = Node->getIDom())) {
526
72.0k
      auto *Defs = MSSA.getBlockDefs(Node->getBlock());
527
72.0k
      if (Defs)
528
6.98k
        return &*Defs->rbegin();
529
72.0k
    }
530
12.3k
    
return Result5.38k
;
531
12.3k
  }
532
533
  /// Result of calling walkToPhiOrClobber.
534
  struct UpwardsWalkResult {
535
    /// The "Result" of the walk. Either a clobber, the last thing we walked, or
536
    /// both. Include alias info when clobber found.
537
    MemoryAccess *Result;
538
    bool IsKnownClobber;
539
    Optional<AliasResult> AR;
540
  };
541
542
  /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last.
543
  /// This will update Desc.Last as it walks. It will (optionally) also stop at
544
  /// StopAt.
545
  ///
546
  /// This does not test for whether StopAt is a clobber
547
  UpwardsWalkResult
548
  walkToPhiOrClobber(DefPath &Desc, const MemoryAccess *StopAt = nullptr,
549
4.52M
                     const MemoryAccess *SkipStopAt = nullptr) const {
550
4.52M
    assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");
551
4.52M
    assert(UpwardWalkLimit && "Need a valid walk limit");
552
4.52M
    bool LimitAlreadyReached = false;
553
4.52M
    // (*UpwardWalkLimit) may be 0 here, due to the loop in tryOptimizePhi. Set
554
4.52M
    // it to 1. This will not do any alias() calls. It either returns in the
555
4.52M
    // first iteration in the loop below, or is set back to 0 if all def chains
556
4.52M
    // are free of MemoryDefs.
557
4.52M
    if (!*UpwardWalkLimit) {
558
201
      *UpwardWalkLimit = 1;
559
201
      LimitAlreadyReached = true;
560
201
    }
561
4.52M
562
7.34M
    for (MemoryAccess *Current : def_chain(Desc.Last)) {
563
7.34M
      Desc.Last = Current;
564
7.34M
      if (Current == StopAt || 
Current == SkipStopAt6.62M
)
565
715k
        return {Current, false, MayAlias};
566
6.62M
567
6.62M
      if (auto *MD = dyn_cast<MemoryDef>(Current)) {
568
4.04M
        if (MSSA.isLiveOnEntryDef(MD))
569
101k
          return {MD, true, MustAlias};
570
3.94M
571
3.94M
        if (!--*UpwardWalkLimit)
572
4.60k
          return {Current, true, MayAlias};
573
3.93M
574
3.93M
        ClobberAlias CA =
575
3.93M
            instructionClobbersQuery(MD, Desc.Loc, Query->Inst, AA);
576
3.93M
        if (CA.IsClobber)
577
1.11M
          return {MD, true, CA.AR};
578
3.93M
      }
579
6.62M
    }
580
4.52M
581
4.52M
    
if (2.58M
LimitAlreadyReached2.58M
)
582
0
      *UpwardWalkLimit = 0;
583
2.58M
584
2.58M
    assert(isa<MemoryPhi>(Desc.Last) &&
585
2.58M
           "Ended at a non-clobber that's not a phi?");
586
2.58M
    return {Desc.Last, false, MayAlias};
587
4.52M
  }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::walkToPhiOrClobber((anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::DefPath&, llvm::MemoryAccess const*, llvm::MemoryAccess const*) const
Line
Count
Source
549
4.47M
                     const MemoryAccess *SkipStopAt = nullptr) const {
550
4.47M
    assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");
551
4.47M
    assert(UpwardWalkLimit && "Need a valid walk limit");
552
4.47M
    bool LimitAlreadyReached = false;
553
4.47M
    // (*UpwardWalkLimit) may be 0 here, due to the loop in tryOptimizePhi. Set
554
4.47M
    // it to 1. This will not do any alias() calls. It either returns in the
555
4.47M
    // first iteration in the loop below, or is set back to 0 if all def chains
556
4.47M
    // are free of MemoryDefs.
557
4.47M
    if (!*UpwardWalkLimit) {
558
125
      *UpwardWalkLimit = 1;
559
125
      LimitAlreadyReached = true;
560
125
    }
561
4.47M
562
7.13M
    for (MemoryAccess *Current : def_chain(Desc.Last)) {
563
7.13M
      Desc.Last = Current;
564
7.13M
      if (Current == StopAt || 
Current == SkipStopAt6.43M
)
565
699k
        return {Current, false, MayAlias};
566
6.43M
567
6.43M
      if (auto *MD = dyn_cast<MemoryDef>(Current)) {
568
3.86M
        if (MSSA.isLiveOnEntryDef(MD))
569
89.9k
          return {MD, true, MustAlias};
570
3.77M
571
3.77M
        if (!--*UpwardWalkLimit)
572
4.29k
          return {Current, true, MayAlias};
573
3.76M
574
3.76M
        ClobberAlias CA =
575
3.76M
            instructionClobbersQuery(MD, Desc.Loc, Query->Inst, AA);
576
3.76M
        if (CA.IsClobber)
577
1.11M
          return {MD, true, CA.AR};
578
3.76M
      }
579
6.43M
    }
580
4.47M
581
4.47M
    
if (2.56M
LimitAlreadyReached2.56M
)
582
0
      *UpwardWalkLimit = 0;
583
2.56M
584
2.56M
    assert(isa<MemoryPhi>(Desc.Last) &&
585
2.56M
           "Ended at a non-clobber that's not a phi?");
586
2.56M
    return {Desc.Last, false, MayAlias};
587
4.47M
  }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::AAResults>::walkToPhiOrClobber((anonymous namespace)::ClobberWalker<llvm::AAResults>::DefPath&, llvm::MemoryAccess const*, llvm::MemoryAccess const*) const
Line
Count
Source
549
51.3k
                     const MemoryAccess *SkipStopAt = nullptr) const {
550
51.3k
    assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");
551
51.3k
    assert(UpwardWalkLimit && "Need a valid walk limit");
552
51.3k
    bool LimitAlreadyReached = false;
553
51.3k
    // (*UpwardWalkLimit) may be 0 here, due to the loop in tryOptimizePhi. Set
554
51.3k
    // it to 1. This will not do any alias() calls. It either returns in the
555
51.3k
    // first iteration in the loop below, or is set back to 0 if all def chains
556
51.3k
    // are free of MemoryDefs.
557
51.3k
    if (!*UpwardWalkLimit) {
558
76
      *UpwardWalkLimit = 1;
559
76
      LimitAlreadyReached = true;
560
76
    }
561
51.3k
562
213k
    for (MemoryAccess *Current : def_chain(Desc.Last)) {
563
213k
      Desc.Last = Current;
564
213k
      if (Current == StopAt || 
Current == SkipStopAt197k
)
565
15.6k
        return {Current, false, MayAlias};
566
197k
567
197k
      if (auto *MD = dyn_cast<MemoryDef>(Current)) {
568
182k
        if (MSSA.isLiveOnEntryDef(MD))
569
11.0k
          return {MD, true, MustAlias};
570
171k
571
171k
        if (!--*UpwardWalkLimit)
572
311
          return {Current, true, MayAlias};
573
170k
574
170k
        ClobberAlias CA =
575
170k
            instructionClobbersQuery(MD, Desc.Loc, Query->Inst, AA);
576
170k
        if (CA.IsClobber)
577
8.77k
          return {MD, true, CA.AR};
578
170k
      }
579
197k
    }
580
51.3k
581
51.3k
    
if (15.5k
LimitAlreadyReached15.5k
)
582
0
      *UpwardWalkLimit = 0;
583
15.5k
584
15.5k
    assert(isa<MemoryPhi>(Desc.Last) &&
585
15.5k
           "Ended at a non-clobber that's not a phi?");
586
15.5k
    return {Desc.Last, false, MayAlias};
587
51.3k
  }
588
589
  void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches,
590
2.58M
                   ListIndex PriorNode) {
591
2.58M
    auto UpwardDefs = make_range(upward_defs_begin({Phi, Paths[PriorNode].Loc}),
592
2.58M
                                 upward_defs_end());
593
6.23M
    for (const MemoryAccessPair &P : UpwardDefs) {
594
6.23M
      PausedSearches.push_back(Paths.size());
595
6.23M
      Paths.emplace_back(P.second, P.first, PriorNode);
596
6.23M
    }
597
2.58M
  }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::addSearches(llvm::MemoryPhi*, llvm::SmallVectorImpl<unsigned int>&, unsigned int)
Line
Count
Source
590
2.56M
                   ListIndex PriorNode) {
591
2.56M
    auto UpwardDefs = make_range(upward_defs_begin({Phi, Paths[PriorNode].Loc}),
592
2.56M
                                 upward_defs_end());
593
6.20M
    for (const MemoryAccessPair &P : UpwardDefs) {
594
6.20M
      PausedSearches.push_back(Paths.size());
595
6.20M
      Paths.emplace_back(P.second, P.first, PriorNode);
596
6.20M
    }
597
2.56M
  }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::AAResults>::addSearches(llvm::MemoryPhi*, llvm::SmallVectorImpl<unsigned int>&, unsigned int)
Line
Count
Source
590
15.4k
                   ListIndex PriorNode) {
591
15.4k
    auto UpwardDefs = make_range(upward_defs_begin({Phi, Paths[PriorNode].Loc}),
592
15.4k
                                 upward_defs_end());
593
32.4k
    for (const MemoryAccessPair &P : UpwardDefs) {
594
32.4k
      PausedSearches.push_back(Paths.size());
595
32.4k
      Paths.emplace_back(P.second, P.first, PriorNode);
596
32.4k
    }
597
15.4k
  }
598
599
  /// Represents a search that terminated after finding a clobber. This clobber
600
  /// may or may not be present in the path of defs from LastNode..SearchStart,
601
  /// since it may have been retrieved from cache.
602
  struct TerminatedPath {
603
    MemoryAccess *Clobber;
604
    ListIndex LastNode;
605
  };
606
607
  /// Get an access that keeps us from optimizing to the given phi.
608
  ///
609
  /// PausedSearches is an array of indices into the Paths array. Its incoming
610
  /// value is the indices of searches that stopped at the last phi optimization
611
  /// target. It's left in an unspecified state.
612
  ///
613
  /// If this returns None, NewPaused is a vector of searches that terminated
614
  /// at StopWhere. Otherwise, NewPaused is left in an unspecified state.
615
  Optional<TerminatedPath>
616
  getBlockingAccess(const MemoryAccess *StopWhere,
617
                    SmallVectorImpl<ListIndex> &PausedSearches,
618
                    SmallVectorImpl<ListIndex> &NewPaused,
619
1.41M
                    SmallVectorImpl<TerminatedPath> &Terminated) {
620
1.41M
    assert(!PausedSearches.empty() && "No searches to continue?");
621
1.41M
622
1.41M
    // BFS vs DFS really doesn't make a difference here, so just do a DFS with
623
1.41M
    // PausedSearches as our stack.
624
4.37M
    while (!PausedSearches.empty()) {
625
3.95M
      ListIndex PathIndex = PausedSearches.pop_back_val();
626
3.95M
      DefPath &Node = Paths[PathIndex];
627
3.95M
628
3.95M
      // If we've already visited this path with this MemoryLocation, we don't
629
3.95M
      // need to do so again.
630
3.95M
      //
631
3.95M
      // NOTE: That we just drop these paths on the ground makes caching
632
3.95M
      // behavior sporadic. e.g. given a diamond:
633
3.95M
      //  A
634
3.95M
      // B C
635
3.95M
      //  D
636
3.95M
      //
637
3.95M
      // ...If we walk D, B, A, C, we'll only cache the result of phi
638
3.95M
      // optimization for A, B, and D; C will be skipped because it dies here.
639
3.95M
      // This arguably isn't the worst thing ever, since:
640
3.95M
      //   - We generally query things in a top-down order, so if we got below D
641
3.95M
      //     without needing cache entries for {C, MemLoc}, then chances are
642
3.95M
      //     that those cache entries would end up ultimately unused.
643
3.95M
      //   - We still cache things for A, so C only needs to walk up a bit.
644
3.95M
      // If this behavior becomes problematic, we can fix without a ton of extra
645
3.95M
      // work.
646
3.95M
      if (!VisitedPhis.insert({Node.Last, Node.Loc}).second)
647
1.22M
        continue;
648
2.72M
649
2.72M
      const MemoryAccess *SkipStopWhere = nullptr;
650
2.72M
      if (Query->SkipSelfAccess && 
Node.Loc == Query->StartingLoc102
) {
651
102
        assert(isa<MemoryDef>(Query->OriginalAccess));
652
102
        SkipStopWhere = Query->OriginalAccess;
653
102
      }
654
2.72M
655
2.72M
      UpwardsWalkResult Res = walkToPhiOrClobber(Node,
656
2.72M
                                                 /*StopAt=*/StopWhere,
657
2.72M
                                                 /*SkipStopAt=*/SkipStopWhere);
658
2.72M
      if (Res.IsKnownClobber) {
659
991k
        assert(Res.Result != StopWhere && Res.Result != SkipStopWhere);
660
991k
661
991k
        // If this wasn't a cache hit, we hit a clobber when walking. That's a
662
991k
        // failure.
663
991k
        TerminatedPath Term{Res.Result, PathIndex};
664
991k
        if (!MSSA.dominates(Res.Result, StopWhere))
665
991k
          return Term;
666
26
667
26
        // Otherwise, it's a valid thing to potentially optimize to.
668
26
        Terminated.push_back(Term);
669
26
        continue;
670
26
      }
671
1.73M
672
1.73M
      if (Res.Result == StopWhere || 
Res.Result == SkipStopWhere1.02M
) {
673
715k
        // We've hit our target. Save this path off for if we want to continue
674
715k
        // walking. If we are in the mode of skipping the OriginalAccess, and
675
715k
        // we've reached back to the OriginalAccess, do not save path, we've
676
715k
        // just looped back to self.
677
715k
        if (Res.Result != SkipStopWhere)
678
715k
          NewPaused.push_back(PathIndex);
679
715k
        continue;
680
715k
      }
681
1.02M
682
1.02M
      assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");
683
1.02M
      addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
684
1.02M
    }
685
1.41M
686
1.41M
    
return None418k
;
687
1.41M
  }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::getBlockingAccess(llvm::MemoryAccess const*, llvm::SmallVectorImpl<unsigned int>&, llvm::SmallVectorImpl<unsigned int>&, llvm::SmallVectorImpl<(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::TerminatedPath>&)
Line
Count
Source
619
1.39M
                    SmallVectorImpl<TerminatedPath> &Terminated) {
620
1.39M
    assert(!PausedSearches.empty() && "No searches to continue?");
621
1.39M
622
1.39M
    // BFS vs DFS really doesn't make a difference here, so just do a DFS with
623
1.39M
    // PausedSearches as our stack.
624
4.34M
    while (!PausedSearches.empty()) {
625
3.93M
      ListIndex PathIndex = PausedSearches.pop_back_val();
626
3.93M
      DefPath &Node = Paths[PathIndex];
627
3.93M
628
3.93M
      // If we've already visited this path with this MemoryLocation, we don't
629
3.93M
      // need to do so again.
630
3.93M
      //
631
3.93M
      // NOTE: That we just drop these paths on the ground makes caching
632
3.93M
      // behavior sporadic. e.g. given a diamond:
633
3.93M
      //  A
634
3.93M
      // B C
635
3.93M
      //  D
636
3.93M
      //
637
3.93M
      // ...If we walk D, B, A, C, we'll only cache the result of phi
638
3.93M
      // optimization for A, B, and D; C will be skipped because it dies here.
639
3.93M
      // This arguably isn't the worst thing ever, since:
640
3.93M
      //   - We generally query things in a top-down order, so if we got below D
641
3.93M
      //     without needing cache entries for {C, MemLoc}, then chances are
642
3.93M
      //     that those cache entries would end up ultimately unused.
643
3.93M
      //   - We still cache things for A, so C only needs to walk up a bit.
644
3.93M
      // If this behavior becomes problematic, we can fix without a ton of extra
645
3.93M
      // work.
646
3.93M
      if (!VisitedPhis.insert({Node.Last, Node.Loc}).second)
647
1.22M
        continue;
648
2.70M
649
2.70M
      const MemoryAccess *SkipStopWhere = nullptr;
650
2.70M
      if (Query->SkipSelfAccess && 
Node.Loc == Query->StartingLoc0
) {
651
0
        assert(isa<MemoryDef>(Query->OriginalAccess));
652
0
        SkipStopWhere = Query->OriginalAccess;
653
0
      }
654
2.70M
655
2.70M
      UpwardsWalkResult Res = walkToPhiOrClobber(Node,
656
2.70M
                                                 /*StopAt=*/StopWhere,
657
2.70M
                                                 /*SkipStopAt=*/SkipStopWhere);
658
2.70M
      if (Res.IsKnownClobber) {
659
987k
        assert(Res.Result != StopWhere && Res.Result != SkipStopWhere);
660
987k
661
987k
        // If this wasn't a cache hit, we hit a clobber when walking. That's a
662
987k
        // failure.
663
987k
        TerminatedPath Term{Res.Result, PathIndex};
664
987k
        if (!MSSA.dominates(Res.Result, StopWhere))
665
987k
          return Term;
666
0
667
0
        // Otherwise, it's a valid thing to potentially optimize to.
668
0
        Terminated.push_back(Term);
669
0
        continue;
670
0
      }
671
1.72M
672
1.72M
      if (Res.Result == StopWhere || 
Res.Result == SkipStopWhere1.02M
) {
673
699k
        // We've hit our target. Save this path off for if we want to continue
674
699k
        // walking. If we are in the mode of skipping the OriginalAccess, and
675
699k
        // we've reached back to the OriginalAccess, do not save path, we've
676
699k
        // just looped back to self.
677
699k
        if (Res.Result != SkipStopWhere)
678
699k
          NewPaused.push_back(PathIndex);
679
699k
        continue;
680
699k
      }
681
1.02M
682
1.02M
      assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");
683
1.02M
      addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
684
1.02M
    }
685
1.39M
686
1.39M
    
return None410k
;
687
1.39M
  }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::AAResults>::getBlockingAccess(llvm::MemoryAccess const*, llvm::SmallVectorImpl<unsigned int>&, llvm::SmallVectorImpl<unsigned int>&, llvm::SmallVectorImpl<(anonymous namespace)::ClobberWalker<llvm::AAResults>::TerminatedPath>&)
Line
Count
Source
619
12.3k
                    SmallVectorImpl<TerminatedPath> &Terminated) {
620
12.3k
    assert(!PausedSearches.empty() && "No searches to continue?");
621
12.3k
622
12.3k
    // BFS vs DFS really doesn't make a difference here, so just do a DFS with
623
12.3k
    // PausedSearches as our stack.
624
32.9k
    while (!PausedSearches.empty()) {
625
25.1k
      ListIndex PathIndex = PausedSearches.pop_back_val();
626
25.1k
      DefPath &Node = Paths[PathIndex];
627
25.1k
628
25.1k
      // If we've already visited this path with this MemoryLocation, we don't
629
25.1k
      // need to do so again.
630
25.1k
      //
631
25.1k
      // NOTE: That we just drop these paths on the ground makes caching
632
25.1k
      // behavior sporadic. e.g. given a diamond:
633
25.1k
      //  A
634
25.1k
      // B C
635
25.1k
      //  D
636
25.1k
      //
637
25.1k
      // ...If we walk D, B, A, C, we'll only cache the result of phi
638
25.1k
      // optimization for A, B, and D; C will be skipped because it dies here.
639
25.1k
      // This arguably isn't the worst thing ever, since:
640
25.1k
      //   - We generally query things in a top-down order, so if we got below D
641
25.1k
      //     without needing cache entries for {C, MemLoc}, then chances are
642
25.1k
      //     that those cache entries would end up ultimately unused.
643
25.1k
      //   - We still cache things for A, so C only needs to walk up a bit.
644
25.1k
      // If this behavior becomes problematic, we can fix without a ton of extra
645
25.1k
      // work.
646
25.1k
      if (!VisitedPhis.insert({Node.Last, Node.Loc}).second)
647
3.73k
        continue;
648
21.4k
649
21.4k
      const MemoryAccess *SkipStopWhere = nullptr;
650
21.4k
      if (Query->SkipSelfAccess && 
Node.Loc == Query->StartingLoc102
) {
651
102
        assert(isa<MemoryDef>(Query->OriginalAccess));
652
102
        SkipStopWhere = Query->OriginalAccess;
653
102
      }
654
21.4k
655
21.4k
      UpwardsWalkResult Res = walkToPhiOrClobber(Node,
656
21.4k
                                                 /*StopAt=*/StopWhere,
657
21.4k
                                                 /*SkipStopAt=*/SkipStopWhere);
658
21.4k
      if (Res.IsKnownClobber) {
659
4.60k
        assert(Res.Result != StopWhere && Res.Result != SkipStopWhere);
660
4.60k
661
4.60k
        // If this wasn't a cache hit, we hit a clobber when walking. That's a
662
4.60k
        // failure.
663
4.60k
        TerminatedPath Term{Res.Result, PathIndex};
664
4.60k
        if (!MSSA.dominates(Res.Result, StopWhere))
665
4.58k
          return Term;
666
26
667
26
        // Otherwise, it's a valid thing to potentially optimize to.
668
26
        Terminated.push_back(Term);
669
26
        continue;
670
26
      }
671
16.8k
672
16.8k
      if (Res.Result == StopWhere || 
Res.Result == SkipStopWhere1.13k
) {
673
15.6k
        // We've hit our target. Save this path off for if we want to continue
674
15.6k
        // walking. If we are in the mode of skipping the OriginalAccess, and
675
15.6k
        // we've reached back to the OriginalAccess, do not save path, we've
676
15.6k
        // just looped back to self.
677
15.6k
        if (Res.Result != SkipStopWhere)
678
15.6k
          NewPaused.push_back(PathIndex);
679
15.6k
        continue;
680
15.6k
      }
681
1.12k
682
1.12k
      assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");
683
1.12k
      addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
684
1.12k
    }
685
12.3k
686
12.3k
    
return None7.78k
;
687
12.3k
  }
688
689
  template <typename T, typename Walker>
690
  struct generic_def_path_iterator
691
      : public iterator_facade_base<generic_def_path_iterator<T, Walker>,
692
                                    std::forward_iterator_tag, T *> {
693
991k
    generic_def_path_iterator() {}
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::generic_def_path_iterator<(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::DefPath, (anonymous namespace)::ClobberWalker<llvm::BatchAAResults> >::generic_def_path_iterator()
Line
Count
Source
693
987k
    generic_def_path_iterator() {}
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::AAResults>::generic_def_path_iterator<(anonymous namespace)::ClobberWalker<llvm::AAResults>::DefPath, (anonymous namespace)::ClobberWalker<llvm::AAResults> >::generic_def_path_iterator()
Line
Count
Source
693
4.58k
    generic_def_path_iterator() {}
694
991k
    generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::generic_def_path_iterator<(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::DefPath, (anonymous namespace)::ClobberWalker<llvm::BatchAAResults> >::generic_def_path_iterator((anonymous namespace)::ClobberWalker<llvm::BatchAAResults>*, unsigned int)
Line
Count
Source
694
987k
    generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::AAResults>::generic_def_path_iterator<(anonymous namespace)::ClobberWalker<llvm::AAResults>::DefPath, (anonymous namespace)::ClobberWalker<llvm::AAResults> >::generic_def_path_iterator((anonymous namespace)::ClobberWalker<llvm::AAResults>*, unsigned int)
Line
Count
Source
694
4.58k
    generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}
695
696
3.41M
    T &operator*() const { return curNode(); }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::generic_def_path_iterator<(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::DefPath, (anonymous namespace)::ClobberWalker<llvm::BatchAAResults> >::operator*() const
Line
Count
Source
696
3.39M
    T &operator*() const { return curNode(); }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::AAResults>::generic_def_path_iterator<(anonymous namespace)::ClobberWalker<llvm::AAResults>::DefPath, (anonymous namespace)::ClobberWalker<llvm::AAResults> >::operator*() const
Line
Count
Source
696
14.3k
    T &operator*() const { return curNode(); }
697
698
1.42M
    generic_def_path_iterator &operator++() {
699
1.42M
      N = curNode().Previous;
700
1.42M
      return *this;
701
1.42M
    }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::generic_def_path_iterator<(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::DefPath, (anonymous namespace)::ClobberWalker<llvm::BatchAAResults> >::operator++()
Line
Count
Source
698
1.42M
    generic_def_path_iterator &operator++() {
699
1.42M
      N = curNode().Previous;
700
1.42M
      return *this;
701
1.42M
    }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::AAResults>::generic_def_path_iterator<(anonymous namespace)::ClobberWalker<llvm::AAResults>::DefPath, (anonymous namespace)::ClobberWalker<llvm::AAResults> >::operator++()
Line
Count
Source
698
5.19k
    generic_def_path_iterator &operator++() {
699
5.19k
      N = curNode().Previous;
700
5.19k
      return *this;
701
5.19k
    }
702
703
2.42M
    bool operator==(const generic_def_path_iterator &O) const {
704
2.42M
      if (N.hasValue() != O.N.hasValue())
705
2.42M
        return false;
706
0
      return !N.hasValue() || *N == *O.N;
707
0
    }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::generic_def_path_iterator<(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::DefPath, (anonymous namespace)::ClobberWalker<llvm::BatchAAResults> >::operator==((anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::generic_def_path_iterator<(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::DefPath, (anonymous namespace)::ClobberWalker<llvm::BatchAAResults> > const&) const
Line
Count
Source
703
2.41M
    bool operator==(const generic_def_path_iterator &O) const {
704
2.41M
      if (N.hasValue() != O.N.hasValue())
705
2.41M
        return false;
706
0
      return !N.hasValue() || *N == *O.N;
707
0
    }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::AAResults>::generic_def_path_iterator<(anonymous namespace)::ClobberWalker<llvm::AAResults>::DefPath, (anonymous namespace)::ClobberWalker<llvm::AAResults> >::operator==((anonymous namespace)::ClobberWalker<llvm::AAResults>::generic_def_path_iterator<(anonymous namespace)::ClobberWalker<llvm::AAResults>::DefPath, (anonymous namespace)::ClobberWalker<llvm::AAResults> > const&) const
Line
Count
Source
703
9.77k
    bool operator==(const generic_def_path_iterator &O) const {
704
9.77k
      if (N.hasValue() != O.N.hasValue())
705
9.77k
        return false;
706
0
      return !N.hasValue() || *N == *O.N;
707
0
    }
708
709
  private:
710
4.84M
    T &curNode() const { return W->Paths[*N]; }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::generic_def_path_iterator<(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::DefPath, (anonymous namespace)::ClobberWalker<llvm::BatchAAResults> >::curNode() const
Line
Count
Source
710
4.82M
    T &curNode() const { return W->Paths[*N]; }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::AAResults>::generic_def_path_iterator<(anonymous namespace)::ClobberWalker<llvm::AAResults>::DefPath, (anonymous namespace)::ClobberWalker<llvm::AAResults> >::curNode() const
Line
Count
Source
710
19.5k
    T &curNode() const { return W->Paths[*N]; }
711
712
    Walker *W = nullptr;
713
    Optional<ListIndex> N = None;
714
  };
715
716
  using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
717
  using const_def_path_iterator =
718
      generic_def_path_iterator<const DefPath, const ClobberWalker>;
719
720
991k
  iterator_range<def_path_iterator> def_path(ListIndex From) {
721
991k
    return make_range(def_path_iterator(this, From), def_path_iterator());
722
991k
  }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::def_path(unsigned int)
Line
Count
Source
720
987k
  iterator_range<def_path_iterator> def_path(ListIndex From) {
721
987k
    return make_range(def_path_iterator(this, From), def_path_iterator());
722
987k
  }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::AAResults>::def_path(unsigned int)
Line
Count
Source
720
4.58k
  iterator_range<def_path_iterator> def_path(ListIndex From) {
721
4.58k
    return make_range(def_path_iterator(this, From), def_path_iterator());
722
4.58k
  }
723
724
  iterator_range<const_def_path_iterator> const_def_path(ListIndex From) const {
725
    return make_range(const_def_path_iterator(this, From),
726
                      const_def_path_iterator());
727
  }
728
729
  struct OptznResult {
730
    /// The path that contains our result.
731
    TerminatedPath PrimaryClobber;
732
    /// The paths that we can legally cache back from, but that aren't
733
    /// necessarily the result of the Phi optimization.
734
    SmallVector<TerminatedPath, 4> OtherClobbers;
735
  };
736
737
3.41M
  ListIndex defPathIndex(const DefPath &N) const {
738
3.41M
    // The assert looks nicer if we don't need to do &N
739
3.41M
    const DefPath *NP = &N;
740
3.41M
    assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
741
3.41M
           "Out of bounds DefPath!");
742
3.41M
    return NP - &Paths.front();
743
3.41M
  }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::defPathIndex((anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::DefPath const&) const
Line
Count
Source
737
3.39M
  ListIndex defPathIndex(const DefPath &N) const {
738
3.39M
    // The assert looks nicer if we don't need to do &N
739
3.39M
    const DefPath *NP = &N;
740
3.39M
    assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
741
3.39M
           "Out of bounds DefPath!");
742
3.39M
    return NP - &Paths.front();
743
3.39M
  }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::AAResults>::defPathIndex((anonymous namespace)::ClobberWalker<llvm::AAResults>::DefPath const&) const
Line
Count
Source
737
14.3k
  ListIndex defPathIndex(const DefPath &N) const {
738
14.3k
    // The assert looks nicer if we don't need to do &N
739
14.3k
    const DefPath *NP = &N;
740
14.3k
    assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
741
14.3k
           "Out of bounds DefPath!");
742
14.3k
    return NP - &Paths.front();
743
14.3k
  }
744
745
  /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths
746
  /// that act as legal clobbers. Note that this won't return *all* clobbers.
747
  ///
748
  /// Phi optimization algorithm tl;dr:
749
  ///   - Find the earliest def/phi, A, we can optimize to
750
  ///   - Find if all paths from the starting memory access ultimately reach A
751
  ///     - If not, optimization isn't possible.
752
  ///     - Otherwise, walk from A to another clobber or phi, A'.
753
  ///       - If A' is a def, we're done.
754
  ///       - If A' is a phi, try to optimize it.
755
  ///
756
  /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path
757
  /// terminates when a MemoryAccess that clobbers said MemoryLocation is found.
758
  OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start,
759
1.12M
                             const MemoryLocation &Loc) {
760
1.12M
    assert(Paths.empty() && VisitedPhis.empty() &&
761
1.12M
           "Reset the optimization state.");
762
1.12M
763
1.12M
    Paths.emplace_back(Loc, Start, Phi, None);
764
1.12M
    // Stores how many "valid" optimization nodes we had prior to calling
765
1.12M
    // addSearches/getBlockingAccess. Necessary for caching if we had a blocker.
766
1.12M
    auto PriorPathsSize = Paths.size();
767
1.12M
768
1.12M
    SmallVector<ListIndex, 16> PausedSearches;
769
1.12M
    SmallVector<ListIndex, 8> NewPaused;
770
1.12M
    SmallVector<TerminatedPath, 4> TerminatedPaths;
771
1.12M
772
1.12M
    addSearches(Phi, PausedSearches, 0);
773
1.12M
774
1.12M
    // Moves the TerminatedPath with the "most dominated" Clobber to the end of
775
1.12M
    // Paths.
776
1.12M
    auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
777
133k
      assert(!Paths.empty() && "Need a path to move");
778
133k
      auto Dom = Paths.begin();
779
228k
      for (auto I = std::next(Dom), E = Paths.end(); I != E; 
++I94.6k
)
780
94.6k
        if (!MSSA.dominates(I->Clobber, Dom->Clobber))
781
288
          Dom = I;
782
133k
      auto Last = Paths.end() - 1;
783
133k
      if (Last != Dom)
784
80.8k
        std::iter_swap(Last, Dom);
785
133k
    };
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::tryOptimizePhi(llvm::MemoryPhi*, llvm::MemoryAccess*, llvm::MemoryLocation const&)::'lambda'(llvm::SmallVectorImpl<(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::TerminatedPath>&)::operator()(llvm::SmallVectorImpl<(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::TerminatedPath>&) const
Line
Count
Source
776
128k
    auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
777
128k
      assert(!Paths.empty() && "Need a path to move");
778
128k
      auto Dom = Paths.begin();
779
217k
      for (auto I = std::next(Dom), E = Paths.end(); I != E; 
++I89.0k
)
780
89.0k
        if (!MSSA.dominates(I->Clobber, Dom->Clobber))
781
190
          Dom = I;
782
128k
      auto Last = Paths.end() - 1;
783
128k
      if (Last != Dom)
784
75.3k
        std::iter_swap(Last, Dom);
785
128k
    };
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::AAResults>::tryOptimizePhi(llvm::MemoryPhi*, llvm::MemoryAccess*, llvm::MemoryLocation const&)::'lambda'(llvm::SmallVectorImpl<(anonymous namespace)::ClobberWalker<llvm::AAResults>::TerminatedPath>&)::operator()(llvm::SmallVectorImpl<(anonymous namespace)::ClobberWalker<llvm::AAResults>::TerminatedPath>&) const
Line
Count
Source
776
5.65k
    auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
777
5.65k
      assert(!Paths.empty() && "Need a path to move");
778
5.65k
      auto Dom = Paths.begin();
779
11.1k
      for (auto I = std::next(Dom), E = Paths.end(); I != E; 
++I5.53k
)
780
5.53k
        if (!MSSA.dominates(I->Clobber, Dom->Clobber))
781
98
          Dom = I;
782
5.65k
      auto Last = Paths.end() - 1;
783
5.65k
      if (Last != Dom)
784
5.42k
        std::iter_swap(Last, Dom);
785
5.65k
    };
786
1.12M
787
1.12M
    MemoryPhi *Current = Phi;
788
1.41M
    while (true) {
789
1.41M
      assert(!MSSA.isLiveOnEntryDef(Current) &&
790
1.41M
             "liveOnEntry wasn't treated as a clobber?");
791
1.41M
792
1.41M
      const auto *Target = getWalkTarget(Current);
793
1.41M
      // If a TerminatedPath doesn't dominate Target, then it wasn't a legal
794
1.41M
      // optimization for the prior phi.
795
1.41M
      assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {
796
1.41M
        return MSSA.dominates(P.Clobber, Target);
797
1.41M
      }));
798
1.41M
799
1.41M
      // FIXME: This is broken, because the Blocker may be reported to be
800
1.41M
      // liveOnEntry, and we'll happily wait for that to disappear (read: never)
801
1.41M
      // For the moment, this is fine, since we do nothing with blocker info.
802
1.41M
      if (Optional<TerminatedPath> Blocker = getBlockingAccess(
803
991k
              Target, PausedSearches, NewPaused, TerminatedPaths)) {
804
991k
805
991k
        // Find the node we started at. We can't search based on N->Last, since
806
991k
        // we may have gone around a loop with a different MemoryLocation.
807
2.42M
        auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) {
808
2.42M
          return defPathIndex(N) < PriorPathsSize;
809
2.42M
        });
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::tryOptimizePhi(llvm::MemoryPhi*, llvm::MemoryAccess*, llvm::MemoryLocation const&)::'lambda'((anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::DefPath const&)::operator()((anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::DefPath const&) const
Line
Count
Source
807
2.41M
        auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) {
808
2.41M
          return defPathIndex(N) < PriorPathsSize;
809
2.41M
        });
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::AAResults>::tryOptimizePhi(llvm::MemoryPhi*, llvm::MemoryAccess*, llvm::MemoryLocation const&)::'lambda'((anonymous namespace)::ClobberWalker<llvm::AAResults>::DefPath const&)::operator()((anonymous namespace)::ClobberWalker<llvm::AAResults>::DefPath const&) const
Line
Count
Source
807
9.77k
        auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) {
808
9.77k
          return defPathIndex(N) < PriorPathsSize;
809
9.77k
        });
810
991k
        assert(Iter != def_path_iterator());
811
991k
812
991k
        DefPath &CurNode = *Iter;
813
991k
        assert(CurNode.Last == Current);
814
991k
815
991k
        // Two things:
816
991k
        // A. We can't reliably cache all of NewPaused back. Consider a case
817
991k
        //    where we have two paths in NewPaused; one of which can't optimize
818
991k
        //    above this phi, whereas the other can. If we cache the second path
819
991k
        //    back, we'll end up with suboptimal cache entries. We can handle
820
991k
        //    cases like this a bit better when we either try to find all
821
991k
        //    clobbers that block phi optimization, or when our cache starts
822
991k
        //    supporting unfinished searches.
823
991k
        // B. We can't reliably cache TerminatedPaths back here without doing
824
991k
        //    extra checks; consider a case like:
825
991k
        //       T
826
991k
        //      / \
827
991k
        //     D   C
828
991k
        //      \ /
829
991k
        //       S
830
991k
        //    Where T is our target, C is a node with a clobber on it, D is a
831
991k
        //    diamond (with a clobber *only* on the left or right node, N), and
832
991k
        //    S is our start. Say we walk to D, through the node opposite N
833
991k
        //    (read: ignoring the clobber), and see a cache entry in the top
834
991k
        //    node of D. That cache entry gets put into TerminatedPaths. We then
835
991k
        //    walk up to C (N is later in our worklist), find the clobber, and
836
991k
        //    quit. If we append TerminatedPaths to OtherClobbers, we'll cache
837
991k
        //    the bottom part of D to the cached clobber, ignoring the clobber
838
991k
        //    in N. Again, this problem goes away if we start tracking all
839
991k
        //    blockers for a given phi optimization.
840
991k
        TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
841
991k
        return {Result, {}};
842
991k
      }
843
418k
844
418k
      // If there's nothing left to search, then all paths led to valid clobbers
845
418k
      // that we got from our cache; pick the nearest to the start, and allow
846
418k
      // the rest to be cached back.
847
418k
      if (NewPaused.empty()) {
848
0
        MoveDominatedPathToEnd(TerminatedPaths);
849
0
        TerminatedPath Result = TerminatedPaths.pop_back_val();
850
0
        return {Result, std::move(TerminatedPaths)};
851
0
      }
852
418k
853
418k
      MemoryAccess *DefChainEnd = nullptr;
854
418k
      SmallVector<TerminatedPath, 4> Clobbers;
855
664k
      for (ListIndex Paused : NewPaused) {
856
664k
        UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
857
664k
        if (WR.IsKnownClobber)
858
228k
          Clobbers.push_back({WR.Result, Paused});
859
436k
        else
860
436k
          // Micro-opt: If we hit the end of the chain, save it.
861
436k
          DefChainEnd = WR.Result;
862
664k
      }
863
418k
864
418k
      if (!TerminatedPaths.empty()) {
865
0
        // If we couldn't find the dominating phi/liveOnEntry in the above loop,
866
0
        // do it now.
867
0
        if (!DefChainEnd)
868
0
          for (auto *MA : def_chain(const_cast<MemoryAccess *>(Target)))
869
0
            DefChainEnd = MA;
870
0
871
0
        // If any of the terminated paths don't dominate the phi we'll try to
872
0
        // optimize, we need to figure out what they are and quit.
873
0
        const BasicBlock *ChainBB = DefChainEnd->getBlock();
874
0
        for (const TerminatedPath &TP : TerminatedPaths) {
875
0
          // Because we know that DefChainEnd is as "high" as we can go, we
876
0
          // don't need local dominance checks; BB dominance is sufficient.
877
0
          if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
878
0
            Clobbers.push_back(TP);
879
0
        }
880
0
      }
881
418k
882
418k
      // If we have clobbers in the def chain, find the one closest to Current
883
418k
      // and quit.
884
418k
      if (!Clobbers.empty()) {
885
133k
        MoveDominatedPathToEnd(Clobbers);
886
133k
        TerminatedPath Result = Clobbers.pop_back_val();
887
133k
        return {Result, std::move(Clobbers)};
888
133k
      }
889
284k
890
284k
      assert(all_of(NewPaused,
891
284k
                    [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
892
284k
893
284k
      // Because liveOnEntry is a clobber, this must be a phi.
894
284k
      auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
895
284k
896
284k
      PriorPathsSize = Paths.size();
897
284k
      PausedSearches.clear();
898
284k
      for (ListIndex I : NewPaused)
899
436k
        addSearches(DefChainPhi, PausedSearches, I);
900
284k
      NewPaused.clear();
901
284k
902
284k
      Current = DefChainPhi;
903
284k
    }
904
1.12M
  }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::tryOptimizePhi(llvm::MemoryPhi*, llvm::MemoryAccess*, llvm::MemoryLocation const&)
Line
Count
Source
759
1.11M
                             const MemoryLocation &Loc) {
760
1.11M
    assert(Paths.empty() && VisitedPhis.empty() &&
761
1.11M
           "Reset the optimization state.");
762
1.11M
763
1.11M
    Paths.emplace_back(Loc, Start, Phi, None);
764
1.11M
    // Stores how many "valid" optimization nodes we had prior to calling
765
1.11M
    // addSearches/getBlockingAccess. Necessary for caching if we had a blocker.
766
1.11M
    auto PriorPathsSize = Paths.size();
767
1.11M
768
1.11M
    SmallVector<ListIndex, 16> PausedSearches;
769
1.11M
    SmallVector<ListIndex, 8> NewPaused;
770
1.11M
    SmallVector<TerminatedPath, 4> TerminatedPaths;
771
1.11M
772
1.11M
    addSearches(Phi, PausedSearches, 0);
773
1.11M
774
1.11M
    // Moves the TerminatedPath with the "most dominated" Clobber to the end of
775
1.11M
    // Paths.
776
1.11M
    auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
777
1.11M
      assert(!Paths.empty() && "Need a path to move");
778
1.11M
      auto Dom = Paths.begin();
779
1.11M
      for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I)
780
1.11M
        if (!MSSA.dominates(I->Clobber, Dom->Clobber))
781
1.11M
          Dom = I;
782
1.11M
      auto Last = Paths.end() - 1;
783
1.11M
      if (Last != Dom)
784
1.11M
        std::iter_swap(Last, Dom);
785
1.11M
    };
786
1.11M
787
1.11M
    MemoryPhi *Current = Phi;
788
1.39M
    while (true) {
789
1.39M
      assert(!MSSA.isLiveOnEntryDef(Current) &&
790
1.39M
             "liveOnEntry wasn't treated as a clobber?");
791
1.39M
792
1.39M
      const auto *Target = getWalkTarget(Current);
793
1.39M
      // If a TerminatedPath doesn't dominate Target, then it wasn't a legal
794
1.39M
      // optimization for the prior phi.
795
1.39M
      assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {
796
1.39M
        return MSSA.dominates(P.Clobber, Target);
797
1.39M
      }));
798
1.39M
799
1.39M
      // FIXME: This is broken, because the Blocker may be reported to be
800
1.39M
      // liveOnEntry, and we'll happily wait for that to disappear (read: never)
801
1.39M
      // For the moment, this is fine, since we do nothing with blocker info.
802
1.39M
      if (Optional<TerminatedPath> Blocker = getBlockingAccess(
803
987k
              Target, PausedSearches, NewPaused, TerminatedPaths)) {
804
987k
805
987k
        // Find the node we started at. We can't search based on N->Last, since
806
987k
        // we may have gone around a loop with a different MemoryLocation.
807
987k
        auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) {
808
987k
          return defPathIndex(N) < PriorPathsSize;
809
987k
        });
810
987k
        assert(Iter != def_path_iterator());
811
987k
812
987k
        DefPath &CurNode = *Iter;
813
987k
        assert(CurNode.Last == Current);
814
987k
815
987k
        // Two things:
816
987k
        // A. We can't reliably cache all of NewPaused back. Consider a case
817
987k
        //    where we have two paths in NewPaused; one of which can't optimize
818
987k
        //    above this phi, whereas the other can. If we cache the second path
819
987k
        //    back, we'll end up with suboptimal cache entries. We can handle
820
987k
        //    cases like this a bit better when we either try to find all
821
987k
        //    clobbers that block phi optimization, or when our cache starts
822
987k
        //    supporting unfinished searches.
823
987k
        // B. We can't reliably cache TerminatedPaths back here without doing
824
987k
        //    extra checks; consider a case like:
825
987k
        //       T
826
987k
        //      / \
827
987k
        //     D   C
828
987k
        //      \ /
829
987k
        //       S
830
987k
        //    Where T is our target, C is a node with a clobber on it, D is a
831
987k
        //    diamond (with a clobber *only* on the left or right node, N), and
832
987k
        //    S is our start. Say we walk to D, through the node opposite N
833
987k
        //    (read: ignoring the clobber), and see a cache entry in the top
834
987k
        //    node of D. That cache entry gets put into TerminatedPaths. We then
835
987k
        //    walk up to C (N is later in our worklist), find the clobber, and
836
987k
        //    quit. If we append TerminatedPaths to OtherClobbers, we'll cache
837
987k
        //    the bottom part of D to the cached clobber, ignoring the clobber
838
987k
        //    in N. Again, this problem goes away if we start tracking all
839
987k
        //    blockers for a given phi optimization.
840
987k
        TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
841
987k
        return {Result, {}};
842
987k
      }
843
410k
844
410k
      // If there's nothing left to search, then all paths led to valid clobbers
845
410k
      // that we got from our cache; pick the nearest to the start, and allow
846
410k
      // the rest to be cached back.
847
410k
      if (NewPaused.empty()) {
848
0
        MoveDominatedPathToEnd(TerminatedPaths);
849
0
        TerminatedPath Result = TerminatedPaths.pop_back_val();
850
0
        return {Result, std::move(TerminatedPaths)};
851
0
      }
852
410k
853
410k
      MemoryAccess *DefChainEnd = nullptr;
854
410k
      SmallVector<TerminatedPath, 4> Clobbers;
855
649k
      for (ListIndex Paused : NewPaused) {
856
649k
        UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
857
649k
        if (WR.IsKnownClobber)
858
217k
          Clobbers.push_back({WR.Result, Paused});
859
432k
        else
860
432k
          // Micro-opt: If we hit the end of the chain, save it.
861
432k
          DefChainEnd = WR.Result;
862
649k
      }
863
410k
864
410k
      if (!TerminatedPaths.empty()) {
865
0
        // If we couldn't find the dominating phi/liveOnEntry in the above loop,
866
0
        // do it now.
867
0
        if (!DefChainEnd)
868
0
          for (auto *MA : def_chain(const_cast<MemoryAccess *>(Target)))
869
0
            DefChainEnd = MA;
870
0
871
0
        // If any of the terminated paths don't dominate the phi we'll try to
872
0
        // optimize, we need to figure out what they are and quit.
873
0
        const BasicBlock *ChainBB = DefChainEnd->getBlock();
874
0
        for (const TerminatedPath &TP : TerminatedPaths) {
875
0
          // Because we know that DefChainEnd is as "high" as we can go, we
876
0
          // don't need local dominance checks; BB dominance is sufficient.
877
0
          if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
878
0
            Clobbers.push_back(TP);
879
0
        }
880
0
      }
881
410k
882
410k
      // If we have clobbers in the def chain, find the one closest to Current
883
410k
      // and quit.
884
410k
      if (!Clobbers.empty()) {
885
128k
        MoveDominatedPathToEnd(Clobbers);
886
128k
        TerminatedPath Result = Clobbers.pop_back_val();
887
128k
        return {Result, std::move(Clobbers)};
888
128k
      }
889
282k
890
282k
      assert(all_of(NewPaused,
891
282k
                    [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
892
282k
893
282k
      // Because liveOnEntry is a clobber, this must be a phi.
894
282k
      auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
895
282k
896
282k
      PriorPathsSize = Paths.size();
897
282k
      PausedSearches.clear();
898
282k
      for (ListIndex I : NewPaused)
899
431k
        addSearches(DefChainPhi, PausedSearches, I);
900
282k
      NewPaused.clear();
901
282k
902
282k
      Current = DefChainPhi;
903
282k
    }
904
1.11M
  }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::AAResults>::tryOptimizePhi(llvm::MemoryPhi*, llvm::MemoryAccess*, llvm::MemoryLocation const&)
Line
Count
Source
759
10.2k
                             const MemoryLocation &Loc) {
760
10.2k
    assert(Paths.empty() && VisitedPhis.empty() &&
761
10.2k
           "Reset the optimization state.");
762
10.2k
763
10.2k
    Paths.emplace_back(Loc, Start, Phi, None);
764
10.2k
    // Stores how many "valid" optimization nodes we had prior to calling
765
10.2k
    // addSearches/getBlockingAccess. Necessary for caching if we had a blocker.
766
10.2k
    auto PriorPathsSize = Paths.size();
767
10.2k
768
10.2k
    SmallVector<ListIndex, 16> PausedSearches;
769
10.2k
    SmallVector<ListIndex, 8> NewPaused;
770
10.2k
    SmallVector<TerminatedPath, 4> TerminatedPaths;
771
10.2k
772
10.2k
    addSearches(Phi, PausedSearches, 0);
773
10.2k
774
10.2k
    // Moves the TerminatedPath with the "most dominated" Clobber to the end of
775
10.2k
    // Paths.
776
10.2k
    auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
777
10.2k
      assert(!Paths.empty() && "Need a path to move");
778
10.2k
      auto Dom = Paths.begin();
779
10.2k
      for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I)
780
10.2k
        if (!MSSA.dominates(I->Clobber, Dom->Clobber))
781
10.2k
          Dom = I;
782
10.2k
      auto Last = Paths.end() - 1;
783
10.2k
      if (Last != Dom)
784
10.2k
        std::iter_swap(Last, Dom);
785
10.2k
    };
786
10.2k
787
10.2k
    MemoryPhi *Current = Phi;
788
12.3k
    while (true) {
789
12.3k
      assert(!MSSA.isLiveOnEntryDef(Current) &&
790
12.3k
             "liveOnEntry wasn't treated as a clobber?");
791
12.3k
792
12.3k
      const auto *Target = getWalkTarget(Current);
793
12.3k
      // If a TerminatedPath doesn't dominate Target, then it wasn't a legal
794
12.3k
      // optimization for the prior phi.
795
12.3k
      assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {
796
12.3k
        return MSSA.dominates(P.Clobber, Target);
797
12.3k
      }));
798
12.3k
799
12.3k
      // FIXME: This is broken, because the Blocker may be reported to be
800
12.3k
      // liveOnEntry, and we'll happily wait for that to disappear (read: never)
801
12.3k
      // For the moment, this is fine, since we do nothing with blocker info.
802
12.3k
      if (Optional<TerminatedPath> Blocker = getBlockingAccess(
803
4.58k
              Target, PausedSearches, NewPaused, TerminatedPaths)) {
804
4.58k
805
4.58k
        // Find the node we started at. We can't search based on N->Last, since
806
4.58k
        // we may have gone around a loop with a different MemoryLocation.
807
4.58k
        auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) {
808
4.58k
          return defPathIndex(N) < PriorPathsSize;
809
4.58k
        });
810
4.58k
        assert(Iter != def_path_iterator());
811
4.58k
812
4.58k
        DefPath &CurNode = *Iter;
813
4.58k
        assert(CurNode.Last == Current);
814
4.58k
815
4.58k
        // Two things:
816
4.58k
        // A. We can't reliably cache all of NewPaused back. Consider a case
817
4.58k
        //    where we have two paths in NewPaused; one of which can't optimize
818
4.58k
        //    above this phi, whereas the other can. If we cache the second path
819
4.58k
        //    back, we'll end up with suboptimal cache entries. We can handle
820
4.58k
        //    cases like this a bit better when we either try to find all
821
4.58k
        //    clobbers that block phi optimization, or when our cache starts
822
4.58k
        //    supporting unfinished searches.
823
4.58k
        // B. We can't reliably cache TerminatedPaths back here without doing
824
4.58k
        //    extra checks; consider a case like:
825
4.58k
        //       T
826
4.58k
        //      / \
827
4.58k
        //     D   C
828
4.58k
        //      \ /
829
4.58k
        //       S
830
4.58k
        //    Where T is our target, C is a node with a clobber on it, D is a
831
4.58k
        //    diamond (with a clobber *only* on the left or right node, N), and
832
4.58k
        //    S is our start. Say we walk to D, through the node opposite N
833
4.58k
        //    (read: ignoring the clobber), and see a cache entry in the top
834
4.58k
        //    node of D. That cache entry gets put into TerminatedPaths. We then
835
4.58k
        //    walk up to C (N is later in our worklist), find the clobber, and
836
4.58k
        //    quit. If we append TerminatedPaths to OtherClobbers, we'll cache
837
4.58k
        //    the bottom part of D to the cached clobber, ignoring the clobber
838
4.58k
        //    in N. Again, this problem goes away if we start tracking all
839
4.58k
        //    blockers for a given phi optimization.
840
4.58k
        TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
841
4.58k
        return {Result, {}};
842
4.58k
      }
843
7.78k
844
7.78k
      // If there's nothing left to search, then all paths led to valid clobbers
845
7.78k
      // that we got from our cache; pick the nearest to the start, and allow
846
7.78k
      // the rest to be cached back.
847
7.78k
      if (NewPaused.empty()) {
848
0
        MoveDominatedPathToEnd(TerminatedPaths);
849
0
        TerminatedPath Result = TerminatedPaths.pop_back_val();
850
0
        return {Result, std::move(TerminatedPaths)};
851
0
      }
852
7.78k
853
7.78k
      MemoryAccess *DefChainEnd = nullptr;
854
7.78k
      SmallVector<TerminatedPath, 4> Clobbers;
855
15.3k
      for (ListIndex Paused : NewPaused) {
856
15.3k
        UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
857
15.3k
        if (WR.IsKnownClobber)
858
11.1k
          Clobbers.push_back({WR.Result, Paused});
859
4.16k
        else
860
4.16k
          // Micro-opt: If we hit the end of the chain, save it.
861
4.16k
          DefChainEnd = WR.Result;
862
15.3k
      }
863
7.78k
864
7.78k
      if (!TerminatedPaths.empty()) {
865
0
        // If we couldn't find the dominating phi/liveOnEntry in the above loop,
866
0
        // do it now.
867
0
        if (!DefChainEnd)
868
0
          for (auto *MA : def_chain(const_cast<MemoryAccess *>(Target)))
869
0
            DefChainEnd = MA;
870
0
871
0
        // If any of the terminated paths don't dominate the phi we'll try to
872
0
        // optimize, we need to figure out what they are and quit.
873
0
        const BasicBlock *ChainBB = DefChainEnd->getBlock();
874
0
        for (const TerminatedPath &TP : TerminatedPaths) {
875
0
          // Because we know that DefChainEnd is as "high" as we can go, we
876
0
          // don't need local dominance checks; BB dominance is sufficient.
877
0
          if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
878
0
            Clobbers.push_back(TP);
879
0
        }
880
0
      }
881
7.78k
882
7.78k
      // If we have clobbers in the def chain, find the one closest to Current
883
7.78k
      // and quit.
884
7.78k
      if (!Clobbers.empty()) {
885
5.65k
        MoveDominatedPathToEnd(Clobbers);
886
5.65k
        TerminatedPath Result = Clobbers.pop_back_val();
887
5.65k
        return {Result, std::move(Clobbers)};
888
5.65k
      }
889
2.13k
890
2.13k
      assert(all_of(NewPaused,
891
2.13k
                    [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
892
2.13k
893
2.13k
      // Because liveOnEntry is a clobber, this must be a phi.
894
2.13k
      auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
895
2.13k
896
2.13k
      PriorPathsSize = Paths.size();
897
2.13k
      PausedSearches.clear();
898
2.13k
      for (ListIndex I : NewPaused)
899
4.08k
        addSearches(DefChainPhi, PausedSearches, I);
900
2.13k
      NewPaused.clear();
901
2.13k
902
2.13k
      Current = DefChainPhi;
903
2.13k
    }
904
10.2k
  }
905
906
1.12M
  void verifyOptResult(const OptznResult &R) const {
907
1.12M
    assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
908
1.12M
      return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
909
1.12M
    }));
910
1.12M
  }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::verifyOptResult((anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::OptznResult const&) const
Line
Count
Source
906
1.11M
  void verifyOptResult(const OptznResult &R) const {
907
1.11M
    assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
908
1.11M
      return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
909
1.11M
    }));
910
1.11M
  }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::AAResults>::verifyOptResult((anonymous namespace)::ClobberWalker<llvm::AAResults>::OptznResult const&) const
Line
Count
Source
906
10.2k
  void verifyOptResult(const OptznResult &R) const {
907
10.2k
    assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
908
10.2k
      return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
909
10.2k
    }));
910
10.2k
  }
911
912
1.12M
  void resetPhiOptznState() {
913
1.12M
    Paths.clear();
914
1.12M
    VisitedPhis.clear();
915
1.12M
  }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::resetPhiOptznState()
Line
Count
Source
912
1.11M
  void resetPhiOptznState() {
913
1.11M
    Paths.clear();
914
1.11M
    VisitedPhis.clear();
915
1.11M
  }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::AAResults>::resetPhiOptznState()
Line
Count
Source
912
10.2k
  void resetPhiOptznState() {
913
10.2k
    Paths.clear();
914
10.2k
    VisitedPhis.clear();
915
10.2k
  }
916
917
public:
918
  ClobberWalker(const MemorySSA &MSSA, AliasAnalysisType &AA, DominatorTree &DT)
919
1.44M
      : MSSA(MSSA), AA(AA), DT(DT) {}
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::ClobberWalker(llvm::MemorySSA const&, llvm::BatchAAResults&, llvm::DominatorTree&)
Line
Count
Source
919
724k
      : MSSA(MSSA), AA(AA), DT(DT) {}
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::AAResults>::ClobberWalker(llvm::MemorySSA const&, llvm::AAResults&, llvm::DominatorTree&)
Line
Count
Source
919
724k
      : MSSA(MSSA), AA(AA), DT(DT) {}
920
921
1.12M
  AliasAnalysisType *getAA() { return &AA; }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::getAA()
Line
Count
Source
921
1.11M
  AliasAnalysisType *getAA() { return &AA; }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::AAResults>::getAA()
Line
Count
Source
921
14.5k
  AliasAnalysisType *getAA() { return &AA; }
922
  /// Finds the nearest clobber for the given query, optimizing phis if
923
  /// possible.
924
  MemoryAccess *findClobber(MemoryAccess *Start, UpwardsMemoryQuery &Q,
925
1.12M
                            unsigned &UpWalkLimit) {
926
1.12M
    Query = &Q;
927
1.12M
    UpwardWalkLimit = &UpWalkLimit;
928
1.12M
    // Starting limit must be > 0.
929
1.12M
    if (!UpWalkLimit)
930
0
      UpWalkLimit++;
931
1.12M
932
1.12M
    MemoryAccess *Current = Start;
933
1.12M
    // This walker pretends uses don't exist. If we're handed one, silently grab
934
1.12M
    // its def. (This has the nice side-effect of ensuring we never cache uses)
935
1.12M
    if (auto *MU = dyn_cast<MemoryUse>(Start))
936
0
      Current = MU->getDefiningAccess();
937
1.12M
938
1.12M
    DefPath FirstDesc(Q.StartingLoc, Current, Current, None);
939
1.12M
    // Fast path for the overly-common case (no crazy phi optimization
940
1.12M
    // necessary)
941
1.12M
    UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
942
1.12M
    MemoryAccess *Result;
943
1.12M
    if (WalkResult.IsKnownClobber) {
944
4.36k
      Result = WalkResult.Result;
945
4.36k
      Q.AR = WalkResult.AR;
946
1.12M
    } else {
947
1.12M
      OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
948
1.12M
                                          Current, Q.StartingLoc);
949
1.12M
      verifyOptResult(OptRes);
950
1.12M
      resetPhiOptznState();
951
1.12M
      Result = OptRes.PrimaryClobber.Clobber;
952
1.12M
    }
953
1.12M
954
#ifdef EXPENSIVE_CHECKS
955
    if (!Q.SkipSelfAccess && *UpwardWalkLimit > 0)
956
      checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, AA);
957
#endif
958
    return Result;
959
1.12M
  }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::BatchAAResults>::findClobber(llvm::MemoryAccess*, (anonymous namespace)::UpwardsMemoryQuery&, unsigned int&)
Line
Count
Source
925
1.11M
                            unsigned &UpWalkLimit) {
926
1.11M
    Query = &Q;
927
1.11M
    UpwardWalkLimit = &UpWalkLimit;
928
1.11M
    // Starting limit must be > 0.
929
1.11M
    if (!UpWalkLimit)
930
0
      UpWalkLimit++;
931
1.11M
932
1.11M
    MemoryAccess *Current = Start;
933
1.11M
    // This walker pretends uses don't exist. If we're handed one, silently grab
934
1.11M
    // its def. (This has the nice side-effect of ensuring we never cache uses)
935
1.11M
    if (auto *MU = dyn_cast<MemoryUse>(Start))
936
0
      Current = MU->getDefiningAccess();
937
1.11M
938
1.11M
    DefPath FirstDesc(Q.StartingLoc, Current, Current, None);
939
1.11M
    // Fast path for the overly-common case (no crazy phi optimization
940
1.11M
    // necessary)
941
1.11M
    UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
942
1.11M
    MemoryAccess *Result;
943
1.11M
    if (WalkResult.IsKnownClobber) {
944
0
      Result = WalkResult.Result;
945
0
      Q.AR = WalkResult.AR;
946
1.11M
    } else {
947
1.11M
      OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
948
1.11M
                                          Current, Q.StartingLoc);
949
1.11M
      verifyOptResult(OptRes);
950
1.11M
      resetPhiOptznState();
951
1.11M
      Result = OptRes.PrimaryClobber.Clobber;
952
1.11M
    }
953
1.11M
954
#ifdef EXPENSIVE_CHECKS
955
    if (!Q.SkipSelfAccess && *UpwardWalkLimit > 0)
956
      checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, AA);
957
#endif
958
    return Result;
959
1.11M
  }
MemorySSA.cpp:(anonymous namespace)::ClobberWalker<llvm::AAResults>::findClobber(llvm::MemoryAccess*, (anonymous namespace)::UpwardsMemoryQuery&, unsigned int&)
Line
Count
Source
925
14.5k
                            unsigned &UpWalkLimit) {
926
14.5k
    Query = &Q;
927
14.5k
    UpwardWalkLimit = &UpWalkLimit;
928
14.5k
    // Starting limit must be > 0.
929
14.5k
    if (!UpWalkLimit)
930
0
      UpWalkLimit++;
931
14.5k
932
14.5k
    MemoryAccess *Current = Start;
933
14.5k
    // This walker pretends uses don't exist. If we're handed one, silently grab
934
14.5k
    // its def. (This has the nice side-effect of ensuring we never cache uses)
935
14.5k
    if (auto *MU = dyn_cast<MemoryUse>(Start))
936
0
      Current = MU->getDefiningAccess();
937
14.5k
938
14.5k
    DefPath FirstDesc(Q.StartingLoc, Current, Current, None);
939
14.5k
    // Fast path for the overly-common case (no crazy phi optimization
940
14.5k
    // necessary)
941
14.5k
    UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
942
14.5k
    MemoryAccess *Result;
943
14.5k
    if (WalkResult.IsKnownClobber) {
944
4.36k
      Result = WalkResult.Result;
945
4.36k
      Q.AR = WalkResult.AR;
946
10.2k
    } else {
947
10.2k
      OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
948
10.2k
                                          Current, Q.StartingLoc);
949
10.2k
      verifyOptResult(OptRes);
950
10.2k
      resetPhiOptznState();
951
10.2k
      Result = OptRes.PrimaryClobber.Clobber;
952
10.2k
    }
953
14.5k
954
#ifdef EXPENSIVE_CHECKS
955
    if (!Q.SkipSelfAccess && *UpwardWalkLimit > 0)
956
      checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, AA);
957
#endif
958
    return Result;
959
14.5k
  }
960
};
961
962
struct RenamePassData {
963
  DomTreeNode *DTN;
964
  DomTreeNode::const_iterator ChildIt;
965
  MemoryAccess *IncomingVal;
966
967
  RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
968
                 MemoryAccess *M)
969
4.89M
      : DTN(D), ChildIt(It), IncomingVal(M) {}
970
971
0
  void swap(RenamePassData &RHS) {
972
0
    std::swap(DTN, RHS.DTN);
973
0
    std::swap(ChildIt, RHS.ChildIt);
974
0
    std::swap(IncomingVal, RHS.IncomingVal);
975
0
  }
976
};
977
978
} // end anonymous namespace
979
980
namespace llvm {
981
982
template <class AliasAnalysisType> class MemorySSA::ClobberWalkerBase {
983
  ClobberWalker<AliasAnalysisType> Walker;
984
  MemorySSA *MSSA;
985
986
public:
987
  ClobberWalkerBase(MemorySSA *M, AliasAnalysisType *A, DominatorTree *D)
988
1.44M
      : Walker(*M, *A, *D), MSSA(M) {}
llvm::MemorySSA::ClobberWalkerBase<llvm::BatchAAResults>::ClobberWalkerBase(llvm::MemorySSA*, llvm::BatchAAResults*, llvm::DominatorTree*)
Line
Count
Source
988
724k
      : Walker(*M, *A, *D), MSSA(M) {}
llvm::MemorySSA::ClobberWalkerBase<llvm::AAResults>::ClobberWalkerBase(llvm::MemorySSA*, llvm::AAResults*, llvm::DominatorTree*)
Line
Count
Source
988
724k
      : Walker(*M, *A, *D), MSSA(M) {}
989
990
  MemoryAccess *getClobberingMemoryAccessBase(MemoryAccess *,
991
                                              const MemoryLocation &,
992
                                              unsigned &);
993
  // Third argument (bool), defines whether the clobber search should skip the
994
  // original queried access. If true, there will be a follow-up query searching
995
  // for a clobber access past "self". Note that the Optimized access is not
996
  // updated if a new clobber is found by this SkipSelf search. If this
997
  // additional query becomes heavily used we may decide to cache the result.
998
  // Walker instantiations will decide how to set the SkipSelf bool.
999
  MemoryAccess *getClobberingMemoryAccessBase(MemoryAccess *, unsigned &, bool);
1000
};
1001
1002
/// A MemorySSAWalker that does AA walks to disambiguate accesses. It no
1003
/// longer does caching on its own, but the name has been retained for the
1004
/// moment.
1005
template <class AliasAnalysisType>
1006
class MemorySSA::CachingWalker final : public MemorySSAWalker {
1007
  ClobberWalkerBase<AliasAnalysisType> *Walker;
1008
1009
public:
1010
  CachingWalker(MemorySSA *M, ClobberWalkerBase<AliasAnalysisType> *W)
1011
1.44M
      : MemorySSAWalker(M), Walker(W) {}
llvm::MemorySSA::CachingWalker<llvm::BatchAAResults>::CachingWalker(llvm::MemorySSA*, llvm::MemorySSA::ClobberWalkerBase<llvm::BatchAAResults>*)
Line
Count
Source
1011
724k
      : MemorySSAWalker(M), Walker(W) {}
llvm::MemorySSA::CachingWalker<llvm::AAResults>::CachingWalker(llvm::MemorySSA*, llvm::MemorySSA::ClobberWalkerBase<llvm::AAResults>*)
Line
Count
Source
1011
724k
      : MemorySSAWalker(M), Walker(W) {}
1012
1.44M
  ~CachingWalker() override = default;
llvm::MemorySSA::CachingWalker<llvm::BatchAAResults>::~CachingWalker()
Line
Count
Source
1012
724k
  ~CachingWalker() override = default;
llvm::MemorySSA::CachingWalker<llvm::AAResults>::~CachingWalker()
Line
Count
Source
1012
724k
  ~CachingWalker() override = default;
1013
1014
  using MemorySSAWalker::getClobberingMemoryAccess;
1015
1016
1.41M
  MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA, unsigned &UWL) {
1017
1.41M
    return Walker->getClobberingMemoryAccessBase(MA, UWL, false);
1018
1.41M
  }
llvm::MemorySSA::CachingWalker<llvm::BatchAAResults>::getClobberingMemoryAccess(llvm::MemoryAccess*, unsigned int&)
Line
Count
Source
1016
1.11M
  MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA, unsigned &UWL) {
1017
1.11M
    return Walker->getClobberingMemoryAccessBase(MA, UWL, false);
1018
1.11M
  }
llvm::MemorySSA::CachingWalker<llvm::AAResults>::getClobberingMemoryAccess(llvm::MemoryAccess*, unsigned int&)
Line
Count
Source
1016
302k
  MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA, unsigned &UWL) {
1017
302k
    return Walker->getClobberingMemoryAccessBase(MA, UWL, false);
1018
302k
  }
1019
  MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
1020
                                          const MemoryLocation &Loc,
1021
2
                                          unsigned &UWL) {
1022
2
    return Walker->getClobberingMemoryAccessBase(MA, Loc, UWL);
1023
2
  }
Unexecuted instantiation: llvm::MemorySSA::CachingWalker<llvm::BatchAAResults>::getClobberingMemoryAccess(llvm::MemoryAccess*, llvm::MemoryLocation const&, unsigned int&)
llvm::MemorySSA::CachingWalker<llvm::AAResults>::getClobberingMemoryAccess(llvm::MemoryAccess*, llvm::MemoryLocation const&, unsigned int&)
Line
Count
Source
1021
2
                                          unsigned &UWL) {
1022
2
    return Walker->getClobberingMemoryAccessBase(MA, Loc, UWL);
1023
2
  }
1024
1025
302k
  MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA) override {
1026
302k
    unsigned UpwardWalkLimit = MaxCheckLimit;
1027
302k
    return getClobberingMemoryAccess(MA, UpwardWalkLimit);
1028
302k
  }
Unexecuted instantiation: llvm::MemorySSA::CachingWalker<llvm::BatchAAResults>::getClobberingMemoryAccess(llvm::MemoryAccess*)
llvm::MemorySSA::CachingWalker<llvm::AAResults>::getClobberingMemoryAccess(llvm::MemoryAccess*)
Line
Count
Source
1025
302k
  MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA) override {
1026
302k
    unsigned UpwardWalkLimit = MaxCheckLimit;
1027
302k
    return getClobberingMemoryAccess(MA, UpwardWalkLimit);
1028
302k
  }
1029
  MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
1030
2
                                          const MemoryLocation &Loc) override {
1031
2
    unsigned UpwardWalkLimit = MaxCheckLimit;
1032
2
    return getClobberingMemoryAccess(MA, Loc, UpwardWalkLimit);
1033
2
  }
Unexecuted instantiation: llvm::MemorySSA::CachingWalker<llvm::BatchAAResults>::getClobberingMemoryAccess(llvm::MemoryAccess*, llvm::MemoryLocation const&)
llvm::MemorySSA::CachingWalker<llvm::AAResults>::getClobberingMemoryAccess(llvm::MemoryAccess*, llvm::MemoryLocation const&)
Line
Count
Source
1030
2
                                          const MemoryLocation &Loc) override {
1031
2
    unsigned UpwardWalkLimit = MaxCheckLimit;
1032
2
    return getClobberingMemoryAccess(MA, Loc, UpwardWalkLimit);
1033
2
  }
1034
1035
8.39k
  void invalidateInfo(MemoryAccess *MA) override {
1036
8.39k
    if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1037
7.70k
      MUD->resetOptimized();
1038
8.39k
  }
Unexecuted instantiation: llvm::MemorySSA::CachingWalker<llvm::BatchAAResults>::invalidateInfo(llvm::MemoryAccess*)
llvm::MemorySSA::CachingWalker<llvm::AAResults>::invalidateInfo(llvm::MemoryAccess*)
Line
Count
Source
1035
8.39k
  void invalidateInfo(MemoryAccess *MA) override {
1036
8.39k
    if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1037
7.70k
      MUD->resetOptimized();
1038
8.39k
  }
1039
};
1040
1041
template <class AliasAnalysisType>
1042
class MemorySSA::SkipSelfWalker final : public MemorySSAWalker {
1043
  ClobberWalkerBase<AliasAnalysisType> *Walker;
1044
1045
public:
1046
  SkipSelfWalker(MemorySSA *M, ClobberWalkerBase<AliasAnalysisType> *W)
1047
79
      : MemorySSAWalker(M), Walker(W) {}
1048
79
  ~SkipSelfWalker() override = default;
1049
1050
  using MemorySSAWalker::getClobberingMemoryAccess;
1051
1052
128
  MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA, unsigned &UWL) {
1053
128
    return Walker->getClobberingMemoryAccessBase(MA, UWL, true);
1054
128
  }
1055
  MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
1056
                                          const MemoryLocation &Loc,
1057
0
                                          unsigned &UWL) {
1058
0
    return Walker->getClobberingMemoryAccessBase(MA, Loc, UWL);
1059
0
  }
1060
1061
128
  MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA) override {
1062
128
    unsigned UpwardWalkLimit = MaxCheckLimit;
1063
128
    return getClobberingMemoryAccess(MA, UpwardWalkLimit);
1064
128
  }
1065
  MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
1066
0
                                          const MemoryLocation &Loc) override {
1067
0
    unsigned UpwardWalkLimit = MaxCheckLimit;
1068
0
    return getClobberingMemoryAccess(MA, Loc, UpwardWalkLimit);
1069
0
  }
1070
1071
0
  void invalidateInfo(MemoryAccess *MA) override {
1072
0
    if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1073
0
      MUD->resetOptimized();
1074
0
  }
1075
};
1076
1077
} // end namespace llvm
1078
1079
void MemorySSA::renameSuccessorPhis(BasicBlock *BB, MemoryAccess *IncomingVal,
1080
4.89M
                                    bool RenameAllUses) {
1081
4.89M
  // Pass through values to our successors
1082
6.48M
  for (const BasicBlock *S : successors(BB)) {
1083
6.48M
    auto It = PerBlockAccesses.find(S);
1084
6.48M
    // Rename the phi nodes in our successor block
1085
6.48M
    if (It == PerBlockAccesses.end() || 
!isa<MemoryPhi>(It->second->front())5.27M
)
1086
3.32M
      continue;
1087
3.16M
    AccessList *Accesses = It->second.get();
1088
3.16M
    auto *Phi = cast<MemoryPhi>(&Accesses->front());
1089
3.16M
    if (RenameAllUses) {
1090
2
      int PhiIndex = Phi->getBasicBlockIndex(BB);
1091
2
      assert(PhiIndex != -1 && "Incomplete phi during partial rename");
1092
2
      Phi->setIncomingValue(PhiIndex, IncomingVal);
1093
2
    } else
1094
3.16M
      Phi->addIncoming(IncomingVal, BB);
1095
3.16M
  }
1096
4.89M
}
1097
1098
/// Rename a single basic block into MemorySSA form.
1099
/// Uses the standard SSA renaming algorithm.
1100
/// \returns The new incoming value.
1101
MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB, MemoryAccess *IncomingVal,
1102
4.89M
                                     bool RenameAllUses) {
1103
4.89M
  auto It = PerBlockAccesses.find(BB);
1104
4.89M
  // Skip most processing if the list is empty.
1105
4.89M
  if (It != PerBlockAccesses.end()) {
1106
3.69M
    AccessList *Accesses = It->second.get();
1107
9.78M
    for (MemoryAccess &L : *Accesses) {
1108
9.78M
      if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&L)) {
1109
8.56M
        if (MUD->getDefiningAccess() == nullptr || 
RenameAllUses16
)
1110
8.56M
          MUD->setDefiningAccess(IncomingVal);
1111
8.56M
        if (isa<MemoryDef>(&L))
1112
5.45M
          IncomingVal = &L;
1113
8.56M
      } else {
1114
1.22M
        IncomingVal = &L;
1115
1.22M
      }
1116
9.78M
    }
1117
3.69M
  }
1118
4.89M
  return IncomingVal;
1119
4.89M
}
1120
1121
/// This is the standard SSA renaming algorithm.
1122
///
1123
/// We walk the dominator tree in preorder, renaming accesses, and then filling
1124
/// in phi nodes in our successors.
1125
void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
1126
                           SmallPtrSetImpl<BasicBlock *> &Visited,
1127
724k
                           bool SkipVisited, bool RenameAllUses) {
1128
724k
  assert(Root && "Trying to rename accesses in an unreachable block");
1129
724k
1130
724k
  SmallVector<RenamePassData, 32> WorkStack;
1131
724k
  // Skip everything if we already renamed this block and we are skipping.
1132
724k
  // Note: You can't sink this into the if, because we need it to occur
1133
724k
  // regardless of whether we skip blocks or not.
1134
724k
  bool AlreadyVisited = !Visited.insert(Root->getBlock()).second;
1135
724k
  if (SkipVisited && 
AlreadyVisited12
)
1136
0
    return;
1137
724k
1138
724k
  IncomingVal = renameBlock(Root->getBlock(), IncomingVal, RenameAllUses);
1139
724k
  renameSuccessorPhis(Root->getBlock(), IncomingVal, RenameAllUses);
1140
724k
  WorkStack.push_back({Root, Root->begin(), IncomingVal});
1141
724k
1142
9.78M
  while (!WorkStack.empty()) {
1143
9.06M
    DomTreeNode *Node = WorkStack.back().DTN;
1144
9.06M
    DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
1145
9.06M
    IncomingVal = WorkStack.back().IncomingVal;
1146
9.06M
1147
9.06M
    if (ChildIt == Node->end()) {
1148
4.89M
      WorkStack.pop_back();
1149
4.89M
    } else {
1150
4.16M
      DomTreeNode *Child = *ChildIt;
1151
4.16M
      ++WorkStack.back().ChildIt;
1152
4.16M
      BasicBlock *BB = Child->getBlock();
1153
4.16M
      // Note: You can't sink this into the if, because we need it to occur
1154
4.16M
      // regardless of whether we skip blocks or not.
1155
4.16M
      AlreadyVisited = !Visited.insert(BB).second;
1156
4.16M
      if (SkipVisited && 
AlreadyVisited3
) {
1157
0
        // We already visited this during our renaming, which can happen when
1158
0
        // being asked to rename multiple blocks. Figure out the incoming val,
1159
0
        // which is the last def.
1160
0
        // Incoming value can only change if there is a block def, and in that
1161
0
        // case, it's the last block def in the list.
1162
0
        if (auto *BlockDefs = getWritableBlockDefs(BB))
1163
0
          IncomingVal = &*BlockDefs->rbegin();
1164
0
      } else
1165
4.16M
        IncomingVal = renameBlock(BB, IncomingVal, RenameAllUses);
1166
4.16M
      renameSuccessorPhis(BB, IncomingVal, RenameAllUses);
1167
4.16M
      WorkStack.push_back({Child, Child->begin(), IncomingVal});
1168
4.16M
    }
1169
9.06M
  }
1170
724k
}
1171
1172
/// This handles unreachable block accesses by deleting phi nodes in
1173
/// unreachable blocks, and marking all other unreachable MemoryAccess's as
1174
/// being uses of the live on entry definition.
1175
9.26k
void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
1176
9.26k
  assert(!DT->isReachableFromEntry(BB) &&
1177
9.26k
         "Reachable block found while handling unreachable blocks");
1178
9.26k
1179
9.26k
  // Make sure phi nodes in our reachable successors end up with a
1180
9.26k
  // LiveOnEntryDef for our incoming edge, even though our block is forward
1181
9.26k
  // unreachable.  We could just disconnect these blocks from the CFG fully,
1182
9.26k
  // but we do not right now.
1183
9.26k
  for (const BasicBlock *S : successors(BB)) {
1184
6.71k
    if (!DT->isReachableFromEntry(S))
1185
4.49k
      continue;
1186
2.22k
    auto It = PerBlockAccesses.find(S);
1187
2.22k
    // Rename the phi nodes in our successor block
1188
2.22k
    if (It == PerBlockAccesses.end() || 
!isa<MemoryPhi>(It->second->front())1.36k
)
1189
1.84k
      continue;
1190
377
    AccessList *Accesses = It->second.get();
1191
377
    auto *Phi = cast<MemoryPhi>(&Accesses->front());
1192
377
    Phi->addIncoming(LiveOnEntryDef.get(), BB);
1193
377
  }
1194
9.26k
1195
9.26k
  auto It = PerBlockAccesses.find(BB);
1196
9.26k
  if (It == PerBlockAccesses.end())
1197
3.73k
    return;
1198
5.53k
1199
5.53k
  auto &Accesses = It->second;
1200
12.2k
  for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1201
6.72k
    auto Next = std::next(AI);
1202
6.72k
    // If we have a phi, just remove it. We are going to replace all
1203
6.72k
    // users with live on entry.
1204
6.72k
    if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1205
6.72k
      UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1206
0
    else
1207
0
      Accesses->erase(AI);
1208
6.72k
    AI = Next;
1209
6.72k
  }
1210
5.53k
}
1211
1212
MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
1213
    : AA(nullptr), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
1214
724k
      SkipWalker(nullptr), NextID(0) {
1215
724k
  // Build MemorySSA using a batch alias analysis. This reuses the internal
1216
724k
  // state that AA collects during an alias()/getModRefInfo() call. This is
1217
724k
  // safe because there are no CFG changes while building MemorySSA and can
1218
724k
  // significantly reduce the time spent by the compiler in AA, because we will
1219
724k
  // make queries about all the instructions in the Function.
1220
724k
  BatchAAResults BatchAA(*AA);
1221
724k
  buildMemorySSA(BatchAA);
1222
724k
  // Intentionally leave AA to nullptr while building so we don't accidently
1223
724k
  // use non-batch AliasAnalysis.
1224
724k
  this->AA = AA;
1225
724k
  // Also create the walker here.
1226
724k
  getWalker();
1227
724k
}
1228
1229
724k
MemorySSA::~MemorySSA() {
1230
724k
  // Drop all our references
1231
724k
  for (const auto &Pair : PerBlockAccesses)
1232
3.68M
    for (MemoryAccess &MA : *Pair.second)
1233
9.68M
      MA.dropAllReferences();
1234
724k
}
1235
1236
4.49M
MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
1237
4.49M
  auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
1238
4.49M
1239
4.49M
  if (Res.second)
1240
3.69M
    Res.first->second = llvm::make_unique<AccessList>();
1241
4.49M
  return Res.first->second.get();
1242
4.49M
}
1243
1244
3.65M
MemorySSA::DefsList *MemorySSA::getOrCreateDefsList(const BasicBlock *BB) {
1245
3.65M
  auto Res = PerBlockDefs.insert(std::make_pair(BB, nullptr));
1246
3.65M
1247
3.65M
  if (Res.second)
1248
3.06M
    Res.first->second = llvm::make_unique<DefsList>();
1249
3.65M
  return Res.first->second.get();
1250
3.65M
}
1251
1252
namespace llvm {
1253
1254
/// This class is a batch walker of all MemoryUse's in the program, and points
1255
/// their defining access at the thing that actually clobbers them.  Because it
1256
/// is a batch walker that touches everything, it does not operate like the
1257
/// other walkers.  This walker is basically performing a top-down SSA renaming
1258
/// pass, where the version stack is used as the cache.  This enables it to be
1259
/// significantly more time and memory efficient than using the regular walker,
1260
/// which is walking bottom-up.
1261
class MemorySSA::OptimizeUses {
1262
public:
1263
  OptimizeUses(MemorySSA *MSSA, CachingWalker<BatchAAResults> *Walker,
1264
               BatchAAResults *BAA, DominatorTree *DT)
1265
724k
      : MSSA(MSSA), Walker(Walker), AA(BAA), DT(DT) {}
1266
1267
  void optimizeUses();
1268
1269
private:
1270
  /// This represents where a given memorylocation is in the stack.
1271
  struct MemlocStackInfo {
1272
    // This essentially is keeping track of versions of the stack. Whenever
1273
    // the stack changes due to pushes or pops, these versions increase.
1274
    unsigned long StackEpoch;
1275
    unsigned long PopEpoch;
1276
    // This is the lower bound of places on the stack to check. It is equal to
1277
    // the place the last stack walk ended.
1278
    // Note: Correctness depends on this being initialized to 0, which densemap
1279
    // does
1280
    unsigned long LowerBound;
1281
    const BasicBlock *LowerBoundBlock;
1282
    // This is where the last walk for this memory location ended.
1283
    unsigned long LastKill;
1284
    bool LastKillValid;
1285
    Optional<AliasResult> AR;
1286
  };
1287
1288
  void optimizeUsesInBlock(const BasicBlock *, unsigned long &, unsigned long &,
1289
                           SmallVectorImpl<MemoryAccess *> &,
1290
                           DenseMap<MemoryLocOrCall, MemlocStackInfo> &);
1291
1292
  MemorySSA *MSSA;
1293
  CachingWalker<BatchAAResults> *Walker;
1294
  BatchAAResults *AA;
1295
  DominatorTree *DT;
1296
};
1297
1298
} // end namespace llvm
1299
1300
/// Optimize the uses in a given block This is basically the SSA renaming
1301
/// algorithm, with one caveat: We are able to use a single stack for all
1302
/// MemoryUses.  This is because the set of *possible* reaching MemoryDefs is
1303
/// the same for every MemoryUse.  The *actual* clobbering MemoryDef is just
1304
/// going to be some position in that stack of possible ones.
1305
///
1306
/// We track the stack positions that each MemoryLocation needs
1307
/// to check, and last ended at.  This is because we only want to check the
1308
/// things that changed since last time.  The same MemoryLocation should
1309
/// get clobbered by the same store (getModRefInfo does not use invariantness or
1310
/// things like this, and if they start, we can modify MemoryLocOrCall to
1311
/// include relevant data)
1312
void MemorySSA::OptimizeUses::optimizeUsesInBlock(
1313
    const BasicBlock *BB, unsigned long &StackEpoch, unsigned long &PopEpoch,
1314
    SmallVectorImpl<MemoryAccess *> &VersionStack,
1315
4.89M
    DenseMap<MemoryLocOrCall, MemlocStackInfo> &LocStackInfo) {
1316
4.89M
1317
4.89M
  /// If no accesses, nothing to do.
1318
4.89M
  MemorySSA::AccessList *Accesses = MSSA->getWritableBlockAccesses(BB);
1319
4.89M
  if (Accesses == nullptr)
1320
1.20M
    return;
1321
3.69M
1322
3.69M
  // Pop everything that doesn't dominate the current block off the stack,
1323
3.69M
  // increment the PopEpoch to account for this.
1324
5.89M
  
while (3.69M
true) {
1325
5.89M
    assert(
1326
5.89M
        !VersionStack.empty() &&
1327
5.89M
        "Version stack should have liveOnEntry sentinel dominating everything");
1328
5.89M
    BasicBlock *BackBlock = VersionStack.back()->getBlock();
1329
5.89M
    if (DT->dominates(BackBlock, BB))
1330
3.69M
      break;
1331
6.56M
    
while (2.20M
VersionStack.back()->getBlock() == BackBlock)
1332
4.35M
      VersionStack.pop_back();
1333
2.20M
    ++PopEpoch;
1334
2.20M
  }
1335
3.69M
1336
9.78M
  for (MemoryAccess &MA : *Accesses) {
1337
9.78M
    auto *MU = dyn_cast<MemoryUse>(&MA);
1338
9.78M
    if (!MU) {
1339
6.67M
      VersionStack.push_back(&MA);
1340
6.67M
      ++StackEpoch;
1341
6.67M
      continue;
1342
6.67M
    }
1343
3.11M
1344
3.11M
    if (isUseTriviallyOptimizableToLiveOnEntry(*AA, MU->getMemoryInst())) {
1345
16.0k
      MU->setDefiningAccess(MSSA->getLiveOnEntryDef(), true, None);
1346
16.0k
      continue;
1347
16.0k
    }
1348
3.09M
1349
3.09M
    MemoryLocOrCall UseMLOC(MU);
1350
3.09M
    auto &LocInfo = LocStackInfo[UseMLOC];
1351
3.09M
    // If the pop epoch changed, it means we've removed stuff from top of
1352
3.09M
    // stack due to changing blocks. We may have to reset the lower bound or
1353
3.09M
    // last kill info.
1354
3.09M
    if (LocInfo.PopEpoch != PopEpoch) {
1355
2.93M
      LocInfo.PopEpoch = PopEpoch;
1356
2.93M
      LocInfo.StackEpoch = StackEpoch;
1357
2.93M
      // If the lower bound was in something that no longer dominates us, we
1358
2.93M
      // have to reset it.
1359
2.93M
      // We can't simply track stack size, because the stack may have had
1360
2.93M
      // pushes/pops in the meantime.
1361
2.93M
      // XXX: This is non-optimal, but only is slower cases with heavily
1362
2.93M
      // branching dominator trees.  To get the optimal number of queries would
1363
2.93M
      // be to make lowerbound and lastkill a per-loc stack, and pop it until
1364
2.93M
      // the top of that stack dominates us.  This does not seem worth it ATM.
1365
2.93M
      // A much cheaper optimization would be to always explore the deepest
1366
2.93M
      // branch of the dominator tree first. This will guarantee this resets on
1367
2.93M
      // the smallest set of blocks.
1368
2.93M
      if (LocInfo.LowerBoundBlock && 
LocInfo.LowerBoundBlock != BB292k
&&
1369
2.93M
          
!DT->dominates(LocInfo.LowerBoundBlock, BB)292k
) {
1370
147k
        // Reset the lower bound of things to check.
1371
147k
        // TODO: Some day we should be able to reset to last kill, rather than
1372
147k
        // 0.
1373
147k
        LocInfo.LowerBound = 0;
1374
147k
        LocInfo.LowerBoundBlock = VersionStack[0]->getBlock();
1375
147k
        LocInfo.LastKillValid = false;
1376
147k
      }
1377
2.93M
    } else 
if (163k
LocInfo.StackEpoch != StackEpoch163k
) {
1378
148k
      // If all that has changed is the StackEpoch, we only have to check the
1379
148k
      // new things on the stack, because we've checked everything before.  In
1380
148k
      // this case, the lower bound of things to check remains the same.
1381
148k
      LocInfo.PopEpoch = PopEpoch;
1382
148k
      LocInfo.StackEpoch = StackEpoch;
1383
148k
    }
1384
3.09M
    if (!LocInfo.LastKillValid) {
1385
2.79M
      LocInfo.LastKill = VersionStack.size() - 1;
1386
2.79M
      LocInfo.LastKillValid = true;
1387
2.79M
      LocInfo.AR = MayAlias;
1388
2.79M
    }
1389
3.09M
1390
3.09M
    // At this point, we should have corrected last kill and LowerBound to be
1391
3.09M
    // in bounds.
1392
3.09M
    assert(LocInfo.LowerBound < VersionStack.size() &&
1393
3.09M
           "Lower bound out of range");
1394
3.09M
    assert(LocInfo.LastKill < VersionStack.size() &&
1395
3.09M
           "Last kill info out of range");
1396
3.09M
    // In any case, the new upper bound is the top of the stack.
1397
3.09M
    unsigned long UpperBound = VersionStack.size() - 1;
1398
3.09M
1399
3.09M
    if (UpperBound - LocInfo.LowerBound > MaxCheckLimit) {
1400
57.6k
      LLVM_DEBUG(dbgs() << "MemorySSA skipping optimization of " << *MU << " ("
1401
57.6k
                        << *(MU->getMemoryInst()) << ")"
1402
57.6k
                        << " because there are "
1403
57.6k
                        << UpperBound - LocInfo.LowerBound
1404
57.6k
                        << " stores to disambiguate\n");
1405
57.6k
      // Because we did not walk, LastKill is no longer valid, as this may
1406
57.6k
      // have been a kill.
1407
57.6k
      LocInfo.LastKillValid = false;
1408
57.6k
      continue;
1409
57.6k
    }
1410
3.03M
    bool FoundClobberResult = false;
1411
3.03M
    unsigned UpwardWalkLimit = MaxCheckLimit;
1412
4.27M
    while (UpperBound > LocInfo.LowerBound) {
1413
3.42M
      if (isa<MemoryPhi>(VersionStack[UpperBound])) {
1414
1.11M
        // For phis, use the walker, see where we ended up, go there
1415
1.11M
        MemoryAccess *Result =
1416
1.11M
            Walker->getClobberingMemoryAccess(MU, UpwardWalkLimit);
1417
1.11M
        // We are guaranteed to find it or something is wrong
1418
1.71M
        while (VersionStack[UpperBound] != Result) {
1419
603k
          assert(UpperBound != 0);
1420
603k
          --UpperBound;
1421
603k
        }
1422
1.11M
        FoundClobberResult = true;
1423
1.11M
        break;
1424
1.11M
      }
1425
2.31M
1426
2.31M
      MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]);
1427
2.31M
      // If the lifetime of the pointer ends at this instruction, it's live on
1428
2.31M
      // entry.
1429
2.31M
      if (!UseMLOC.IsCall && 
lifetimeEndsAt(MD, UseMLOC.getLoc(), *AA)2.28M
) {
1430
3
        // Reset UpperBound to liveOnEntryDef's place in the stack
1431
3
        UpperBound = 0;
1432
3
        FoundClobberResult = true;
1433
3
        LocInfo.AR = MustAlias;
1434
3
        break;
1435
3
      }
1436
2.31M
      ClobberAlias CA = instructionClobbersQuery(MD, MU, UseMLOC, *AA);
1437
2.31M
      if (CA.IsClobber) {
1438
1.07M
        FoundClobberResult = true;
1439
1.07M
        LocInfo.AR = CA.AR;
1440
1.07M
        break;
1441
1.07M
      }
1442
1.23M
      --UpperBound;
1443
1.23M
    }
1444
3.03M
1445
3.03M
    // Note: Phis always have AliasResult AR set to MayAlias ATM.
1446
3.03M
1447
3.03M
    // At the end of this loop, UpperBound is either a clobber, or lower bound
1448
3.03M
    // PHI walking may cause it to be < LowerBound, and in fact, < LastKill.
1449
3.03M
    if (FoundClobberResult || 
UpperBound < LocInfo.LastKill848k
) {
1450
2.24M
      // We were last killed now by where we got to
1451
2.24M
      if (MSSA->isLiveOnEntryDef(VersionStack[UpperBound]))
1452
110k
        LocInfo.AR = None;
1453
2.24M
      MU->setDefiningAccess(VersionStack[UpperBound], true, LocInfo.AR);
1454
2.24M
      LocInfo.LastKill = UpperBound;
1455
2.24M
    } else {
1456
792k
      // Otherwise, we checked all the new ones, and now we know we can get to
1457
792k
      // LastKill.
1458
792k
      MU->setDefiningAccess(VersionStack[LocInfo.LastKill], true, LocInfo.AR);
1459
792k
    }
1460
3.03M
    LocInfo.LowerBound = VersionStack.size() - 1;
1461
3.03M
    LocInfo.LowerBoundBlock = BB;
1462
3.03M
  }
1463
3.69M
}
1464
1465
/// Optimize uses to point to their actual clobbering definitions.
1466
724k
void MemorySSA::OptimizeUses::optimizeUses() {
1467
724k
  SmallVector<MemoryAccess *, 16> VersionStack;
1468
724k
  DenseMap<MemoryLocOrCall, MemlocStackInfo> LocStackInfo;
1469
724k
  VersionStack.push_back(MSSA->getLiveOnEntryDef());
1470
724k
1471
724k
  unsigned long StackEpoch = 1;
1472
724k
  unsigned long PopEpoch = 1;
1473
724k
  // We perform a non-recursive top-down dominator tree walk.
1474
724k
  for (const auto *DomNode : depth_first(DT->getRootNode()))
1475
4.89M
    optimizeUsesInBlock(DomNode->getBlock(), StackEpoch, PopEpoch, VersionStack,
1476
4.89M
                        LocStackInfo);
1477
724k
}
1478
1479
void MemorySSA::placePHINodes(
1480
724k
    const SmallPtrSetImpl<BasicBlock *> &DefiningBlocks) {
1481
724k
  // Determine where our MemoryPhi's should go
1482
724k
  ForwardIDFCalculator IDFs(*DT);
1483
724k
  IDFs.setDefiningBlocks(DefiningBlocks);
1484
724k
  SmallVector<BasicBlock *, 32> IDFBlocks;
1485
724k
  IDFs.calculate(IDFBlocks);
1486
724k
1487
724k
  // Now place MemoryPhi nodes.
1488
724k
  for (auto &BB : IDFBlocks)
1489
1.22M
    createMemoryPhi(BB);
1490
724k
}
1491
1492
724k
void MemorySSA::buildMemorySSA(BatchAAResults &BAA) {
1493
724k
  // We create an access to represent "live on entry", for things like
1494
724k
  // arguments or users of globals, where the memory they use is defined before
1495
724k
  // the beginning of the function. We do not actually insert it into the IR.
1496
724k
  // We do not define a live on exit for the immediate uses, and thus our
1497
724k
  // semantics do *not* imply that something with no immediate uses can simply
1498
724k
  // be removed.
1499
724k
  BasicBlock &StartingPoint = F.getEntryBlock();
1500
724k
  LiveOnEntryDef.reset(new MemoryDef(F.getContext(), nullptr, nullptr,
1501
724k
                                     &StartingPoint, NextID++));
1502
724k
1503
724k
  // We maintain lists of memory accesses per-block, trading memory for time. We
1504
724k
  // could just look up the memory access for every possible instruction in the
1505
724k
  // stream.
1506
724k
  SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
1507
724k
  // Go through each block, figure out where defs occur, and chain together all
1508
724k
  // the accesses.
1509
4.90M
  for (BasicBlock &B : F) {
1510
4.90M
    bool InsertIntoDef = false;
1511
4.90M
    AccessList *Accesses = nullptr;
1512
4.90M
    DefsList *Defs = nullptr;
1513
26.6M
    for (Instruction &I : B) {
1514
26.6M
      MemoryUseOrDef *MUD = createNewAccess(&I, &BAA);
1515
26.6M
      if (!MUD)
1516
18.0M
        continue;
1517
8.56M
1518
8.56M
      if (!Accesses)
1519
3.26M
        Accesses = getOrCreateAccessList(&B);
1520
8.56M
      Accesses->push_back(MUD);
1521
8.56M
      if (isa<MemoryDef>(MUD)) {
1522
5.45M
        InsertIntoDef = true;
1523
5.45M
        if (!Defs)
1524
2.42M
          Defs = getOrCreateDefsList(&B);
1525
5.45M
        Defs->push_back(*MUD);
1526
5.45M
      }
1527
8.56M
    }
1528
4.90M
    if (InsertIntoDef)
1529
2.42M
      DefiningBlocks.insert(&B);
1530
4.90M
  }
1531
724k
  placePHINodes(DefiningBlocks);
1532
724k
1533
724k
  // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
1534
724k
  // filled in with all blocks.
1535
724k
  SmallPtrSet<BasicBlock *, 16> Visited;
1536
724k
  renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1537
724k
1538
724k
  ClobberWalkerBase<BatchAAResults> WalkerBase(this, &BAA, DT);
1539
724k
  CachingWalker<BatchAAResults> WalkerLocal(this, &WalkerBase);
1540
724k
  OptimizeUses(this, &WalkerLocal, &BAA, DT).optimizeUses();
1541
724k
1542
724k
  // Mark the uses in unreachable blocks as live on entry, so that they go
1543
724k
  // somewhere.
1544
724k
  for (auto &BB : F)
1545
4.90M
    if (!Visited.count(&BB))
1546
9.26k
      markUnreachableAsLiveOnEntry(&BB);
1547
724k
}
1548
1549
1.03M
MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
1550
1551
1.03M
MemorySSA::CachingWalker<AliasAnalysis> *MemorySSA::getWalkerImpl() {
1552
1.03M
  if (Walker)
1553
310k
    return Walker.get();
1554
724k
1555
724k
  if (!WalkerBase)
1556
724k
    WalkerBase =
1557
724k
        llvm::make_unique<ClobberWalkerBase<AliasAnalysis>>(this, AA, DT);
1558
724k
1559
724k
  Walker =
1560
724k
      llvm::make_unique<CachingWalker<AliasAnalysis>>(this, WalkerBase.get());
1561
724k
  return Walker.get();
1562
724k
}
1563
1564
128
MemorySSAWalker *MemorySSA::getSkipSelfWalker() {
1565
128
  if (SkipWalker)
1566
49
    return SkipWalker.get();
1567
79
1568
79
  if (!WalkerBase)
1569
0
    WalkerBase =
1570
0
        llvm::make_unique<ClobberWalkerBase<AliasAnalysis>>(this, AA, DT);
1571
79
1572
79
  SkipWalker =
1573
79
      llvm::make_unique<SkipSelfWalker<AliasAnalysis>>(this, WalkerBase.get());
1574
79
  return SkipWalker.get();
1575
79
 }
1576
1577
1578
// This is a helper function used by the creation routines. It places NewAccess
1579
// into the access and defs lists for a given basic block, at the given
1580
// insertion point.
1581
void MemorySSA::insertIntoListsForBlock(MemoryAccess *NewAccess,
1582
                                        const BasicBlock *BB,
1583
1.22M
                                        InsertionPlace Point) {
1584
1.22M
  auto *Accesses = getOrCreateAccessList(BB);
1585
1.22M
  if (Point == Beginning) {
1586
1.22M
    // If it's a phi node, it goes first, otherwise, it goes after any phi
1587
1.22M
    // nodes.
1588
1.22M
    if (isa<MemoryPhi>(NewAccess)) {
1589
1.22M
      Accesses->push_front(NewAccess);
1590
1.22M
      auto *Defs = getOrCreateDefsList(BB);
1591
1.22M
      Defs->push_front(*NewAccess);
1592
1.22M
    } else {
1593
27
      auto AI = find_if_not(
1594
27
          *Accesses, [](const MemoryAccess &MA) 
{ return isa<MemoryPhi>(MA); }5
);
1595
27
      Accesses->insert(AI, NewAccess);
1596
27
      if (!isa<MemoryUse>(NewAccess)) {
1597
15
        auto *Defs = getOrCreateDefsList(BB);
1598
15
        auto DI = find_if_not(
1599
15
            *Defs, [](const MemoryAccess &MA) 
{ return isa<MemoryPhi>(MA); }0
);
1600
15
        Defs->insert(DI, *NewAccess);
1601
15
      }
1602
27
    }
1603
1.22M
  } else {
1604
402
    Accesses->push_back(NewAccess);
1605
402
    if (!isa<MemoryUse>(NewAccess)) {
1606
210
      auto *Defs = getOrCreateDefsList(BB);
1607
210
      Defs->push_back(*NewAccess);
1608
210
    }
1609
402
  }
1610
1.22M
  BlockNumberingValid.erase(BB);
1611
1.22M
}
1612
1613
void MemorySSA::insertIntoListsBefore(MemoryAccess *What, const BasicBlock *BB,
1614
16
                                      AccessList::iterator InsertPt) {
1615
16
  auto *Accesses = getWritableBlockAccesses(BB);
1616
16
  bool WasEnd = InsertPt == Accesses->end();
1617
16
  Accesses->insert(AccessList::iterator(InsertPt), What);
1618
16
  if (!isa<MemoryUse>(What)) {
1619
6
    auto *Defs = getOrCreateDefsList(BB);
1620
6
    // If we got asked to insert at the end, we have an easy job, just shove it
1621
6
    // at the end. If we got asked to insert before an existing def, we also get
1622
6
    // an iterator. If we got asked to insert before a use, we have to hunt for
1623
6
    // the next def.
1624
6
    if (WasEnd) {
1625
3
      Defs->push_back(*What);
1626
3
    } else if (isa<MemoryDef>(InsertPt)) {
1627
2
      Defs->insert(InsertPt->getDefsIterator(), *What);
1628
2
    } else {
1629
2
      while (InsertPt != Accesses->end() && 
!isa<MemoryDef>(InsertPt)1
)
1630
1
        ++InsertPt;
1631
1
      // Either we found a def, or we are inserting at the end
1632
1
      if (InsertPt == Accesses->end())
1633
1
        Defs->push_back(*What);
1634
0
      else
1635
0
        Defs->insert(InsertPt->getDefsIterator(), *What);
1636
1
    }
1637
6
  }
1638
16
  BlockNumberingValid.erase(BB);
1639
16
}
1640
1641
172
void MemorySSA::prepareForMoveTo(MemoryAccess *What, BasicBlock *BB) {
1642
172
  // Keep it in the lookup tables, remove from the lists
1643
172
  removeFromLists(What, false);
1644
172
1645
172
  // Note that moving should implicitly invalidate the optimized state of a
1646
172
  // MemoryUse (and Phis can't be optimized). However, it doesn't do so for a
1647
172
  // MemoryDef.
1648
172
  if (auto *MD = dyn_cast<MemoryDef>(What))
1649
74
    MD->resetOptimized();
1650
172
  What->setBlock(BB);
1651
172
}
1652
1653
// Move What before Where in the IR.  The end result is that What will belong to
1654
// the right lists and have the right Block set, but will not otherwise be
1655
// correct. It will not have the right defining access, and if it is a def,
1656
// things below it will not properly be updated.
1657
void MemorySSA::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
1658
4
                       AccessList::iterator Where) {
1659
4
  prepareForMoveTo(What, BB);
1660
4
  insertIntoListsBefore(What, BB, Where);
1661
4
}
1662
1663
void MemorySSA::moveTo(MemoryAccess *What, BasicBlock *BB,
1664
168
                       InsertionPlace Point) {
1665
168
  if (isa<MemoryPhi>(What)) {
1666
2
    assert(Point == Beginning &&
1667
2
           "Can only move a Phi at the beginning of the block");
1668
2
    // Update lookup table entry
1669
2
    ValueToMemoryAccess.erase(What->getBlock());
1670
2
    bool Inserted = ValueToMemoryAccess.insert({BB, What}).second;
1671
2
    (void)Inserted;
1672
2
    assert(Inserted && "Cannot move a Phi to a block that already has one");
1673
2
  }
1674
168
1675
168
  prepareForMoveTo(What, BB);
1676
168
  insertIntoListsForBlock(What, BB, Point);
1677
168
}
1678
1679
1.22M
MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
1680
1.22M
  assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
1681
1.22M
  MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
1682
1.22M
  // Phi's always are placed at the front of the block.
1683
1.22M
  insertIntoListsForBlock(Phi, BB, Beginning);
1684
1.22M
  ValueToMemoryAccess[BB] = Phi;
1685
1.22M
  return Phi;
1686
1.22M
}
1687
1688
MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
1689
                                               MemoryAccess *Definition,
1690
275
                                               const MemoryUseOrDef *Template) {
1691
275
  assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
1692
275
  MemoryUseOrDef *NewAccess = createNewAccess(I, AA, Template);
1693
275
  assert(
1694
275
      NewAccess != nullptr &&
1695
275
      "Tried to create a memory access for a non-memory touching instruction");
1696
275
  NewAccess->setDefiningAccess(Definition);
1697
275
  return NewAccess;
1698
275
}
1699
1700
// Return true if the instruction has ordering constraints.
1701
// Note specifically that this only considers stores and loads
1702
// because others are still considered ModRef by getModRefInfo.
1703
21.1M
static inline bool isOrdered(const Instruction *I) {
1704
21.1M
  if (auto *SI = dyn_cast<StoreInst>(I)) {
1705
0
    if (!SI->isUnordered())
1706
0
      return true;
1707
21.1M
  } else if (auto *LI = dyn_cast<LoadInst>(I)) {
1708
3.06M
    if (!LI->isUnordered())
1709
24.4k
      return true;
1710
21.1M
  }
1711
21.1M
  return false;
1712
21.1M
}
1713
1714
/// Helper function to create new memory accesses
1715
template <typename AliasAnalysisType>
1716
MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I,
1717
                                           AliasAnalysisType *AAP,
1718
26.6M
                                           const MemoryUseOrDef *Template) {
1719
26.6M
  // The assume intrinsic has a control dependency which we model by claiming
1720
26.6M
  // that it writes arbitrarily. Ignore that fake memory dependency here.
1721
26.6M
  // FIXME: Replace this special casing with a more accurate modelling of
1722
26.6M
  // assume's control dependency.
1723
26.6M
  if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1724
511k
    if (II->getIntrinsicID() == Intrinsic::assume)
1725
81
      return nullptr;
1726
26.6M
1727
26.6M
  bool Def, Use;
1728
26.6M
  if (Template) {
1729
216
    Def = dyn_cast_or_null<MemoryDef>(Template) != nullptr;
1730
216
    Use = dyn_cast_or_null<MemoryUse>(Template) != nullptr;
1731
#if !defined(NDEBUG)
1732
    ModRefInfo ModRef = AAP->getModRefInfo(I, None);
1733
    bool DefCheck, UseCheck;
1734
    DefCheck = isModSet(ModRef) || isOrdered(I);
1735
    UseCheck = isRefSet(ModRef);
1736
    assert(Def == DefCheck && (Def || Use == UseCheck) && "Invalid template");
1737
#endif
1738
26.6M
  } else {
1739
26.6M
    // Find out what affect this instruction has on memory.
1740
26.6M
    ModRefInfo ModRef = AAP->getModRefInfo(I, None);
1741
26.6M
    // The isOrdered check is used to ensure that volatiles end up as defs
1742
26.6M
    // (atomics end up as ModRef right now anyway).  Until we separate the
1743
26.6M
    // ordering chain from the memory chain, this enables people to see at least
1744
26.6M
    // some relative ordering to volatiles.  Note that getClobberingMemoryAccess
1745
26.6M
    // will still give an answer that bypasses other volatile loads.  TODO:
1746
26.6M
    // Separate memory aliasing and ordering into two different chains so that
1747
26.6M
    // we can precisely represent both "what memory will this read/write/is
1748
26.6M
    // clobbered by" and "what instructions can I move this past".
1749
26.6M
    Def = isModSet(ModRef) || 
isOrdered(I)21.1M
;
1750
26.6M
    Use = isRefSet(ModRef);
1751
26.6M
  }
1752
26.6M
1753
26.6M
  // It's possible for an instruction to not modify memory at all. During
1754
26.6M
  // construction, we ignore them.
1755
26.6M
  if (!Def && 
!Use21.1M
)
1756
18.0M
    return nullptr;
1757
8.56M
1758
8.56M
  MemoryUseOrDef *MUD;
1759
8.56M
  if (Def)
1760
5.45M
    MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
1761
3.11M
  else
1762
3.11M
    MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
1763
8.56M
  ValueToMemoryAccess[I] = MUD;
1764
8.56M
  return MUD;
1765
8.56M
}
llvm::MemoryUseOrDef* llvm::MemorySSA::createNewAccess<llvm::BatchAAResults>(llvm::Instruction*, llvm::BatchAAResults*, llvm::MemoryUseOrDef const*)
Line
Count
Source
1718
26.6M
                                           const MemoryUseOrDef *Template) {
1719
26.6M
  // The assume intrinsic has a control dependency which we model by claiming
1720
26.6M
  // that it writes arbitrarily. Ignore that fake memory dependency here.
1721
26.6M
  // FIXME: Replace this special casing with a more accurate modelling of
1722
26.6M
  // assume's control dependency.
1723
26.6M
  if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1724
511k
    if (II->getIntrinsicID() == Intrinsic::assume)
1725
81
      return nullptr;
1726
26.6M
1727
26.6M
  bool Def, Use;
1728
26.6M
  if (Template) {
1729
0
    Def = dyn_cast_or_null<MemoryDef>(Template) != nullptr;
1730
0
    Use = dyn_cast_or_null<MemoryUse>(Template) != nullptr;
1731
#if !defined(NDEBUG)
1732
    ModRefInfo ModRef = AAP->getModRefInfo(I, None);
1733
    bool DefCheck, UseCheck;
1734
    DefCheck = isModSet(ModRef) || isOrdered(I);
1735
    UseCheck = isRefSet(ModRef);
1736
    assert(Def == DefCheck && (Def || Use == UseCheck) && "Invalid template");
1737
#endif
1738
26.6M
  } else {
1739
26.6M
    // Find out what affect this instruction has on memory.
1740
26.6M
    ModRefInfo ModRef = AAP->getModRefInfo(I, None);
1741
26.6M
    // The isOrdered check is used to ensure that volatiles end up as defs
1742
26.6M
    // (atomics end up as ModRef right now anyway).  Until we separate the
1743
26.6M
    // ordering chain from the memory chain, this enables people to see at least
1744
26.6M
    // some relative ordering to volatiles.  Note that getClobberingMemoryAccess
1745
26.6M
    // will still give an answer that bypasses other volatile loads.  TODO:
1746
26.6M
    // Separate memory aliasing and ordering into two different chains so that
1747
26.6M
    // we can precisely represent both "what memory will this read/write/is
1748
26.6M
    // clobbered by" and "what instructions can I move this past".
1749
26.6M
    Def = isModSet(ModRef) || 
isOrdered(I)21.1M
;
1750
26.6M
    Use = isRefSet(ModRef);
1751
26.6M
  }
1752
26.6M
1753
26.6M
  // It's possible for an instruction to not modify memory at all. During
1754
26.6M
  // construction, we ignore them.
1755
26.6M
  if (!Def && 
!Use21.1M
)
1756
18.0M
    return nullptr;
1757
8.56M
1758
8.56M
  MemoryUseOrDef *MUD;
1759
8.56M
  if (Def)
1760
5.45M
    MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
1761
3.11M
  else
1762
3.11M
    MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
1763
8.56M
  ValueToMemoryAccess[I] = MUD;
1764
8.56M
  return MUD;
1765
8.56M
}
llvm::MemoryUseOrDef* llvm::MemorySSA::createNewAccess<llvm::AAResults>(llvm::Instruction*, llvm::AAResults*, llvm::MemoryUseOrDef const*)
Line
Count
Source
1718
275
                                           const MemoryUseOrDef *Template) {
1719
275
  // The assume intrinsic has a control dependency which we model by claiming
1720
275
  // that it writes arbitrarily. Ignore that fake memory dependency here.
1721
275
  // FIXME: Replace this special casing with a more accurate modelling of
1722
275
  // assume's control dependency.
1723
275
  if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1724
9
    if (II->getIntrinsicID() == Intrinsic::assume)
1725
0
      return nullptr;
1726
275
1727
275
  bool Def, Use;
1728
275
  if (Template) {
1729
216
    Def = dyn_cast_or_null<MemoryDef>(Template) != nullptr;
1730
216
    Use = dyn_cast_or_null<MemoryUse>(Template) != nullptr;
1731
#if !defined(NDEBUG)
1732
    ModRefInfo ModRef = AAP->getModRefInfo(I, None);
1733
    bool DefCheck, UseCheck;
1734
    DefCheck = isModSet(ModRef) || isOrdered(I);
1735
    UseCheck = isRefSet(ModRef);
1736
    assert(Def == DefCheck && (Def || Use == UseCheck) && "Invalid template");
1737
#endif
1738
59
  } else {
1739
59
    // Find out what affect this instruction has on memory.
1740
59
    ModRefInfo ModRef = AAP->getModRefInfo(I, None);
1741
59
    // The isOrdered check is used to ensure that volatiles end up as defs
1742
59
    // (atomics end up as ModRef right now anyway).  Until we separate the
1743
59
    // ordering chain from the memory chain, this enables people to see at least
1744
59
    // some relative ordering to volatiles.  Note that getClobberingMemoryAccess
1745
59
    // will still give an answer that bypasses other volatile loads.  TODO:
1746
59
    // Separate memory aliasing and ordering into two different chains so that
1747
59
    // we can precisely represent both "what memory will this read/write/is
1748
59
    // clobbered by" and "what instructions can I move this past".
1749
59
    Def = isModSet(ModRef) || 
isOrdered(I)38
;
1750
59
    Use = isRefSet(ModRef);
1751
59
  }
1752
275
1753
275
  // It's possible for an instruction to not modify memory at all. During
1754
275
  // construction, we ignore them.
1755
275
  if (!Def && 
!Use118
)
1756
0
    return nullptr;
1757
275
1758
275
  MemoryUseOrDef *MUD;
1759
275
  if (Def)
1760
157
    MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
1761
118
  else
1762
118
    MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
1763
275
  ValueToMemoryAccess[I] = MUD;
1764
275
  return MUD;
1765
275
}
1766
1767
/// Returns true if \p Replacer dominates \p Replacee .
1768
bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
1769
0
                             const MemoryAccess *Replacee) const {
1770
0
  if (isa<MemoryUseOrDef>(Replacee))
1771
0
    return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
1772
0
  const auto *MP = cast<MemoryPhi>(Replacee);
1773
0
  // For a phi node, the use occurs in the predecessor block of the phi node.
1774
0
  // Since we may occur multiple times in the phi node, we have to check each
1775
0
  // operand to ensure Replacer dominates each operand where Replacee occurs.
1776
0
  for (const Use &Arg : MP->operands()) {
1777
0
    if (Arg.get() != Replacee &&
1778
0
        !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
1779
0
      return false;
1780
0
  }
1781
0
  return true;
1782
0
}
1783
1784
/// Properly remove \p MA from all of MemorySSA's lookup tables.
1785
111k
void MemorySSA::removeFromLookups(MemoryAccess *MA) {
1786
111k
  assert(MA->use_empty() &&
1787
111k
         "Trying to remove memory access that still has uses");
1788
111k
  BlockNumbering.erase(MA);
1789
111k
  if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1790
110k
    MUD->setDefiningAccess(nullptr);
1791
111k
  // Invalidate our walker's cache if necessary
1792
111k
  if (!isa<MemoryUse>(MA))
1793
8.39k
    getWalker()->invalidateInfo(MA);
1794
111k
1795
111k
  Value *MemoryInst;
1796
111k
  if (const auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1797
110k
    MemoryInst = MUD->getMemoryInst();
1798
691
  else
1799
691
    MemoryInst = MA->getBlock();
1800
111k
1801
111k
  auto VMA = ValueToMemoryAccess.find(MemoryInst);
1802
111k
  if (VMA->second == MA)
1803
111k
    ValueToMemoryAccess.erase(VMA);
1804
111k
}
1805
1806
/// Properly remove \p MA from all of MemorySSA's lists.
1807
///
1808
/// Because of the way the intrusive list and use lists work, it is important to
1809
/// do removal in the right order.
1810
/// ShouldDelete defaults to true, and will cause the memory access to also be
1811
/// deleted, not just removed.
1812
111k
void MemorySSA::removeFromLists(MemoryAccess *MA, bool ShouldDelete) {
1813
111k
  BasicBlock *BB = MA->getBlock();
1814
111k
  // The access list owns the reference, so we erase it from the non-owning list
1815
111k
  // first.
1816
111k
  if (!isa<MemoryUse>(MA)) {
1817
8.46k
    auto DefsIt = PerBlockDefs.find(BB);
1818
8.46k
    std::unique_ptr<DefsList> &Defs = DefsIt->second;
1819
8.46k
    Defs->remove(*MA);
1820
8.46k
    if (Defs->empty())
1821
977
      PerBlockDefs.erase(DefsIt);
1822
8.46k
  }
1823
111k
1824
111k
  // The erase call here will delete it. If we don't want it deleted, we call
1825
111k
  // remove instead.
1826
111k
  auto AccessIt = PerBlockAccesses.find(BB);
1827
111k
  std::unique_ptr<AccessList> &Accesses = AccessIt->second;
1828
111k
  if (ShouldDelete)
1829
111k
    Accesses->erase(MA);
1830
172
  else
1831
172
    Accesses->remove(MA);
1832
111k
1833
111k
  if (Accesses->empty()) {
1834
13.9k
    PerBlockAccesses.erase(AccessIt);
1835
13.9k
    BlockNumberingValid.erase(BB);
1836
13.9k
  }
1837
111k
}
1838
1839
100
void MemorySSA::print(raw_ostream &OS) const {
1840
100
  MemorySSAAnnotatedWriter Writer(this);
1841
100
  F.print(OS, &Writer);
1842
100
}
1843
1844
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1845
LLVM_DUMP_METHOD void MemorySSA::dump() const { print(dbgs()); }
1846
#endif
1847
1848
3.95k
void MemorySSA::verifyMemorySSA() const {
1849
3.95k
  verifyDefUses(F);
1850
3.95k
  verifyDomination(F);
1851
3.95k
  verifyOrdering(F);
1852
3.95k
  verifyDominationNumbers(F);
1853
3.95k
  // Previously, the verification used to also verify that the clobberingAccess
1854
3.95k
  // cached by MemorySSA is the same as the clobberingAccess found at a later
1855
3.95k
  // query to AA. This does not hold true in general due to the current fragility
1856
3.95k
  // of BasicAA which has arbitrary caps on the things it analyzes before giving
1857
3.95k
  // up. As a result, transformations that are correct, will lead to BasicAA
1858
3.95k
  // returning different Alias answers before and after that transformation.
1859
3.95k
  // Invalidating MemorySSA is not an option, as the results in BasicAA can be so
1860
3.95k
  // random, in the worst case we'd need to rebuild MemorySSA from scratch after
1861
3.95k
  // every transformation, which defeats the purpose of using it. For such an
1862
3.95k
  // example, see test4 added in D51960.
1863
3.95k
}
1864
1865
/// Verify that all of the blocks we believe to have valid domination numbers
1866
/// actually have valid domination numbers.
1867
3.95k
void MemorySSA::verifyDominationNumbers(const Function &F) const {
1868
#ifndef NDEBUG
1869
  if (BlockNumberingValid.empty())
1870
    return;
1871
1872
  SmallPtrSet<const BasicBlock *, 16> ValidBlocks = BlockNumberingValid;
1873
  for (const BasicBlock &BB : F) {
1874
    if (!ValidBlocks.count(&BB))
1875
      continue;
1876
1877
    ValidBlocks.erase(&BB);
1878
1879
    const AccessList *Accesses = getBlockAccesses(&BB);
1880
    // It's correct to say an empty block has valid numbering.
1881
    if (!Accesses)
1882
      continue;
1883
1884
    // Block numbering starts at 1.
1885
    unsigned long LastNumber = 0;
1886
    for (const MemoryAccess &MA : *Accesses) {
1887
      auto ThisNumberIter = BlockNumbering.find(&MA);
1888
      assert(ThisNumberIter != BlockNumbering.end() &&
1889
             "MemoryAccess has no domination number in a valid block!");
1890
1891
      unsigned long ThisNumber = ThisNumberIter->second;
1892
      assert(ThisNumber > LastNumber &&
1893
             "Domination numbers should be strictly increasing!");
1894
      LastNumber = ThisNumber;
1895
    }
1896
  }
1897
1898
  assert(ValidBlocks.empty() &&
1899
         "All valid BasicBlocks should exist in F -- dangling pointers?");
1900
#endif
1901
}
1902
1903
/// Verify that the order and existence of MemoryAccesses matches the
1904
/// order and existence of memory affecting instructions.
1905
3.95k
void MemorySSA::verifyOrdering(Function &F) const {
1906
#ifndef NDEBUG
1907
  // Walk all the blocks, comparing what the lookups think and what the access
1908
  // lists think, as well as the order in the blocks vs the order in the access
1909
  // lists.
1910
  SmallVector<MemoryAccess *, 32> ActualAccesses;
1911
  SmallVector<MemoryAccess *, 32> ActualDefs;
1912
  for (BasicBlock &B : F) {
1913
    const AccessList *AL = getBlockAccesses(&B);
1914
    const auto *DL = getBlockDefs(&B);
1915
    MemoryAccess *Phi = getMemoryAccess(&B);
1916
    if (Phi) {
1917
      ActualAccesses.push_back(Phi);
1918
      ActualDefs.push_back(Phi);
1919
    }
1920
1921
    for (Instruction &I : B) {
1922
      MemoryAccess *MA = getMemoryAccess(&I);
1923
      assert((!MA || (AL && (isa<MemoryUse>(MA) || DL))) &&
1924
             "We have memory affecting instructions "
1925
             "in this block but they are not in the "
1926
             "access list or defs list");
1927
      if (MA) {
1928
        ActualAccesses.push_back(MA);
1929
        if (isa<MemoryDef>(MA))
1930
          ActualDefs.push_back(MA);
1931
      }
1932
    }
1933
    // Either we hit the assert, really have no accesses, or we have both
1934
    // accesses and an access list.
1935
    // Same with defs.
1936
    if (!AL && !DL)
1937
      continue;
1938
    assert(AL->size() == ActualAccesses.size() &&
1939
           "We don't have the same number of accesses in the block as on the "
1940
           "access list");
1941
    assert((DL || ActualDefs.size() == 0) &&
1942
           "Either we should have a defs list, or we should have no defs");
1943
    assert((!DL || DL->size() == ActualDefs.size()) &&
1944
           "We don't have the same number of defs in the block as on the "
1945
           "def list");
1946
    auto ALI = AL->begin();
1947
    auto AAI = ActualAccesses.begin();
1948
    while (ALI != AL->end() && AAI != ActualAccesses.end()) {
1949
      assert(&*ALI == *AAI && "Not the same accesses in the same order");
1950
      ++ALI;
1951
      ++AAI;
1952
    }
1953
    ActualAccesses.clear();
1954
    if (DL) {
1955
      auto DLI = DL->begin();
1956
      auto ADI = ActualDefs.begin();
1957
      while (DLI != DL->end() && ADI != ActualDefs.end()) {
1958
        assert(&*DLI == *ADI && "Not the same defs in the same order");
1959
        ++DLI;
1960
        ++ADI;
1961
      }
1962
    }
1963
    ActualDefs.clear();
1964
  }
1965
#endif
1966
}
1967
1968
/// Verify the domination properties of MemorySSA by checking that each
1969
/// definition dominates all of its uses.
1970
3.95k
void MemorySSA::verifyDomination(Function &F) const {
1971
#ifndef NDEBUG
1972
  for (BasicBlock &B : F) {
1973
    // Phi nodes are attached to basic blocks
1974
    if (MemoryPhi *MP = getMemoryAccess(&B))
1975
      for (const Use &U : MP->uses())
1976
        assert(dominates(MP, U) && "Memory PHI does not dominate it's uses");
1977
1978
    for (Instruction &I : B) {
1979
      MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
1980
      if (!MD)
1981
        continue;
1982
1983
      for (const Use &U : MD->uses())
1984
        assert(dominates(MD, U) && "Memory Def does not dominate it's uses");
1985
    }
1986
  }
1987
#endif
1988
}
1989
1990
/// Verify the def-use lists in MemorySSA, by verifying that \p Use
1991
/// appears in the use list of \p Def.
1992
0
void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
1993
#ifndef NDEBUG
1994
  // The live on entry use may cause us to get a NULL def here
1995
  if (!Def)
1996
    assert(isLiveOnEntryDef(Use) &&
1997
           "Null def but use not point to live on entry def");
1998
  else
1999
    assert(is_contained(Def->users(), Use) &&
2000
           "Did not find use in def's use list");
2001
#endif
2002
}
2003
2004
/// Verify the immediate use information, by walking all the memory
2005
/// accesses and verifying that, for each use, it appears in the
2006
/// appropriate def's use list
2007
3.95k
void MemorySSA::verifyDefUses(Function &F) const {
2008
#ifndef NDEBUG
2009
  for (BasicBlock &B : F) {
2010
    // Phi nodes are attached to basic blocks
2011
    if (MemoryPhi *Phi = getMemoryAccess(&B)) {
2012
      assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
2013
                                          pred_begin(&B), pred_end(&B))) &&
2014
             "Incomplete MemoryPhi Node");
2015
      for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
2016
        verifyUseInDefs(Phi->getIncomingValue(I), Phi);
2017
        assert(find(predecessors(&B), Phi->getIncomingBlock(I)) !=
2018
                   pred_end(&B) &&
2019
               "Incoming phi block not a block predecessor");
2020
      }
2021
    }
2022
2023
    for (Instruction &I : B) {
2024
      if (MemoryUseOrDef *MA = getMemoryAccess(&I)) {
2025
        verifyUseInDefs(MA->getDefiningAccess(), MA);
2026
      }
2027
    }
2028
  }
2029
#endif
2030
}
2031
2032
/// Perform a local numbering on blocks so that instruction ordering can be
2033
/// determined in constant time.
2034
/// TODO: We currently just number in order.  If we numbered by N, we could
2035
/// allow at least N-1 sequences of insertBefore or insertAfter (and at least
2036
/// log2(N) sequences of mixed before and after) without needing to invalidate
2037
/// the numbering.
2038
45.3k
void MemorySSA::renumberBlock(const BasicBlock *B) const {
2039
45.3k
  // The pre-increment ensures the numbers really start at 1.
2040
45.3k
  unsigned long CurrentNumber = 0;
2041
45.3k
  const AccessList *AL = getBlockAccesses(B);
2042
45.3k
  assert(AL != nullptr && "Asking to renumber an empty block");
2043
45.3k
  for (const auto &I : *AL)
2044
425k
    BlockNumbering[&I] = ++CurrentNumber;
2045
45.3k
  BlockNumberingValid.insert(B);
2046
45.3k
}
2047
2048
/// Determine, for two memory accesses in the same block,
2049
/// whether \p Dominator dominates \p Dominatee.
2050
/// \returns True if \p Dominator dominates \p Dominatee.
2051
bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
2052
81.6k
                                 const MemoryAccess *Dominatee) const {
2053
81.6k
  const BasicBlock *DominatorBlock = Dominator->getBlock();
2054
81.6k
2055
81.6k
  assert((DominatorBlock == Dominatee->getBlock()) &&
2056
81.6k
         "Asking for local domination when accesses are in different blocks!");
2057
81.6k
  // A node dominates itself.
2058
81.6k
  if (Dominatee == Dominator)
2059
0
    return true;
2060
81.6k
2061
81.6k
  // When Dominatee is defined on function entry, it is not dominated by another
2062
81.6k
  // memory access.
2063
81.6k
  if (isLiveOnEntryDef(Dominatee))
2064
0
    return false;
2065
81.6k
2066
81.6k
  // When Dominator is defined on function entry, it dominates the other memory
2067
81.6k
  // access.
2068
81.6k
  if (isLiveOnEntryDef(Dominator))
2069
10.2k
    return true;
2070
71.3k
2071
71.3k
  if (!BlockNumberingValid.count(DominatorBlock))
2072
45.3k
    renumberBlock(DominatorBlock);
2073
71.3k
2074
71.3k
  unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
2075
71.3k
  // All numbers start with 1
2076
71.3k
  assert(DominatorNum != 0 && "Block was not numbered properly");
2077
71.3k
  unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
2078
71.3k
  assert(DominateeNum != 0 && "Block was not numbered properly");
2079
71.3k
  return DominatorNum < DominateeNum;
2080
71.3k
}
2081
2082
bool MemorySSA::dominates(const MemoryAccess *Dominator,
2083
1.39M
                          const MemoryAccess *Dominatee) const {
2084
1.39M
  if (Dominator == Dominatee)
2085
106k
    return true;
2086
1.28M
2087
1.28M
  if (isLiveOnEntryDef(Dominatee))
2088
158k
    return false;
2089
1.12M
2090
1.12M
  if (Dominator->getBlock() != Dominatee->getBlock())
2091
1.04M
    return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
2092
81.6k
  return locallyDominates(Dominator, Dominatee);
2093
81.6k
}
2094
2095
bool MemorySSA::dominates(const MemoryAccess *Dominator,
2096
0
                          const Use &Dominatee) const {
2097
0
  if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Dominatee.getUser())) {
2098
0
    BasicBlock *UseBB = MP->getIncomingBlock(Dominatee);
2099
0
    // The def must dominate the incoming block of the phi.
2100
0
    if (UseBB != Dominator->getBlock())
2101
0
      return DT->dominates(Dominator->getBlock(), UseBB);
2102
0
    // If the UseBB and the DefBB are the same, compare locally.
2103
0
    return locallyDominates(Dominator, cast<MemoryAccess>(Dominatee));
2104
0
  }
2105
0
  // If it's not a PHI node use, the normal dominates can already handle it.
2106
0
  return dominates(Dominator, cast<MemoryAccess>(Dominatee.getUser()));
2107
0
}
2108
2109
const static char LiveOnEntryStr[] = "liveOnEntry";
2110
2111
562
void MemoryAccess::print(raw_ostream &OS) const {
2112
562
  switch (getValueID()) {
2113
562
  
case MemoryPhiVal: return static_cast<const MemoryPhi *>(this)->print(OS)97
;
2114
562
  
case MemoryDefVal: return static_cast<const MemoryDef *>(this)->print(OS)284
;
2115
562
  
case MemoryUseVal: return static_cast<const MemoryUse *>(this)->print(OS)181
;
2116
0
  }
2117
0
  llvm_unreachable("invalid value id");
2118
0
}
2119
2120
284
void MemoryDef::print(raw_ostream &OS) const {
2121
284
  MemoryAccess *UO = getDefiningAccess();
2122
284
2123
284
  auto printID = [&OS](MemoryAccess *A) {
2124
284
    if (A && A->getID())
2125
198
      OS << A->getID();
2126
86
    else
2127
86
      OS << LiveOnEntryStr;
2128
284
  };
2129
284
2130
284
  OS << getID() << " = MemoryDef(";
2131
284
  printID(UO);
2132
284
  OS << ")";
2133
284
2134
284
  if (isOptimized()) {
2135
0
    OS << "->";
2136
0
    printID(getOptimized());
2137
0
2138
0
    if (Optional<AliasResult> AR = getOptimizedAccessType())
2139
0
      OS << " " << *AR;
2140
0
  }
2141
284
}
2142
2143
97
void MemoryPhi::print(raw_ostream &OS) const {
2144
97
  bool First = true;
2145
97
  OS << getID() << " = MemoryPhi(";
2146
217
  for (const auto &Op : operands()) {
2147
217
    BasicBlock *BB = getIncomingBlock(Op);
2148
217
    MemoryAccess *MA = cast<MemoryAccess>(Op);
2149
217
    if (!First)
2150
120
      OS << ',';
2151
97
    else
2152
97
      First = false;
2153
217
2154
217
    OS << '{';
2155
217
    if (BB->hasName())
2156
197
      OS << BB->getName();
2157
20
    else
2158
20
      BB->printAsOperand(OS, false);
2159
217
    OS << ',';
2160
217
    if (unsigned ID = MA->getID())
2161
197
      OS << ID;
2162
20
    else
2163
20
      OS << LiveOnEntryStr;
2164
217
    OS << '}';
2165
217
  }
2166
97
  OS << ')';
2167
97
}
2168
2169
181
void MemoryUse::print(raw_ostream &OS) const {
2170
181
  MemoryAccess *UO = getDefiningAccess();
2171
181
  OS << "MemoryUse(";
2172
181
  if (UO && UO->getID())
2173
148
    OS << UO->getID();
2174
33
  else
2175
33
    OS << LiveOnEntryStr;
2176
181
  OS << ')';
2177
181
2178
181
  if (Optional<AliasResult> AR = getOptimizedAccessType())
2179
155
    OS << " " << *AR;
2180
181
}
2181
2182
0
void MemoryAccess::dump() const {
2183
0
// Cannot completely remove virtual function even in release mode.
2184
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2185
  print(dbgs());
2186
  dbgs() << "\n";
2187
#endif
2188
}
2189
2190
char MemorySSAPrinterLegacyPass::ID = 0;
2191
2192
22
MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) {
2193
22
  initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
2194
22
}
2195
2196
22
void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
2197
22
  AU.setPreservesAll();
2198
22
  AU.addRequired<MemorySSAWrapperPass>();
2199
22
}
2200
2201
54
bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) {
2202
54
  auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
2203
54
  MSSA.print(dbgs());
2204
54
  if (VerifyMemorySSA)
2205
53
    MSSA.verifyMemorySSA();
2206
54
  return false;
2207
54
}
2208
2209
AnalysisKey MemorySSAAnalysis::Key;
2210
2211
MemorySSAAnalysis::Result MemorySSAAnalysis::run(Function &F,
2212
1.32k
                                                 FunctionAnalysisManager &AM) {
2213
1.32k
  auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2214
1.32k
  auto &AA = AM.getResult<AAManager>(F);
2215
1.32k
  return MemorySSAAnalysis::Result(llvm::make_unique<MemorySSA>(F, &AA, &DT));
2216
1.32k
}
2217
2218
bool MemorySSAAnalysis::Result::invalidate(
2219
    Function &F, const PreservedAnalyses &PA,
2220
1.26k
    FunctionAnalysisManager::Invalidator &Inv) {
2221
1.26k
  auto PAC = PA.getChecker<MemorySSAAnalysis>();
2222
1.26k
  return !(PAC.preserved() || 
PAC.preservedSet<AllAnalysesOn<Function>>()1.11k
) ||
2223
1.26k
         
Inv.invalidate<AAManager>(F, PA)152
||
2224
1.26k
         
Inv.invalidate<DominatorTreeAnalysis>(F, PA)148
;
2225
1.26k
}
2226
2227
PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
2228
44
                                            FunctionAnalysisManager &AM) {
2229
44
  OS << "MemorySSA for function: " << F.getName() << "\n";
2230
44
  AM.getResult<MemorySSAAnalysis>(F).getMSSA().print(OS);
2231
44
2232
44
  return PreservedAnalyses::all();
2233
44
}
2234
2235
PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
2236
41
                                             FunctionAnalysisManager &AM) {
2237
41
  AM.getResult<MemorySSAAnalysis>(F).getMSSA().verifyMemorySSA();
2238
41
2239
41
  return PreservedAnalyses::all();
2240
41
}
2241
2242
char MemorySSAWrapperPass::ID = 0;
2243
2244
21.8k
MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
2245
21.8k
  initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
2246
21.8k
}
2247
2248
723k
void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
2249
2250
21.8k
void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
2251
21.8k
  AU.setPreservesAll();
2252
21.8k
  AU.addRequiredTransitive<DominatorTreeWrapperPass>();
2253
21.8k
  AU.addRequiredTransitive<AAResultsWrapperPass>();
2254
21.8k
}
2255
2256
723k
bool MemorySSAWrapperPass::runOnFunction(Function &F) {
2257
723k
  auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2258
723k
  auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2259
723k
  MSSA.reset(new MemorySSA(F, &AA, &DT));
2260
723k
  return false;
2261
723k
}
2262
2263
0
void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); }
2264
2265
2
void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
2266
2
  MSSA->print(OS);
2267
2
}
2268
2269
1.45M
MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
2270
2271
/// Walk the use-def chains starting at \p StartingAccess and find
2272
/// the MemoryAccess that actually clobbers Loc.
2273
///
2274
/// \returns our clobbering memory access
2275
template <typename AliasAnalysisType>
2276
MemoryAccess *
2277
MemorySSA::ClobberWalkerBase<AliasAnalysisType>::getClobberingMemoryAccessBase(
2278
    MemoryAccess *StartingAccess, const MemoryLocation &Loc,
2279
2
    unsigned &UpwardWalkLimit) {
2280
2
  if (isa<MemoryPhi>(StartingAccess))
2281
0
    return StartingAccess;
2282
2
2283
2
  auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
2284
2
  if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
2285
0
    return StartingUseOrDef;
2286
2
2287
2
  Instruction *I = StartingUseOrDef->getMemoryInst();
2288
2
2289
2
  // Conservatively, fences are always clobbers, so don't perform the walk if we
2290
2
  // hit a fence.
2291
2
  if (!isa<CallBase>(I) && I->isFenceLike())
2292
0
    return StartingUseOrDef;
2293
2
2294
2
  UpwardsMemoryQuery Q;
2295
2
  Q.OriginalAccess = StartingUseOrDef;
2296
2
  Q.StartingLoc = Loc;
2297
2
  Q.Inst = I;
2298
2
  Q.IsCall = false;
2299
2
2300
2
  // Unlike the other function, do not walk to the def of a def, because we are
2301
2
  // handed something we already believe is the clobbering access.
2302
2
  // We never set SkipSelf to true in Q in this method.
2303
2
  MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
2304
2
                                     ? 
StartingUseOrDef->getDefiningAccess()0
2305
2
                                     : StartingUseOrDef;
2306
2
2307
2
  MemoryAccess *Clobber =
2308
2
      Walker.findClobber(DefiningAccess, Q, UpwardWalkLimit);
2309
2
  LLVM_DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2310
2
  LLVM_DEBUG(dbgs() << *StartingUseOrDef << "\n");
2311
2
  LLVM_DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2312
2
  LLVM_DEBUG(dbgs() << *Clobber << "\n");
2313
2
  return Clobber;
2314
2
}
Unexecuted instantiation: llvm::MemorySSA::ClobberWalkerBase<llvm::BatchAAResults>::getClobberingMemoryAccessBase(llvm::MemoryAccess*, llvm::MemoryLocation const&, unsigned int&)
llvm::MemorySSA::ClobberWalkerBase<llvm::AAResults>::getClobberingMemoryAccessBase(llvm::MemoryAccess*, llvm::MemoryLocation const&, unsigned int&)
Line
Count
Source
2279
2
    unsigned &UpwardWalkLimit) {
2280
2
  if (isa<MemoryPhi>(StartingAccess))
2281
0
    return StartingAccess;
2282
2
2283
2
  auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
2284
2
  if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
2285
0
    return StartingUseOrDef;
2286
2
2287
2
  Instruction *I = StartingUseOrDef->getMemoryInst();
2288
2
2289
2
  // Conservatively, fences are always clobbers, so don't perform the walk if we
2290
2
  // hit a fence.
2291
2
  if (!isa<CallBase>(I) && I->isFenceLike())
2292
0
    return StartingUseOrDef;
2293
2
2294
2
  UpwardsMemoryQuery Q;
2295
2
  Q.OriginalAccess = StartingUseOrDef;
2296
2
  Q.StartingLoc = Loc;
2297
2
  Q.Inst = I;
2298
2
  Q.IsCall = false;
2299
2
2300
2
  // Unlike the other function, do not walk to the def of a def, because we are
2301
2
  // handed something we already believe is the clobbering access.
2302
2
  // We never set SkipSelf to true in Q in this method.
2303
2
  MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
2304
2
                                     ? 
StartingUseOrDef->getDefiningAccess()0
2305
2
                                     : StartingUseOrDef;
2306
2
2307
2
  MemoryAccess *Clobber =
2308
2
      Walker.findClobber(DefiningAccess, Q, UpwardWalkLimit);
2309
2
  LLVM_DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2310
2
  LLVM_DEBUG(dbgs() << *StartingUseOrDef << "\n");
2311
2
  LLVM_DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2312
2
  LLVM_DEBUG(dbgs() << *Clobber << "\n");
2313
2
  return Clobber;
2314
2
}
2315
2316
template <typename AliasAnalysisType>
2317
MemoryAccess *
2318
MemorySSA::ClobberWalkerBase<AliasAnalysisType>::getClobberingMemoryAccessBase(
2319
1.41M
    MemoryAccess *MA, unsigned &UpwardWalkLimit, bool SkipSelf) {
2320
1.41M
  auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
2321
1.41M
  // If this is a MemoryPhi, we can't do anything.
2322
1.41M
  if (!StartingAccess)
2323
0
    return MA;
2324
1.41M
2325
1.41M
  bool IsOptimized = false;
2326
1.41M
2327
1.41M
  // If this is an already optimized use or def, return the optimized result.
2328
1.41M
  // Note: Currently, we store the optimized def result in a separate field,
2329
1.41M
  // since we can't use the defining access.
2330
1.41M
  if (StartingAccess->isOptimized()) {
2331
287k
    if (!SkipSelf || 
!isa<MemoryDef>(StartingAccess)102
)
2332
287k
      return StartingAccess->getOptimized();
2333
21
    IsOptimized = true;
2334
21
  }
2335
1.41M
2336
1.41M
  const Instruction *I = StartingAccess->getMemoryInst();
2337
1.12M
  // We can't sanely do anything with a fence, since they conservatively clobber
2338
1.12M
  // all memory, and have no locations to get pointers from to try to
2339
1.12M
  // disambiguate.
2340
1.12M
  if (!isa<CallBase>(I) && 
I->isFenceLike()1.12M
)
2341
0
    return StartingAccess;
2342
1.12M
2343
1.12M
  UpwardsMemoryQuery Q(I, StartingAccess);
2344
1.12M
2345
1.12M
  if (isUseTriviallyOptimizableToLiveOnEntry(*Walker.getAA(), I)) {
2346
1
    MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef();
2347
1
    StartingAccess->setOptimized(LiveOnEntry);
2348
1
    StartingAccess->setOptimizedAccessType(None);
2349
1
    return LiveOnEntry;
2350
1
  }
2351
1.12M
2352
1.12M
  MemoryAccess *OptimizedAccess;
2353
1.12M
  if (!IsOptimized) {
2354
1.12M
    // Start with the thing we already think clobbers this location
2355
1.12M
    MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
2356
1.12M
2357
1.12M
    // At this point, DefiningAccess may be the live on entry def.
2358
1.12M
    // If it is, we will not get a better result.
2359
1.12M
    if (MSSA->isLiveOnEntryDef(DefiningAccess)) {
2360
12
      StartingAccess->setOptimized(DefiningAccess);
2361
12
      StartingAccess->setOptimizedAccessType(None);
2362
12
      return DefiningAccess;
2363
12
    }
2364
1.12M
2365
1.12M
    OptimizedAccess = Walker.findClobber(DefiningAccess, Q, UpwardWalkLimit);
2366
1.12M
    StartingAccess->setOptimized(OptimizedAccess);
2367
1.12M
    if (MSSA->isLiveOnEntryDef(OptimizedAccess))
2368
59.4k
      StartingAccess->setOptimizedAccessType(None);
2369
1.07M
    else if (Q.AR == MustAlias)
2370
562
      StartingAccess->setOptimizedAccessType(MustAlias);
2371
1.12M
  } else
2372
21
    OptimizedAccess = StartingAccess->getOptimized();
2373
1.12M
2374
1.12M
  
LLVM_DEBUG1.12M
(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2375
1.12M
  LLVM_DEBUG(dbgs() << *StartingAccess << "\n");
2376
1.12M
  LLVM_DEBUG(dbgs() << "Optimized Memory SSA clobber for " << *I << " is ");
2377
1.12M
  LLVM_DEBUG(dbgs() << *OptimizedAccess << "\n");
2378
1.12M
2379
1.12M
  MemoryAccess *Result;
2380
1.12M
  if (SkipSelf && 
isa<MemoryPhi>(OptimizedAccess)47
&&
2381
1.12M
      
isa<MemoryDef>(StartingAccess)41
&&
UpwardWalkLimit41
) {
2382
41
    assert(isa<MemoryDef>(Q.OriginalAccess));
2383
41
    Q.SkipSelfAccess = true;
2384
41
    Result = Walker.findClobber(OptimizedAccess, Q, UpwardWalkLimit);
2385
41
  } else
2386
1.12M
    Result = OptimizedAccess;
2387
1.12M
2388
1.12M
  LLVM_DEBUG(dbgs() << "Result Memory SSA clobber [SkipSelf = " << SkipSelf);
2389
1.12M
  LLVM_DEBUG(dbgs() << "] for " << *I << " is " << *Result << "\n");
2390
1.12M
2391
1.12M
  return Result;
2392
1.12M
}
llvm::MemorySSA::ClobberWalkerBase<llvm::BatchAAResults>::getClobberingMemoryAccessBase(llvm::MemoryAccess*, unsigned int&, bool)
Line
Count
Source
2319
1.11M
    MemoryAccess *MA, unsigned &UpwardWalkLimit, bool SkipSelf) {
2320
1.11M
  auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
2321
1.11M
  // If this is a MemoryPhi, we can't do anything.
2322
1.11M
  if (!StartingAccess)
2323
0
    return MA;
2324
1.11M
2325
1.11M
  bool IsOptimized = false;
2326
1.11M
2327
1.11M
  // If this is an already optimized use or def, return the optimized result.
2328
1.11M
  // Note: Currently, we store the optimized def result in a separate field,
2329
1.11M
  // since we can't use the defining access.
2330
1.11M
  if (StartingAccess->isOptimized()) {
2331
0
    if (!SkipSelf || !isa<MemoryDef>(StartingAccess))
2332
0
      return StartingAccess->getOptimized();
2333
0
    IsOptimized = true;
2334
0
  }
2335
1.11M
2336
1.11M
  const Instruction *I = StartingAccess->getMemoryInst();
2337
1.11M
  // We can't sanely do anything with a fence, since they conservatively clobber
2338
1.11M
  // all memory, and have no locations to get pointers from to try to
2339
1.11M
  // disambiguate.
2340
1.11M
  if (!isa<CallBase>(I) && 
I->isFenceLike()1.10M
)
2341
0
    return StartingAccess;
2342
1.11M
2343
1.11M
  UpwardsMemoryQuery Q(I, StartingAccess);
2344
1.11M
2345
1.11M
  if (isUseTriviallyOptimizableToLiveOnEntry(*Walker.getAA(), I)) {
2346
0
    MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef();
2347
0
    StartingAccess->setOptimized(LiveOnEntry);
2348
0
    StartingAccess->setOptimizedAccessType(None);
2349
0
    return LiveOnEntry;
2350
0
  }
2351
1.11M
2352
1.11M
  MemoryAccess *OptimizedAccess;
2353
1.11M
  if (!IsOptimized) {
2354
1.11M
    // Start with the thing we already think clobbers this location
2355
1.11M
    MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
2356
1.11M
2357
1.11M
    // At this point, DefiningAccess may be the live on entry def.
2358
1.11M
    // If it is, we will not get a better result.
2359
1.11M
    if (MSSA->isLiveOnEntryDef(DefiningAccess)) {
2360
0
      StartingAccess->setOptimized(DefiningAccess);
2361
0
      StartingAccess->setOptimizedAccessType(None);
2362
0
      return DefiningAccess;
2363
0
    }
2364
1.11M
2365
1.11M
    OptimizedAccess = Walker.findClobber(DefiningAccess, Q, UpwardWalkLimit);
2366
1.11M
    StartingAccess->setOptimized(OptimizedAccess);
2367
1.11M
    if (MSSA->isLiveOnEntryDef(OptimizedAccess))
2368
53.7k
      StartingAccess->setOptimizedAccessType(None);
2369
1.06M
    else if (Q.AR == MustAlias)
2370
0
      StartingAccess->setOptimizedAccessType(MustAlias);
2371
1.11M
  } else
2372
0
    OptimizedAccess = StartingAccess->getOptimized();
2373
1.11M
2374
1.11M
  LLVM_DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2375
1.11M
  LLVM_DEBUG(dbgs() << *StartingAccess << "\n");
2376
1.11M
  LLVM_DEBUG(dbgs() << "Optimized Memory SSA clobber for " << *I << " is ");
2377
1.11M
  LLVM_DEBUG(dbgs() << *OptimizedAccess << "\n");
2378
1.11M
2379
1.11M
  MemoryAccess *Result;
2380
1.11M
  if (SkipSelf && 
isa<MemoryPhi>(OptimizedAccess)0
&&
2381
1.11M
      
isa<MemoryDef>(StartingAccess)0
&&
UpwardWalkLimit0
) {
2382
0
    assert(isa<MemoryDef>(Q.OriginalAccess));
2383
0
    Q.SkipSelfAccess = true;
2384
0
    Result = Walker.findClobber(OptimizedAccess, Q, UpwardWalkLimit);
2385
0
  } else
2386
1.11M
    Result = OptimizedAccess;
2387
1.11M
2388
1.11M
  LLVM_DEBUG(dbgs() << "Result Memory SSA clobber [SkipSelf = " << SkipSelf);
2389
1.11M
  LLVM_DEBUG(dbgs() << "] for " << *I << " is " << *Result << "\n");
2390
1.11M
2391
1.11M
  return Result;
2392
1.11M
}
llvm::MemorySSA::ClobberWalkerBase<llvm::AAResults>::getClobberingMemoryAccessBase(llvm::MemoryAccess*, unsigned int&, bool)
Line
Count
Source
2319
302k
    MemoryAccess *MA, unsigned &UpwardWalkLimit, bool SkipSelf) {
2320
302k
  auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
2321
302k
  // If this is a MemoryPhi, we can't do anything.
2322
302k
  if (!StartingAccess)
2323
0
    return MA;
2324
302k
2325
302k
  bool IsOptimized = false;
2326
302k
2327
302k
  // If this is an already optimized use or def, return the optimized result.
2328
302k
  // Note: Currently, we store the optimized def result in a separate field,
2329
302k
  // since we can't use the defining access.
2330
302k
  if (StartingAccess->isOptimized()) {
2331
287k
    if (!SkipSelf || 
!isa<MemoryDef>(StartingAccess)102
)
2332
287k
      return StartingAccess->getOptimized();
2333
21
    IsOptimized = true;
2334
21
  }
2335
302k
2336
302k
  const Instruction *I = StartingAccess->getMemoryInst();
2337
14.5k
  // We can't sanely do anything with a fence, since they conservatively clobber
2338
14.5k
  // all memory, and have no locations to get pointers from to try to
2339
14.5k
  // disambiguate.
2340
14.5k
  if (!isa<CallBase>(I) && 
I->isFenceLike()14.5k
)
2341
0
    return StartingAccess;
2342
14.5k
2343
14.5k
  UpwardsMemoryQuery Q(I, StartingAccess);
2344
14.5k
2345
14.5k
  if (isUseTriviallyOptimizableToLiveOnEntry(*Walker.getAA(), I)) {
2346
1
    MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef();
2347
1
    StartingAccess->setOptimized(LiveOnEntry);
2348
1
    StartingAccess->setOptimizedAccessType(None);
2349
1
    return LiveOnEntry;
2350
1
  }
2351
14.5k
2352
14.5k
  MemoryAccess *OptimizedAccess;
2353
14.5k
  if (!IsOptimized) {
2354
14.5k
    // Start with the thing we already think clobbers this location
2355
14.5k
    MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
2356
14.5k
2357
14.5k
    // At this point, DefiningAccess may be the live on entry def.
2358
14.5k
    // If it is, we will not get a better result.
2359
14.5k
    if (MSSA->isLiveOnEntryDef(DefiningAccess)) {
2360
12
      StartingAccess->setOptimized(DefiningAccess);
2361
12
      StartingAccess->setOptimizedAccessType(None);
2362
12
      return DefiningAccess;
2363
12
    }
2364
14.5k
2365
14.5k
    OptimizedAccess = Walker.findClobber(DefiningAccess, Q, UpwardWalkLimit);
2366
14.5k
    StartingAccess->setOptimized(OptimizedAccess);
2367
14.5k
    if (MSSA->isLiveOnEntryDef(OptimizedAccess))
2368
5.72k
      StartingAccess->setOptimizedAccessType(None);
2369
8.82k
    else if (Q.AR == MustAlias)
2370
562
      StartingAccess->setOptimizedAccessType(MustAlias);
2371
14.5k
  } else
2372
21
    OptimizedAccess = StartingAccess->getOptimized();
2373
14.5k
2374
14.5k
  
LLVM_DEBUG14.5k
(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2375
14.5k
  LLVM_DEBUG(dbgs() << *StartingAccess << "\n");
2376
14.5k
  LLVM_DEBUG(dbgs() << "Optimized Memory SSA clobber for " << *I << " is ");
2377
14.5k
  LLVM_DEBUG(dbgs() << *OptimizedAccess << "\n");
2378
14.5k
2379
14.5k
  MemoryAccess *Result;
2380
14.5k
  if (SkipSelf && 
isa<MemoryPhi>(OptimizedAccess)47
&&
2381
14.5k
      
isa<MemoryDef>(StartingAccess)41
&&
UpwardWalkLimit41
) {
2382
41
    assert(isa<MemoryDef>(Q.OriginalAccess));
2383
41
    Q.SkipSelfAccess = true;
2384
41
    Result = Walker.findClobber(OptimizedAccess, Q, UpwardWalkLimit);
2385
41
  } else
2386
14.5k
    Result = OptimizedAccess;
2387
14.5k
2388
14.5k
  LLVM_DEBUG(dbgs() << "Result Memory SSA clobber [SkipSelf = " << SkipSelf);
2389
14.5k
  LLVM_DEBUG(dbgs() << "] for " << *I << " is " << *Result << "\n");
2390
14.5k
2391
14.5k
  return Result;
2392
14.5k
}
2393
2394
MemoryAccess *
2395
0
DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
2396
0
  if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
2397
0
    return Use->getDefiningAccess();
2398
0
  return MA;
2399
0
}
2400
2401
MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
2402
0
    MemoryAccess *StartingAccess, const MemoryLocation &) {
2403
0
  if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
2404
0
    return Use->getDefiningAccess();
2405
0
  return StartingAccess;
2406
0
}
2407
2408
1.22M
void MemoryPhi::deleteMe(DerivedUser *Self) {
2409
1.22M
  delete static_cast<MemoryPhi *>(Self);
2410
1.22M
}
2411
2412
6.18M
void MemoryDef::deleteMe(DerivedUser *Self) {
2413
6.18M
  delete static_cast<MemoryDef *>(Self);
2414
6.18M
}
2415
2416
3.11M
void MemoryUse::deleteMe(DerivedUser *Self) {
2417
3.11M
  delete static_cast<MemoryUse *>(Self);
2418
3.11M
}