Bug Summary

File:llvm/lib/Analysis/MemorySSA.cpp
Warning:line 2063, column 5
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name MemorySSA.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/Analysis -I /build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/lib/Analysis -I include -I /build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-command-line-argument -Wno-unknown-warning-option -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/build-llvm -ferror-limit 19 -fvisibility-inlines-hidden -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-10-17-004846-21170-1 -x c++ /build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/lib/Analysis/MemorySSA.cpp

/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/lib/Analysis/MemorySSA.cpp

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

/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h

1//===- MemorySSA.h - Build Memory SSA ---------------------------*- C++ -*-===//
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/// \file
10/// This file exposes an interface to building/using memory SSA to
11/// walk memory instructions using a use/def graph.
12///
13/// Memory SSA class builds an SSA form that links together memory access
14/// instructions such as loads, stores, atomics, and calls. Additionally, it
15/// does a trivial form of "heap versioning" Every time the memory state changes
16/// in the program, we generate a new heap version. It generates
17/// MemoryDef/Uses/Phis that are overlayed on top of the existing instructions.
18///
19/// As a trivial example,
20/// define i32 @main() #0 {
21/// entry:
22/// %call = call noalias i8* @_Znwm(i64 4) #2
23/// %0 = bitcast i8* %call to i32*
24/// %call1 = call noalias i8* @_Znwm(i64 4) #2
25/// %1 = bitcast i8* %call1 to i32*
26/// store i32 5, i32* %0, align 4
27/// store i32 7, i32* %1, align 4
28/// %2 = load i32* %0, align 4
29/// %3 = load i32* %1, align 4
30/// %add = add nsw i32 %2, %3
31/// ret i32 %add
32/// }
33///
34/// Will become
35/// define i32 @main() #0 {
36/// entry:
37/// ; 1 = MemoryDef(0)
38/// %call = call noalias i8* @_Znwm(i64 4) #3
39/// %2 = bitcast i8* %call to i32*
40/// ; 2 = MemoryDef(1)
41/// %call1 = call noalias i8* @_Znwm(i64 4) #3
42/// %4 = bitcast i8* %call1 to i32*
43/// ; 3 = MemoryDef(2)
44/// store i32 5, i32* %2, align 4
45/// ; 4 = MemoryDef(3)
46/// store i32 7, i32* %4, align 4
47/// ; MemoryUse(3)
48/// %7 = load i32* %2, align 4
49/// ; MemoryUse(4)
50/// %8 = load i32* %4, align 4
51/// %add = add nsw i32 %7, %8
52/// ret i32 %add
53/// }
54///
55/// Given this form, all the stores that could ever effect the load at %8 can be
56/// gotten by using the MemoryUse associated with it, and walking from use to
57/// def until you hit the top of the function.
58///
59/// Each def also has a list of users associated with it, so you can walk from
60/// both def to users, and users to defs. Note that we disambiguate MemoryUses,
61/// but not the RHS of MemoryDefs. You can see this above at %7, which would
62/// otherwise be a MemoryUse(4). Being disambiguated means that for a given
63/// store, all the MemoryUses on its use lists are may-aliases of that store
64/// (but the MemoryDefs on its use list may not be).
65///
66/// MemoryDefs are not disambiguated because it would require multiple reaching
67/// definitions, which would require multiple phis, and multiple memoryaccesses
68/// per instruction.
69//
70//===----------------------------------------------------------------------===//
71
72#ifndef LLVM_ANALYSIS_MEMORYSSA_H
73#define LLVM_ANALYSIS_MEMORYSSA_H
74
75#include "llvm/ADT/DenseMap.h"
76#include "llvm/ADT/GraphTraits.h"
77#include "llvm/ADT/SmallPtrSet.h"
78#include "llvm/ADT/SmallVector.h"
79#include "llvm/ADT/ilist.h"
80#include "llvm/ADT/ilist_node.h"
81#include "llvm/ADT/iterator.h"
82#include "llvm/ADT/iterator_range.h"
83#include "llvm/ADT/simple_ilist.h"
84#include "llvm/Analysis/AliasAnalysis.h"
85#include "llvm/Analysis/MemoryLocation.h"
86#include "llvm/Analysis/PHITransAddr.h"
87#include "llvm/IR/BasicBlock.h"
88#include "llvm/IR/DerivedUser.h"
89#include "llvm/IR/Dominators.h"
90#include "llvm/IR/Module.h"
91#include "llvm/IR/Operator.h"
92#include "llvm/IR/Type.h"
93#include "llvm/IR/Use.h"
94#include "llvm/IR/User.h"
95#include "llvm/IR/Value.h"
96#include "llvm/IR/ValueHandle.h"
97#include "llvm/Pass.h"
98#include "llvm/Support/Casting.h"
99#include "llvm/Support/CommandLine.h"
100#include <algorithm>
101#include <cassert>
102#include <cstddef>
103#include <iterator>
104#include <memory>
105#include <utility>
106
107namespace llvm {
108
109class AllocaInst;
110class Function;
111class Instruction;
112class MemoryAccess;
113class MemorySSAWalker;
114class LLVMContext;
115class raw_ostream;
116
117namespace MSSAHelpers {
118
119struct AllAccessTag {};
120struct DefsOnlyTag {};
121
122} // end namespace MSSAHelpers
123
124enum : unsigned {
125 // Used to signify what the default invalid ID is for MemoryAccess's
126 // getID()
127 INVALID_MEMORYACCESS_ID = -1U
128};
129
130template <class T> class memoryaccess_def_iterator_base;
131using memoryaccess_def_iterator = memoryaccess_def_iterator_base<MemoryAccess>;
132using const_memoryaccess_def_iterator =
133 memoryaccess_def_iterator_base<const MemoryAccess>;
134
135// The base for all memory accesses. All memory accesses in a block are
136// linked together using an intrusive list.
137class MemoryAccess
138 : public DerivedUser,
139 public ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>,
140 public ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>> {
141public:
142 using AllAccessType =
143 ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>;
144 using DefsOnlyType =
145 ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>>;
146
147 MemoryAccess(const MemoryAccess &) = delete;
148 MemoryAccess &operator=(const MemoryAccess &) = delete;
149
150 void *operator new(size_t) = delete;
151
152 // Methods for support type inquiry through isa, cast, and
153 // dyn_cast
154 static bool classof(const Value *V) {
155 unsigned ID = V->getValueID();
156 return ID == MemoryUseVal || ID == MemoryPhiVal || ID == MemoryDefVal;
157 }
158
159 BasicBlock *getBlock() const { return Block; }
160
161 void print(raw_ostream &OS) const;
162 void dump() const;
163
164 /// The user iterators for a memory access
165 using iterator = user_iterator;
166 using const_iterator = const_user_iterator;
167
168 /// This iterator walks over all of the defs in a given
169 /// MemoryAccess. For MemoryPhi nodes, this walks arguments. For
170 /// MemoryUse/MemoryDef, this walks the defining access.
171 memoryaccess_def_iterator defs_begin();
172 const_memoryaccess_def_iterator defs_begin() const;
173 memoryaccess_def_iterator defs_end();
174 const_memoryaccess_def_iterator defs_end() const;
175
176 /// Get the iterators for the all access list and the defs only list
177 /// We default to the all access list.
178 AllAccessType::self_iterator getIterator() {
179 return this->AllAccessType::getIterator();
180 }
181 AllAccessType::const_self_iterator getIterator() const {
182 return this->AllAccessType::getIterator();
183 }
184 AllAccessType::reverse_self_iterator getReverseIterator() {
185 return this->AllAccessType::getReverseIterator();
186 }
187 AllAccessType::const_reverse_self_iterator getReverseIterator() const {
188 return this->AllAccessType::getReverseIterator();
189 }
190 DefsOnlyType::self_iterator getDefsIterator() {
191 return this->DefsOnlyType::getIterator();
192 }
193 DefsOnlyType::const_self_iterator getDefsIterator() const {
194 return this->DefsOnlyType::getIterator();
195 }
196 DefsOnlyType::reverse_self_iterator getReverseDefsIterator() {
197 return this->DefsOnlyType::getReverseIterator();
198 }
199 DefsOnlyType::const_reverse_self_iterator getReverseDefsIterator() const {
200 return this->DefsOnlyType::getReverseIterator();
201 }
202
203protected:
204 friend class MemoryDef;
205 friend class MemoryPhi;
206 friend class MemorySSA;
207 friend class MemoryUse;
208 friend class MemoryUseOrDef;
209
210 /// Used by MemorySSA to change the block of a MemoryAccess when it is
211 /// moved.
212 void setBlock(BasicBlock *BB) { Block = BB; }
213
214 /// Used for debugging and tracking things about MemoryAccesses.
215 /// Guaranteed unique among MemoryAccesses, no guarantees otherwise.
216 inline unsigned getID() const;
217
218 MemoryAccess(LLVMContext &C, unsigned Vty, DeleteValueTy DeleteValue,
219 BasicBlock *BB, unsigned NumOperands)
220 : DerivedUser(Type::getVoidTy(C), Vty, nullptr, NumOperands, DeleteValue),
221 Block(BB) {}
222
223 // Use deleteValue() to delete a generic MemoryAccess.
224 ~MemoryAccess() = default;
225
226private:
227 BasicBlock *Block;
228};
229
230template <>
231struct ilist_alloc_traits<MemoryAccess> {
232 static void deleteNode(MemoryAccess *MA) { MA->deleteValue(); }
233};
234
235inline raw_ostream &operator<<(raw_ostream &OS, const MemoryAccess &MA) {
236 MA.print(OS);
237 return OS;
238}
239
240/// Class that has the common methods + fields of memory uses/defs. It's
241/// a little awkward to have, but there are many cases where we want either a
242/// use or def, and there are many cases where uses are needed (defs aren't
243/// acceptable), and vice-versa.
244///
245/// This class should never be instantiated directly; make a MemoryUse or
246/// MemoryDef instead.
247class MemoryUseOrDef : public MemoryAccess {
248public:
249 void *operator new(size_t) = delete;
250
251 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess)public: inline MemoryAccess *getOperand(unsigned) const; inline
void setOperand(unsigned, MemoryAccess*); inline op_iterator
op_begin(); inline const_op_iterator op_begin() const; inline
op_iterator op_end(); inline const_op_iterator op_end() const
; protected: template <int> inline Use &Op(); template
<int> inline const Use &Op() const; public: inline
unsigned getNumOperands() const
;
252
253 /// Get the instruction that this MemoryUse represents.
254 Instruction *getMemoryInst() const { return MemoryInstruction; }
255
256 /// Get the access that produces the memory state used by this Use.
257 MemoryAccess *getDefiningAccess() const { return getOperand(0); }
258
259 static bool classof(const Value *MA) {
260 return MA->getValueID() == MemoryUseVal || MA->getValueID() == MemoryDefVal;
261 }
262
263 // Sadly, these have to be public because they are needed in some of the
264 // iterators.
265 inline bool isOptimized() const;
266 inline MemoryAccess *getOptimized() const;
267 inline void setOptimized(MemoryAccess *);
268
269 // Retrieve AliasResult type of the optimized access. Ideally this would be
270 // returned by the caching walker and may go away in the future.
271 Optional<AliasResult> getOptimizedAccessType() const {
272 return isOptimized() ? OptimizedAccessAlias : None;
273 }
274
275 /// Reset the ID of what this MemoryUse was optimized to, causing it to
276 /// be rewalked by the walker if necessary.
277 /// This really should only be called by tests.
278 inline void resetOptimized();
279
280protected:
281 friend class MemorySSA;
282 friend class MemorySSAUpdater;
283
284 MemoryUseOrDef(LLVMContext &C, MemoryAccess *DMA, unsigned Vty,
285 DeleteValueTy DeleteValue, Instruction *MI, BasicBlock *BB,
286 unsigned NumOperands)
287 : MemoryAccess(C, Vty, DeleteValue, BB, NumOperands),
288 MemoryInstruction(MI), OptimizedAccessAlias(AliasResult::MayAlias) {
289 setDefiningAccess(DMA);
290 }
291
292 // Use deleteValue() to delete a generic MemoryUseOrDef.
293 ~MemoryUseOrDef() = default;
294
295 void setOptimizedAccessType(Optional<AliasResult> AR) {
296 OptimizedAccessAlias = AR;
297 }
298
299 void setDefiningAccess(
300 MemoryAccess *DMA, bool Optimized = false,
301 Optional<AliasResult> AR = AliasResult(AliasResult::MayAlias)) {
302 if (!Optimized) {
303 setOperand(0, DMA);
304 return;
305 }
306 setOptimized(DMA);
307 setOptimizedAccessType(AR);
308 }
309
310private:
311 Instruction *MemoryInstruction;
312 Optional<AliasResult> OptimizedAccessAlias;
313};
314
315/// Represents read-only accesses to memory
316///
317/// In particular, the set of Instructions that will be represented by
318/// MemoryUse's is exactly the set of Instructions for which
319/// AliasAnalysis::getModRefInfo returns "Ref".
320class MemoryUse final : public MemoryUseOrDef {
321public:
322 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess)public: inline MemoryAccess *getOperand(unsigned) const; inline
void setOperand(unsigned, MemoryAccess*); inline op_iterator
op_begin(); inline const_op_iterator op_begin() const; inline
op_iterator op_end(); inline const_op_iterator op_end() const
; protected: template <int> inline Use &Op(); template
<int> inline const Use &Op() const; public: inline
unsigned getNumOperands() const
;
323
324 MemoryUse(LLVMContext &C, MemoryAccess *DMA, Instruction *MI, BasicBlock *BB)
325 : MemoryUseOrDef(C, DMA, MemoryUseVal, deleteMe, MI, BB,
326 /*NumOperands=*/1) {}
327
328 // allocate space for exactly one operand
329 void *operator new(size_t S) { return User::operator new(S, 1); }
330 void operator delete(void *Ptr) { User::operator delete(Ptr); }
331
332 static bool classof(const Value *MA) {
333 return MA->getValueID() == MemoryUseVal;
334 }
335
336 void print(raw_ostream &OS) const;
337
338 void setOptimized(MemoryAccess *DMA) {
339 OptimizedID = DMA->getID();
340 setOperand(0, DMA);
341 }
342
343 bool isOptimized() const {
344 return getDefiningAccess() && OptimizedID == getDefiningAccess()->getID();
345 }
346
347 MemoryAccess *getOptimized() const {
348 return getDefiningAccess();
349 }
350
351 void resetOptimized() {
352 OptimizedID = INVALID_MEMORYACCESS_ID;
353 }
354
355protected:
356 friend class MemorySSA;
357
358private:
359 static void deleteMe(DerivedUser *Self);
360
361 unsigned OptimizedID = INVALID_MEMORYACCESS_ID;
362};
363
364template <>
365struct OperandTraits<MemoryUse> : public FixedNumOperandTraits<MemoryUse, 1> {};
366DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryUse, MemoryAccess)MemoryUse::op_iterator MemoryUse::op_begin() { return OperandTraits
<MemoryUse>::op_begin(this); } MemoryUse::const_op_iterator
MemoryUse::op_begin() const { return OperandTraits<MemoryUse
>::op_begin(const_cast<MemoryUse*>(this)); } MemoryUse
::op_iterator MemoryUse::op_end() { return OperandTraits<MemoryUse
>::op_end(this); } MemoryUse::const_op_iterator MemoryUse::
op_end() const { return OperandTraits<MemoryUse>::op_end
(const_cast<MemoryUse*>(this)); } MemoryAccess *MemoryUse
::getOperand(unsigned i_nocapture) const { (static_cast <bool
> (i_nocapture < OperandTraits<MemoryUse>::operands
(this) && "getOperand() out of range!") ? void (0) : __assert_fail
("i_nocapture < OperandTraits<MemoryUse>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 366, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<MemoryAccess>( OperandTraits<MemoryUse>::op_begin
(const_cast<MemoryUse*>(this))[i_nocapture].get()); } void
MemoryUse::setOperand(unsigned i_nocapture, MemoryAccess *Val_nocapture
) { (static_cast <bool> (i_nocapture < OperandTraits
<MemoryUse>::operands(this) && "setOperand() out of range!"
) ? void (0) : __assert_fail ("i_nocapture < OperandTraits<MemoryUse>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 366, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
MemoryUse>::op_begin(this)[i_nocapture] = Val_nocapture; }
unsigned MemoryUse::getNumOperands() const { return OperandTraits
<MemoryUse>::operands(this); } template <int Idx_nocapture
> Use &MemoryUse::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
MemoryUse::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
367
368/// Represents a read-write access to memory, whether it is a must-alias,
369/// or a may-alias.
370///
371/// In particular, the set of Instructions that will be represented by
372/// MemoryDef's is exactly the set of Instructions for which
373/// AliasAnalysis::getModRefInfo returns "Mod" or "ModRef".
374/// Note that, in order to provide def-def chains, all defs also have a use
375/// associated with them. This use points to the nearest reaching
376/// MemoryDef/MemoryPhi.
377class MemoryDef final : public MemoryUseOrDef {
378public:
379 friend class MemorySSA;
380
381 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess)public: inline MemoryAccess *getOperand(unsigned) const; inline
void setOperand(unsigned, MemoryAccess*); inline op_iterator
op_begin(); inline const_op_iterator op_begin() const; inline
op_iterator op_end(); inline const_op_iterator op_end() const
; protected: template <int> inline Use &Op(); template
<int> inline const Use &Op() const; public: inline
unsigned getNumOperands() const
;
382
383 MemoryDef(LLVMContext &C, MemoryAccess *DMA, Instruction *MI, BasicBlock *BB,
384 unsigned Ver)
385 : MemoryUseOrDef(C, DMA, MemoryDefVal, deleteMe, MI, BB,
386 /*NumOperands=*/2),
387 ID(Ver) {}
388
389 // allocate space for exactly two operands
390 void *operator new(size_t S) { return User::operator new(S, 2); }
391 void operator delete(void *Ptr) { User::operator delete(Ptr); }
392
393 static bool classof(const Value *MA) {
394 return MA->getValueID() == MemoryDefVal;
395 }
396
397 void setOptimized(MemoryAccess *MA) {
398 setOperand(1, MA);
399 OptimizedID = MA->getID();
400 }
401
402 MemoryAccess *getOptimized() const {
403 return cast_or_null<MemoryAccess>(getOperand(1));
404 }
405
406 bool isOptimized() const {
407 return getOptimized() && OptimizedID == getOptimized()->getID();
408 }
409
410 void resetOptimized() {
411 OptimizedID = INVALID_MEMORYACCESS_ID;
412 setOperand(1, nullptr);
413 }
414
415 void print(raw_ostream &OS) const;
416
417 unsigned getID() const { return ID; }
418
419private:
420 static void deleteMe(DerivedUser *Self);
421
422 const unsigned ID;
423 unsigned OptimizedID = INVALID_MEMORYACCESS_ID;
424};
425
426template <>
427struct OperandTraits<MemoryDef> : public FixedNumOperandTraits<MemoryDef, 2> {};
428DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryDef, MemoryAccess)MemoryDef::op_iterator MemoryDef::op_begin() { return OperandTraits
<MemoryDef>::op_begin(this); } MemoryDef::const_op_iterator
MemoryDef::op_begin() const { return OperandTraits<MemoryDef
>::op_begin(const_cast<MemoryDef*>(this)); } MemoryDef
::op_iterator MemoryDef::op_end() { return OperandTraits<MemoryDef
>::op_end(this); } MemoryDef::const_op_iterator MemoryDef::
op_end() const { return OperandTraits<MemoryDef>::op_end
(const_cast<MemoryDef*>(this)); } MemoryAccess *MemoryDef
::getOperand(unsigned i_nocapture) const { (static_cast <bool
> (i_nocapture < OperandTraits<MemoryDef>::operands
(this) && "getOperand() out of range!") ? void (0) : __assert_fail
("i_nocapture < OperandTraits<MemoryDef>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 428, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<MemoryAccess>( OperandTraits<MemoryDef>::op_begin
(const_cast<MemoryDef*>(this))[i_nocapture].get()); } void
MemoryDef::setOperand(unsigned i_nocapture, MemoryAccess *Val_nocapture
) { (static_cast <bool> (i_nocapture < OperandTraits
<MemoryDef>::operands(this) && "setOperand() out of range!"
) ? void (0) : __assert_fail ("i_nocapture < OperandTraits<MemoryDef>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 428, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
MemoryDef>::op_begin(this)[i_nocapture] = Val_nocapture; }
unsigned MemoryDef::getNumOperands() const { return OperandTraits
<MemoryDef>::operands(this); } template <int Idx_nocapture
> Use &MemoryDef::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
MemoryDef::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
429
430template <>
431struct OperandTraits<MemoryUseOrDef> {
432 static Use *op_begin(MemoryUseOrDef *MUD) {
433 if (auto *MU = dyn_cast<MemoryUse>(MUD))
434 return OperandTraits<MemoryUse>::op_begin(MU);
435 return OperandTraits<MemoryDef>::op_begin(cast<MemoryDef>(MUD));
436 }
437
438 static Use *op_end(MemoryUseOrDef *MUD) {
439 if (auto *MU = dyn_cast<MemoryUse>(MUD))
440 return OperandTraits<MemoryUse>::op_end(MU);
441 return OperandTraits<MemoryDef>::op_end(cast<MemoryDef>(MUD));
442 }
443
444 static unsigned operands(const MemoryUseOrDef *MUD) {
445 if (const auto *MU = dyn_cast<MemoryUse>(MUD))
446 return OperandTraits<MemoryUse>::operands(MU);
447 return OperandTraits<MemoryDef>::operands(cast<MemoryDef>(MUD));
448 }
449};
450DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryUseOrDef, MemoryAccess)MemoryUseOrDef::op_iterator MemoryUseOrDef::op_begin() { return
OperandTraits<MemoryUseOrDef>::op_begin(this); } MemoryUseOrDef
::const_op_iterator MemoryUseOrDef::op_begin() const { return
OperandTraits<MemoryUseOrDef>::op_begin(const_cast<
MemoryUseOrDef*>(this)); } MemoryUseOrDef::op_iterator MemoryUseOrDef
::op_end() { return OperandTraits<MemoryUseOrDef>::op_end
(this); } MemoryUseOrDef::const_op_iterator MemoryUseOrDef::op_end
() const { return OperandTraits<MemoryUseOrDef>::op_end
(const_cast<MemoryUseOrDef*>(this)); } MemoryAccess *MemoryUseOrDef
::getOperand(unsigned i_nocapture) const { (static_cast <bool
> (i_nocapture < OperandTraits<MemoryUseOrDef>::operands
(this) && "getOperand() out of range!") ? void (0) : __assert_fail
("i_nocapture < OperandTraits<MemoryUseOrDef>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 450, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<MemoryAccess>( OperandTraits<MemoryUseOrDef>::op_begin
(const_cast<MemoryUseOrDef*>(this))[i_nocapture].get())
; } void MemoryUseOrDef::setOperand(unsigned i_nocapture, MemoryAccess
*Val_nocapture) { (static_cast <bool> (i_nocapture <
OperandTraits<MemoryUseOrDef>::operands(this) &&
"setOperand() out of range!") ? void (0) : __assert_fail ("i_nocapture < OperandTraits<MemoryUseOrDef>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 450, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
MemoryUseOrDef>::op_begin(this)[i_nocapture] = Val_nocapture
; } unsigned MemoryUseOrDef::getNumOperands() const { return OperandTraits
<MemoryUseOrDef>::operands(this); } template <int Idx_nocapture
> Use &MemoryUseOrDef::Op() { return this->OpFrom<
Idx_nocapture>(this); } template <int Idx_nocapture>
const Use &MemoryUseOrDef::Op() const { return this->
OpFrom<Idx_nocapture>(this); }
451
452/// Represents phi nodes for memory accesses.
453///
454/// These have the same semantic as regular phi nodes, with the exception that
455/// only one phi will ever exist in a given basic block.
456/// Guaranteeing one phi per block means guaranteeing there is only ever one
457/// valid reaching MemoryDef/MemoryPHI along each path to the phi node.
458/// This is ensured by not allowing disambiguation of the RHS of a MemoryDef or
459/// a MemoryPhi's operands.
460/// That is, given
461/// if (a) {
462/// store %a
463/// store %b
464/// }
465/// it *must* be transformed into
466/// if (a) {
467/// 1 = MemoryDef(liveOnEntry)
468/// store %a
469/// 2 = MemoryDef(1)
470/// store %b
471/// }
472/// and *not*
473/// if (a) {
474/// 1 = MemoryDef(liveOnEntry)
475/// store %a
476/// 2 = MemoryDef(liveOnEntry)
477/// store %b
478/// }
479/// even if the two stores do not conflict. Otherwise, both 1 and 2 reach the
480/// end of the branch, and if there are not two phi nodes, one will be
481/// disconnected completely from the SSA graph below that point.
482/// Because MemoryUse's do not generate new definitions, they do not have this
483/// issue.
484class MemoryPhi final : public MemoryAccess {
485 // allocate space for exactly zero operands
486 void *operator new(size_t S) { return User::operator new(S); }
487
488public:
489 void operator delete(void *Ptr) { User::operator delete(Ptr); }
490
491 /// Provide fast operand accessors
492 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess)public: inline MemoryAccess *getOperand(unsigned) const; inline
void setOperand(unsigned, MemoryAccess*); inline op_iterator
op_begin(); inline const_op_iterator op_begin() const; inline
op_iterator op_end(); inline const_op_iterator op_end() const
; protected: template <int> inline Use &Op(); template
<int> inline const Use &Op() const; public: inline
unsigned getNumOperands() const
;
493
494 MemoryPhi(LLVMContext &C, BasicBlock *BB, unsigned Ver, unsigned NumPreds = 0)
495 : MemoryAccess(C, MemoryPhiVal, deleteMe, BB, 0), ID(Ver),
496 ReservedSpace(NumPreds) {
497 allocHungoffUses(ReservedSpace);
498 }
499
500 // Block iterator interface. This provides access to the list of incoming
501 // basic blocks, which parallels the list of incoming values.
502 using block_iterator = BasicBlock **;
503 using const_block_iterator = BasicBlock *const *;
504
505 block_iterator block_begin() {
506 return reinterpret_cast<block_iterator>(op_begin() + ReservedSpace);
507 }
508
509 const_block_iterator block_begin() const {
510 return reinterpret_cast<const_block_iterator>(op_begin() + ReservedSpace);
511 }
512
513 block_iterator block_end() { return block_begin() + getNumOperands(); }
514
515 const_block_iterator block_end() const {
516 return block_begin() + getNumOperands();
517 }
518
519 iterator_range<block_iterator> blocks() {
520 return make_range(block_begin(), block_end());
521 }
522
523 iterator_range<const_block_iterator> blocks() const {
524 return make_range(block_begin(), block_end());
525 }
526
527 op_range incoming_values() { return operands(); }
528
529 const_op_range incoming_values() const { return operands(); }
530
531 /// Return the number of incoming edges
532 unsigned getNumIncomingValues() const { return getNumOperands(); }
533
534 /// Return incoming value number x
535 MemoryAccess *getIncomingValue(unsigned I) const { return getOperand(I); }
536 void setIncomingValue(unsigned I, MemoryAccess *V) {
537 assert(V && "PHI node got a null value!")(static_cast <bool> (V && "PHI node got a null value!"
) ? void (0) : __assert_fail ("V && \"PHI node got a null value!\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 537, __extension__ __PRETTY_FUNCTION__))
;
538 setOperand(I, V);
539 }
540
541 static unsigned getOperandNumForIncomingValue(unsigned I) { return I; }
542 static unsigned getIncomingValueNumForOperand(unsigned I) { return I; }
543
544 /// Return incoming basic block number @p i.
545 BasicBlock *getIncomingBlock(unsigned I) const { return block_begin()[I]; }
546
547 /// Return incoming basic block corresponding
548 /// to an operand of the PHI.
549 BasicBlock *getIncomingBlock(const Use &U) const {
550 assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?")(static_cast <bool> (this == U.getUser() && "Iterator doesn't point to PHI's Uses?"
) ? void (0) : __assert_fail ("this == U.getUser() && \"Iterator doesn't point to PHI's Uses?\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 550, __extension__ __PRETTY_FUNCTION__))
;
551 return getIncomingBlock(unsigned(&U - op_begin()));
552 }
553
554 /// Return incoming basic block corresponding
555 /// to value use iterator.
556 BasicBlock *getIncomingBlock(MemoryAccess::const_user_iterator I) const {
557 return getIncomingBlock(I.getUse());
558 }
559
560 void setIncomingBlock(unsigned I, BasicBlock *BB) {
561 assert(BB && "PHI node got a null basic block!")(static_cast <bool> (BB && "PHI node got a null basic block!"
) ? void (0) : __assert_fail ("BB && \"PHI node got a null basic block!\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 561, __extension__ __PRETTY_FUNCTION__))
;
562 block_begin()[I] = BB;
563 }
564
565 /// Add an incoming value to the end of the PHI list
566 void addIncoming(MemoryAccess *V, BasicBlock *BB) {
567 if (getNumOperands() == ReservedSpace)
568 growOperands(); // Get more space!
569 // Initialize some new operands.
570 setNumHungOffUseOperands(getNumOperands() + 1);
571 setIncomingValue(getNumOperands() - 1, V);
572 setIncomingBlock(getNumOperands() - 1, BB);
573 }
574
575 /// Return the first index of the specified basic
576 /// block in the value list for this PHI. Returns -1 if no instance.
577 int getBasicBlockIndex(const BasicBlock *BB) const {
578 for (unsigned I = 0, E = getNumOperands(); I != E; ++I)
579 if (block_begin()[I] == BB)
580 return I;
581 return -1;
582 }
583
584 MemoryAccess *getIncomingValueForBlock(const BasicBlock *BB) const {
585 int Idx = getBasicBlockIndex(BB);
586 assert(Idx >= 0 && "Invalid basic block argument!")(static_cast <bool> (Idx >= 0 && "Invalid basic block argument!"
) ? void (0) : __assert_fail ("Idx >= 0 && \"Invalid basic block argument!\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 586, __extension__ __PRETTY_FUNCTION__))
;
587 return getIncomingValue(Idx);
588 }
589
590 // After deleting incoming position I, the order of incoming may be changed.
591 void unorderedDeleteIncoming(unsigned I) {
592 unsigned E = getNumOperands();
593 assert(I < E && "Cannot remove out of bounds Phi entry.")(static_cast <bool> (I < E && "Cannot remove out of bounds Phi entry."
) ? void (0) : __assert_fail ("I < E && \"Cannot remove out of bounds Phi entry.\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 593, __extension__ __PRETTY_FUNCTION__))
;
594 // MemoryPhi must have at least two incoming values, otherwise the MemoryPhi
595 // itself should be deleted.
596 assert(E >= 2 && "Cannot only remove incoming values in MemoryPhis with "(static_cast <bool> (E >= 2 && "Cannot only remove incoming values in MemoryPhis with "
"at least 2 values.") ? void (0) : __assert_fail ("E >= 2 && \"Cannot only remove incoming values in MemoryPhis with \" \"at least 2 values.\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 597, __extension__ __PRETTY_FUNCTION__))
597 "at least 2 values.")(static_cast <bool> (E >= 2 && "Cannot only remove incoming values in MemoryPhis with "
"at least 2 values.") ? void (0) : __assert_fail ("E >= 2 && \"Cannot only remove incoming values in MemoryPhis with \" \"at least 2 values.\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 597, __extension__ __PRETTY_FUNCTION__))
;
598 setIncomingValue(I, getIncomingValue(E - 1));
599 setIncomingBlock(I, block_begin()[E - 1]);
600 setOperand(E - 1, nullptr);
601 block_begin()[E - 1] = nullptr;
602 setNumHungOffUseOperands(getNumOperands() - 1);
603 }
604
605 // After deleting entries that satisfy Pred, remaining entries may have
606 // changed order.
607 template <typename Fn> void unorderedDeleteIncomingIf(Fn &&Pred) {
608 for (unsigned I = 0, E = getNumOperands(); I != E; ++I)
609 if (Pred(getIncomingValue(I), getIncomingBlock(I))) {
610 unorderedDeleteIncoming(I);
611 E = getNumOperands();
612 --I;
613 }
614 assert(getNumOperands() >= 1 &&(static_cast <bool> (getNumOperands() >= 1 &&
"Cannot remove all incoming blocks in a MemoryPhi.") ? void (
0) : __assert_fail ("getNumOperands() >= 1 && \"Cannot remove all incoming blocks in a MemoryPhi.\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 615, __extension__ __PRETTY_FUNCTION__))
615 "Cannot remove all incoming blocks in a MemoryPhi.")(static_cast <bool> (getNumOperands() >= 1 &&
"Cannot remove all incoming blocks in a MemoryPhi.") ? void (
0) : __assert_fail ("getNumOperands() >= 1 && \"Cannot remove all incoming blocks in a MemoryPhi.\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 615, __extension__ __PRETTY_FUNCTION__))
;
616 }
617
618 // After deleting incoming block BB, the incoming blocks order may be changed.
619 void unorderedDeleteIncomingBlock(const BasicBlock *BB) {
620 unorderedDeleteIncomingIf(
621 [&](const MemoryAccess *, const BasicBlock *B) { return BB == B; });
622 }
623
624 // After deleting incoming memory access MA, the incoming accesses order may
625 // be changed.
626 void unorderedDeleteIncomingValue(const MemoryAccess *MA) {
627 unorderedDeleteIncomingIf(
628 [&](const MemoryAccess *M, const BasicBlock *) { return MA == M; });
629 }
630
631 static bool classof(const Value *V) {
632 return V->getValueID() == MemoryPhiVal;
633 }
634
635 void print(raw_ostream &OS) const;
636
637 unsigned getID() const { return ID; }
638
639protected:
640 friend class MemorySSA;
641
642 /// this is more complicated than the generic
643 /// User::allocHungoffUses, because we have to allocate Uses for the incoming
644 /// values and pointers to the incoming blocks, all in one allocation.
645 void allocHungoffUses(unsigned N) {
646 User::allocHungoffUses(N, /* IsPhi */ true);
647 }
648
649private:
650 // For debugging only
651 const unsigned ID;
652 unsigned ReservedSpace;
653
654 /// This grows the operand list in response to a push_back style of
655 /// operation. This grows the number of ops by 1.5 times.
656 void growOperands() {
657 unsigned E = getNumOperands();
658 // 2 op PHI nodes are VERY common, so reserve at least enough for that.
659 ReservedSpace = std::max(E + E / 2, 2u);
660 growHungoffUses(ReservedSpace, /* IsPhi */ true);
661 }
662
663 static void deleteMe(DerivedUser *Self);
664};
665
666inline unsigned MemoryAccess::getID() const {
667 assert((isa<MemoryDef>(this) || isa<MemoryPhi>(this)) &&(static_cast <bool> ((isa<MemoryDef>(this) || isa
<MemoryPhi>(this)) && "only memory defs and phis have ids"
) ? void (0) : __assert_fail ("(isa<MemoryDef>(this) || isa<MemoryPhi>(this)) && \"only memory defs and phis have ids\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 668, __extension__ __PRETTY_FUNCTION__))
668 "only memory defs and phis have ids")(static_cast <bool> ((isa<MemoryDef>(this) || isa
<MemoryPhi>(this)) && "only memory defs and phis have ids"
) ? void (0) : __assert_fail ("(isa<MemoryDef>(this) || isa<MemoryPhi>(this)) && \"only memory defs and phis have ids\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 668, __extension__ __PRETTY_FUNCTION__))
;
669 if (const auto *MD = dyn_cast<MemoryDef>(this))
670 return MD->getID();
671 return cast<MemoryPhi>(this)->getID();
672}
673
674inline bool MemoryUseOrDef::isOptimized() const {
675 if (const auto *MD = dyn_cast<MemoryDef>(this))
676 return MD->isOptimized();
677 return cast<MemoryUse>(this)->isOptimized();
678}
679
680inline MemoryAccess *MemoryUseOrDef::getOptimized() const {
681 if (const auto *MD = dyn_cast<MemoryDef>(this))
682 return MD->getOptimized();
683 return cast<MemoryUse>(this)->getOptimized();
684}
685
686inline void MemoryUseOrDef::setOptimized(MemoryAccess *MA) {
687 if (auto *MD = dyn_cast<MemoryDef>(this))
688 MD->setOptimized(MA);
689 else
690 cast<MemoryUse>(this)->setOptimized(MA);
691}
692
693inline void MemoryUseOrDef::resetOptimized() {
694 if (auto *MD = dyn_cast<MemoryDef>(this))
695 MD->resetOptimized();
696 else
697 cast<MemoryUse>(this)->resetOptimized();
698}
699
700template <> struct OperandTraits<MemoryPhi> : public HungoffOperandTraits<2> {};
701DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryPhi, MemoryAccess)MemoryPhi::op_iterator MemoryPhi::op_begin() { return OperandTraits
<MemoryPhi>::op_begin(this); } MemoryPhi::const_op_iterator
MemoryPhi::op_begin() const { return OperandTraits<MemoryPhi
>::op_begin(const_cast<MemoryPhi*>(this)); } MemoryPhi
::op_iterator MemoryPhi::op_end() { return OperandTraits<MemoryPhi
>::op_end(this); } MemoryPhi::const_op_iterator MemoryPhi::
op_end() const { return OperandTraits<MemoryPhi>::op_end
(const_cast<MemoryPhi*>(this)); } MemoryAccess *MemoryPhi
::getOperand(unsigned i_nocapture) const { (static_cast <bool
> (i_nocapture < OperandTraits<MemoryPhi>::operands
(this) && "getOperand() out of range!") ? void (0) : __assert_fail
("i_nocapture < OperandTraits<MemoryPhi>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 701, __extension__ __PRETTY_FUNCTION__)); return cast_or_null
<MemoryAccess>( OperandTraits<MemoryPhi>::op_begin
(const_cast<MemoryPhi*>(this))[i_nocapture].get()); } void
MemoryPhi::setOperand(unsigned i_nocapture, MemoryAccess *Val_nocapture
) { (static_cast <bool> (i_nocapture < OperandTraits
<MemoryPhi>::operands(this) && "setOperand() out of range!"
) ? void (0) : __assert_fail ("i_nocapture < OperandTraits<MemoryPhi>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 701, __extension__ __PRETTY_FUNCTION__)); OperandTraits<
MemoryPhi>::op_begin(this)[i_nocapture] = Val_nocapture; }
unsigned MemoryPhi::getNumOperands() const { return OperandTraits
<MemoryPhi>::operands(this); } template <int Idx_nocapture
> Use &MemoryPhi::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
MemoryPhi::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
702
703/// Encapsulates MemorySSA, including all data associated with memory
704/// accesses.
705class MemorySSA {
706public:
707 MemorySSA(Function &, AliasAnalysis *, DominatorTree *);
708
709 // MemorySSA must remain where it's constructed; Walkers it creates store
710 // pointers to it.
711 MemorySSA(MemorySSA &&) = delete;
712
713 ~MemorySSA();
714
715 MemorySSAWalker *getWalker();
716 MemorySSAWalker *getSkipSelfWalker();
717
718 /// Given a memory Mod/Ref'ing instruction, get the MemorySSA
719 /// access associated with it. If passed a basic block gets the memory phi
720 /// node that exists for that block, if there is one. Otherwise, this will get
721 /// a MemoryUseOrDef.
722 MemoryUseOrDef *getMemoryAccess(const Instruction *I) const {
723 return cast_or_null<MemoryUseOrDef>(ValueToMemoryAccess.lookup(I));
724 }
725
726 MemoryPhi *getMemoryAccess(const BasicBlock *BB) const {
727 return cast_or_null<MemoryPhi>(ValueToMemoryAccess.lookup(cast<Value>(BB)));
23
'BB' is a 'Value'
24
Assuming null pointer is passed into cast
25
Returning null pointer, which participates in a condition later
728 }
729
730 DominatorTree &getDomTree() const { return *DT; }
731
732 void dump() const;
733 void print(raw_ostream &) const;
734
735 /// Return true if \p MA represents the live on entry value
736 ///
737 /// Loads and stores from pointer arguments and other global values may be
738 /// defined by memory operations that do not occur in the current function, so
739 /// they may be live on entry to the function. MemorySSA represents such
740 /// memory state by the live on entry definition, which is guaranteed to occur
741 /// before any other memory access in the function.
742 inline bool isLiveOnEntryDef(const MemoryAccess *MA) const {
743 return MA == LiveOnEntryDef.get();
744 }
745
746 inline MemoryAccess *getLiveOnEntryDef() const {
747 return LiveOnEntryDef.get();
748 }
749
750 // Sadly, iplists, by default, owns and deletes pointers added to the
751 // list. It's not currently possible to have two iplists for the same type,
752 // where one owns the pointers, and one does not. This is because the traits
753 // are per-type, not per-tag. If this ever changes, we should make the
754 // DefList an iplist.
755 using AccessList = iplist<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>;
756 using DefsList =
757 simple_ilist<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>>;
758
759 /// Return the list of MemoryAccess's for a given basic block.
760 ///
761 /// This list is not modifiable by the user.
762 const AccessList *getBlockAccesses(const BasicBlock *BB) const {
763 return getWritableBlockAccesses(BB);
6
Calling 'MemorySSA::getWritableBlockAccesses'
10
Returning from 'MemorySSA::getWritableBlockAccesses'
11
Returning pointer, which participates in a condition later
12
Returning pointer
764 }
765
766 /// Return the list of MemoryDef's and MemoryPhi's for a given basic
767 /// block.
768 ///
769 /// This list is not modifiable by the user.
770 const DefsList *getBlockDefs(const BasicBlock *BB) const {
771 return getWritableBlockDefs(BB);
16
Calling 'MemorySSA::getWritableBlockDefs'
19
Returning from 'MemorySSA::getWritableBlockDefs'
20
Returning pointer, which participates in a condition later
772 }
773
774 /// Given two memory accesses in the same basic block, determine
775 /// whether MemoryAccess \p A dominates MemoryAccess \p B.
776 bool locallyDominates(const MemoryAccess *A, const MemoryAccess *B) const;
777
778 /// Given two memory accesses in potentially different blocks,
779 /// determine whether MemoryAccess \p A dominates MemoryAccess \p B.
780 bool dominates(const MemoryAccess *A, const MemoryAccess *B) const;
781
782 /// Given a MemoryAccess and a Use, determine whether MemoryAccess \p A
783 /// dominates Use \p B.
784 bool dominates(const MemoryAccess *A, const Use &B) const;
785
786 enum class VerificationLevel { Fast, Full };
787 /// Verify that MemorySSA is self consistent (IE definitions dominate
788 /// all uses, uses appear in the right places). This is used by unit tests.
789 void verifyMemorySSA(VerificationLevel = VerificationLevel::Fast) const;
790
791 /// Used in various insertion functions to specify whether we are talking
792 /// about the beginning or end of a block.
793 enum InsertionPlace { Beginning, End, BeforeTerminator };
794
795protected:
796 // Used by Memory SSA dumpers and wrapper pass
797 friend class MemorySSAPrinterLegacyPass;
798 friend class MemorySSAUpdater;
799
800 void verifyOrderingDominationAndDefUses(
801 Function &F, VerificationLevel = VerificationLevel::Fast) const;
802 void verifyDominationNumbers(const Function &F) const;
803 void verifyPrevDefInPhis(Function &F) const;
804
805 // This is used by the use optimizer and updater.
806 AccessList *getWritableBlockAccesses(const BasicBlock *BB) const {
807 auto It = PerBlockAccesses.find(BB);
808 return It == PerBlockAccesses.end() ? nullptr : It->second.get();
7
'?' condition is false
8
Returning pointer, which participates in a condition later
9
Returning pointer
809 }
810
811 // This is used by the use optimizer and updater.
812 DefsList *getWritableBlockDefs(const BasicBlock *BB) const {
813 auto It = PerBlockDefs.find(BB);
814 return It == PerBlockDefs.end() ? nullptr : It->second.get();
17
'?' condition is false
18
Returning pointer, which participates in a condition later
815 }
816
817 // These is used by the updater to perform various internal MemorySSA
818 // machinsations. They do not always leave the IR in a correct state, and
819 // relies on the updater to fixup what it breaks, so it is not public.
820
821 void moveTo(MemoryUseOrDef *What, BasicBlock *BB, AccessList::iterator Where);
822 void moveTo(MemoryAccess *What, BasicBlock *BB, InsertionPlace Point);
823
824 // Rename the dominator tree branch rooted at BB.
825 void renamePass(BasicBlock *BB, MemoryAccess *IncomingVal,
826 SmallPtrSetImpl<BasicBlock *> &Visited) {
827 renamePass(DT->getNode(BB), IncomingVal, Visited, true, true);
828 }
829
830 void removeFromLookups(MemoryAccess *);
831 void removeFromLists(MemoryAccess *, bool ShouldDelete = true);
832 void insertIntoListsForBlock(MemoryAccess *, const BasicBlock *,
833 InsertionPlace);
834 void insertIntoListsBefore(MemoryAccess *, const BasicBlock *,
835 AccessList::iterator);
836 MemoryUseOrDef *createDefinedAccess(Instruction *, MemoryAccess *,
837 const MemoryUseOrDef *Template = nullptr,
838 bool CreationMustSucceed = true);
839
840private:
841 template <class AliasAnalysisType> class ClobberWalkerBase;
842 template <class AliasAnalysisType> class CachingWalker;
843 template <class AliasAnalysisType> class SkipSelfWalker;
844 class OptimizeUses;
845
846 CachingWalker<AliasAnalysis> *getWalkerImpl();
847 void buildMemorySSA(BatchAAResults &BAA);
848
849 void prepareForMoveTo(MemoryAccess *, BasicBlock *);
850 void verifyUseInDefs(MemoryAccess *, MemoryAccess *) const;
851
852 using AccessMap = DenseMap<const BasicBlock *, std::unique_ptr<AccessList>>;
853 using DefsMap = DenseMap<const BasicBlock *, std::unique_ptr<DefsList>>;
854
855 void markUnreachableAsLiveOnEntry(BasicBlock *BB);
856 MemoryPhi *createMemoryPhi(BasicBlock *BB);
857 template <typename AliasAnalysisType>
858 MemoryUseOrDef *createNewAccess(Instruction *, AliasAnalysisType *,
859 const MemoryUseOrDef *Template = nullptr);
860 void placePHINodes(const SmallPtrSetImpl<BasicBlock *> &);
861 MemoryAccess *renameBlock(BasicBlock *, MemoryAccess *, bool);
862 void renameSuccessorPhis(BasicBlock *, MemoryAccess *, bool);
863 void renamePass(DomTreeNode *, MemoryAccess *IncomingVal,
864 SmallPtrSetImpl<BasicBlock *> &Visited,
865 bool SkipVisited = false, bool RenameAllUses = false);
866 AccessList *getOrCreateAccessList(const BasicBlock *);
867 DefsList *getOrCreateDefsList(const BasicBlock *);
868 void renumberBlock(const BasicBlock *) const;
869 AliasAnalysis *AA;
870 DominatorTree *DT;
871 Function &F;
872
873 // Memory SSA mappings
874 DenseMap<const Value *, MemoryAccess *> ValueToMemoryAccess;
875
876 // These two mappings contain the main block to access/def mappings for
877 // MemorySSA. The list contained in PerBlockAccesses really owns all the
878 // MemoryAccesses.
879 // Both maps maintain the invariant that if a block is found in them, the
880 // corresponding list is not empty, and if a block is not found in them, the
881 // corresponding list is empty.
882 AccessMap PerBlockAccesses;
883 DefsMap PerBlockDefs;
884 std::unique_ptr<MemoryAccess, ValueDeleter> LiveOnEntryDef;
885
886 // Domination mappings
887 // Note that the numbering is local to a block, even though the map is
888 // global.
889 mutable SmallPtrSet<const BasicBlock *, 16> BlockNumberingValid;
890 mutable DenseMap<const MemoryAccess *, unsigned long> BlockNumbering;
891
892 // Memory SSA building info
893 std::unique_ptr<ClobberWalkerBase<AliasAnalysis>> WalkerBase;
894 std::unique_ptr<CachingWalker<AliasAnalysis>> Walker;
895 std::unique_ptr<SkipSelfWalker<AliasAnalysis>> SkipWalker;
896 unsigned NextID;
897};
898
899/// Enables verification of MemorySSA.
900///
901/// The checks which this flag enables is exensive and disabled by default
902/// unless `EXPENSIVE_CHECKS` is defined. The flag `-verify-memoryssa` can be
903/// used to selectively enable the verification without re-compilation.
904extern bool VerifyMemorySSA;
905
906// Internal MemorySSA utils, for use by MemorySSA classes and walkers
907class MemorySSAUtil {
908protected:
909 friend class GVNHoist;
910 friend class MemorySSAWalker;
911
912 // This function should not be used by new passes.
913 static bool defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU,
914 AliasAnalysis &AA);
915};
916
917// This pass does eager building and then printing of MemorySSA. It is used by
918// the tests to be able to build, dump, and verify Memory SSA.
919class MemorySSAPrinterLegacyPass : public FunctionPass {
920public:
921 MemorySSAPrinterLegacyPass();
922
923 bool runOnFunction(Function &) override;
924 void getAnalysisUsage(AnalysisUsage &AU) const override;
925
926 static char ID;
927};
928
929/// An analysis that produces \c MemorySSA for a function.
930///
931class MemorySSAAnalysis : public AnalysisInfoMixin<MemorySSAAnalysis> {
932 friend AnalysisInfoMixin<MemorySSAAnalysis>;
933
934 static AnalysisKey Key;
935
936public:
937 // Wrap MemorySSA result to ensure address stability of internal MemorySSA
938 // pointers after construction. Use a wrapper class instead of plain
939 // unique_ptr<MemorySSA> to avoid build breakage on MSVC.
940 struct Result {
941 Result(std::unique_ptr<MemorySSA> &&MSSA) : MSSA(std::move(MSSA)) {}
942
943 MemorySSA &getMSSA() { return *MSSA.get(); }
944
945 std::unique_ptr<MemorySSA> MSSA;
946
947 bool invalidate(Function &F, const PreservedAnalyses &PA,
948 FunctionAnalysisManager::Invalidator &Inv);
949 };
950
951 Result run(Function &F, FunctionAnalysisManager &AM);
952};
953
954/// Printer pass for \c MemorySSA.
955class MemorySSAPrinterPass : public PassInfoMixin<MemorySSAPrinterPass> {
956 raw_ostream &OS;
957
958public:
959 explicit MemorySSAPrinterPass(raw_ostream &OS) : OS(OS) {}
960
961 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
962};
963
964/// Printer pass for \c MemorySSA via the walker.
965class MemorySSAWalkerPrinterPass
966 : public PassInfoMixin<MemorySSAWalkerPrinterPass> {
967 raw_ostream &OS;
968
969public:
970 explicit MemorySSAWalkerPrinterPass(raw_ostream &OS) : OS(OS) {}
971
972 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
973};
974
975/// Verifier pass for \c MemorySSA.
976struct MemorySSAVerifierPass : PassInfoMixin<MemorySSAVerifierPass> {
977 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
978};
979
980/// Legacy analysis pass which computes \c MemorySSA.
981class MemorySSAWrapperPass : public FunctionPass {
982public:
983 MemorySSAWrapperPass();
984
985 static char ID;
986
987 bool runOnFunction(Function &) override;
988 void releaseMemory() override;
989 MemorySSA &getMSSA() { return *MSSA; }
990 const MemorySSA &getMSSA() const { return *MSSA; }
991
992 void getAnalysisUsage(AnalysisUsage &AU) const override;
993
994 void verifyAnalysis() const override;
995 void print(raw_ostream &OS, const Module *M = nullptr) const override;
996
997private:
998 std::unique_ptr<MemorySSA> MSSA;
999};
1000
1001/// This is the generic walker interface for walkers of MemorySSA.
1002/// Walkers are used to be able to further disambiguate the def-use chains
1003/// MemorySSA gives you, or otherwise produce better info than MemorySSA gives
1004/// you.
1005/// In particular, while the def-use chains provide basic information, and are
1006/// guaranteed to give, for example, the nearest may-aliasing MemoryDef for a
1007/// MemoryUse as AliasAnalysis considers it, a user mant want better or other
1008/// information. In particular, they may want to use SCEV info to further
1009/// disambiguate memory accesses, or they may want the nearest dominating
1010/// may-aliasing MemoryDef for a call or a store. This API enables a
1011/// standardized interface to getting and using that info.
1012class MemorySSAWalker {
1013public:
1014 MemorySSAWalker(MemorySSA *);
1015 virtual ~MemorySSAWalker() = default;
1016
1017 using MemoryAccessSet = SmallVector<MemoryAccess *, 8>;
1018
1019 /// Given a memory Mod/Ref/ModRef'ing instruction, calling this
1020 /// will give you the nearest dominating MemoryAccess that Mod's the location
1021 /// the instruction accesses (by skipping any def which AA can prove does not
1022 /// alias the location(s) accessed by the instruction given).
1023 ///
1024 /// Note that this will return a single access, and it must dominate the
1025 /// Instruction, so if an operand of a MemoryPhi node Mod's the instruction,
1026 /// this will return the MemoryPhi, not the operand. This means that
1027 /// given:
1028 /// if (a) {
1029 /// 1 = MemoryDef(liveOnEntry)
1030 /// store %a
1031 /// } else {
1032 /// 2 = MemoryDef(liveOnEntry)
1033 /// store %b
1034 /// }
1035 /// 3 = MemoryPhi(2, 1)
1036 /// MemoryUse(3)
1037 /// load %a
1038 ///
1039 /// calling this API on load(%a) will return the MemoryPhi, not the MemoryDef
1040 /// in the if (a) branch.
1041 MemoryAccess *getClobberingMemoryAccess(const Instruction *I) {
1042 MemoryAccess *MA = MSSA->getMemoryAccess(I);
1043 assert(MA && "Handed an instruction that MemorySSA doesn't recognize?")(static_cast <bool> (MA && "Handed an instruction that MemorySSA doesn't recognize?"
) ? void (0) : __assert_fail ("MA && \"Handed an instruction that MemorySSA doesn't recognize?\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 1043, __extension__ __PRETTY_FUNCTION__))
;
1044 return getClobberingMemoryAccess(MA);
1045 }
1046
1047 /// Does the same thing as getClobberingMemoryAccess(const Instruction *I),
1048 /// but takes a MemoryAccess instead of an Instruction.
1049 virtual MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) = 0;
1050
1051 /// Given a potentially clobbering memory access and a new location,
1052 /// calling this will give you the nearest dominating clobbering MemoryAccess
1053 /// (by skipping non-aliasing def links).
1054 ///
1055 /// This version of the function is mainly used to disambiguate phi translated
1056 /// pointers, where the value of a pointer may have changed from the initial
1057 /// memory access. Note that this expects to be handed either a MemoryUse,
1058 /// or an already potentially clobbering access. Unlike the above API, if
1059 /// given a MemoryDef that clobbers the pointer as the starting access, it
1060 /// will return that MemoryDef, whereas the above would return the clobber
1061 /// starting from the use side of the memory def.
1062 virtual MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
1063 const MemoryLocation &) = 0;
1064
1065 /// Given a memory access, invalidate anything this walker knows about
1066 /// that access.
1067 /// This API is used by walkers that store information to perform basic cache
1068 /// invalidation. This will be called by MemorySSA at appropriate times for
1069 /// the walker it uses or returns.
1070 virtual void invalidateInfo(MemoryAccess *) {}
1071
1072protected:
1073 friend class MemorySSA; // For updating MSSA pointer in MemorySSA move
1074 // constructor.
1075 MemorySSA *MSSA;
1076};
1077
1078/// A MemorySSAWalker that does no alias queries, or anything else. It
1079/// simply returns the links as they were constructed by the builder.
1080class DoNothingMemorySSAWalker final : public MemorySSAWalker {
1081public:
1082 // Keep the overrides below from hiding the Instruction overload of
1083 // getClobberingMemoryAccess.
1084 using MemorySSAWalker::getClobberingMemoryAccess;
1085
1086 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) override;
1087 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
1088 const MemoryLocation &) override;
1089};
1090
1091using MemoryAccessPair = std::pair<MemoryAccess *, MemoryLocation>;
1092using ConstMemoryAccessPair = std::pair<const MemoryAccess *, MemoryLocation>;
1093
1094/// Iterator base class used to implement const and non-const iterators
1095/// over the defining accesses of a MemoryAccess.
1096template <class T>
1097class memoryaccess_def_iterator_base
1098 : public iterator_facade_base<memoryaccess_def_iterator_base<T>,
1099 std::forward_iterator_tag, T, ptrdiff_t, T *,
1100 T *> {
1101 using BaseT = typename memoryaccess_def_iterator_base::iterator_facade_base;
1102
1103public:
1104 memoryaccess_def_iterator_base(T *Start) : Access(Start) {}
1105 memoryaccess_def_iterator_base() = default;
1106
1107 bool operator==(const memoryaccess_def_iterator_base &Other) const {
1108 return Access == Other.Access && (!Access || ArgNo == Other.ArgNo);
1109 }
1110
1111 // This is a bit ugly, but for MemoryPHI's, unlike PHINodes, you can't get the
1112 // block from the operand in constant time (In a PHINode, the uselist has
1113 // both, so it's just subtraction). We provide it as part of the
1114 // iterator to avoid callers having to linear walk to get the block.
1115 // If the operation becomes constant time on MemoryPHI's, this bit of
1116 // abstraction breaking should be removed.
1117 BasicBlock *getPhiArgBlock() const {
1118 MemoryPhi *MP = dyn_cast<MemoryPhi>(Access);
1119 assert(MP && "Tried to get phi arg block when not iterating over a PHI")(static_cast <bool> (MP && "Tried to get phi arg block when not iterating over a PHI"
) ? void (0) : __assert_fail ("MP && \"Tried to get phi arg block when not iterating over a PHI\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 1119, __extension__ __PRETTY_FUNCTION__))
;
1120 return MP->getIncomingBlock(ArgNo);
1121 }
1122
1123 typename std::iterator_traits<BaseT>::pointer operator*() const {
1124 assert(Access && "Tried to access past the end of our iterator")(static_cast <bool> (Access && "Tried to access past the end of our iterator"
) ? void (0) : __assert_fail ("Access && \"Tried to access past the end of our iterator\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 1124, __extension__ __PRETTY_FUNCTION__))
;
1125 // Go to the first argument for phis, and the defining access for everything
1126 // else.
1127 if (const MemoryPhi *MP = dyn_cast<MemoryPhi>(Access))
1128 return MP->getIncomingValue(ArgNo);
1129 return cast<MemoryUseOrDef>(Access)->getDefiningAccess();
1130 }
1131
1132 using BaseT::operator++;
1133 memoryaccess_def_iterator_base &operator++() {
1134 assert(Access && "Hit end of iterator")(static_cast <bool> (Access && "Hit end of iterator"
) ? void (0) : __assert_fail ("Access && \"Hit end of iterator\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 1134, __extension__ __PRETTY_FUNCTION__))
;
1135 if (const MemoryPhi *MP = dyn_cast<MemoryPhi>(Access)) {
1136 if (++ArgNo >= MP->getNumIncomingValues()) {
1137 ArgNo = 0;
1138 Access = nullptr;
1139 }
1140 } else {
1141 Access = nullptr;
1142 }
1143 return *this;
1144 }
1145
1146private:
1147 T *Access = nullptr;
1148 unsigned ArgNo = 0;
1149};
1150
1151inline memoryaccess_def_iterator MemoryAccess::defs_begin() {
1152 return memoryaccess_def_iterator(this);
1153}
1154
1155inline const_memoryaccess_def_iterator MemoryAccess::defs_begin() const {
1156 return const_memoryaccess_def_iterator(this);
1157}
1158
1159inline memoryaccess_def_iterator MemoryAccess::defs_end() {
1160 return memoryaccess_def_iterator();
1161}
1162
1163inline const_memoryaccess_def_iterator MemoryAccess::defs_end() const {
1164 return const_memoryaccess_def_iterator();
1165}
1166
1167/// GraphTraits for a MemoryAccess, which walks defs in the normal case,
1168/// and uses in the inverse case.
1169template <> struct GraphTraits<MemoryAccess *> {
1170 using NodeRef = MemoryAccess *;
1171 using ChildIteratorType = memoryaccess_def_iterator;
1172
1173 static NodeRef getEntryNode(NodeRef N) { return N; }
1174 static ChildIteratorType child_begin(NodeRef N) { return N->defs_begin(); }
1175 static ChildIteratorType child_end(NodeRef N) { return N->defs_end(); }
1176};
1177
1178template <> struct GraphTraits<Inverse<MemoryAccess *>> {
1179 using NodeRef = MemoryAccess *;
1180 using ChildIteratorType = MemoryAccess::iterator;
1181
1182 static NodeRef getEntryNode(NodeRef N) { return N; }
1183 static ChildIteratorType child_begin(NodeRef N) { return N->user_begin(); }
1184 static ChildIteratorType child_end(NodeRef N) { return N->user_end(); }
1185};
1186
1187/// Provide an iterator that walks defs, giving both the memory access,
1188/// and the current pointer location, updating the pointer location as it
1189/// changes due to phi node translation.
1190///
1191/// This iterator, while somewhat specialized, is what most clients actually
1192/// want when walking upwards through MemorySSA def chains. It takes a pair of
1193/// <MemoryAccess,MemoryLocation>, and walks defs, properly translating the
1194/// memory location through phi nodes for the user.
1195class upward_defs_iterator
1196 : public iterator_facade_base<upward_defs_iterator,
1197 std::forward_iterator_tag,
1198 const MemoryAccessPair> {
1199 using BaseT = upward_defs_iterator::iterator_facade_base;
1200
1201public:
1202 upward_defs_iterator(const MemoryAccessPair &Info, DominatorTree *DT,
1203 bool *PerformedPhiTranslation = nullptr)
1204 : DefIterator(Info.first), Location(Info.second),
1205 OriginalAccess(Info.first), DT(DT),
1206 PerformedPhiTranslation(PerformedPhiTranslation) {
1207 CurrentPair.first = nullptr;
1208
1209 WalkingPhi = Info.first && isa<MemoryPhi>(Info.first);
1210 fillInCurrentPair();
1211 }
1212
1213 upward_defs_iterator() { CurrentPair.first = nullptr; }
1214
1215 bool operator==(const upward_defs_iterator &Other) const {
1216 return DefIterator == Other.DefIterator;
1217 }
1218
1219 typename std::iterator_traits<BaseT>::reference operator*() const {
1220 assert(DefIterator != OriginalAccess->defs_end() &&(static_cast <bool> (DefIterator != OriginalAccess->
defs_end() && "Tried to access past the end of our iterator"
) ? void (0) : __assert_fail ("DefIterator != OriginalAccess->defs_end() && \"Tried to access past the end of our iterator\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 1221, __extension__ __PRETTY_FUNCTION__))
1221 "Tried to access past the end of our iterator")(static_cast <bool> (DefIterator != OriginalAccess->
defs_end() && "Tried to access past the end of our iterator"
) ? void (0) : __assert_fail ("DefIterator != OriginalAccess->defs_end() && \"Tried to access past the end of our iterator\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 1221, __extension__ __PRETTY_FUNCTION__))
;
1222 return CurrentPair;
1223 }
1224
1225 using BaseT::operator++;
1226 upward_defs_iterator &operator++() {
1227 assert(DefIterator != OriginalAccess->defs_end() &&(static_cast <bool> (DefIterator != OriginalAccess->
defs_end() && "Tried to access past the end of the iterator"
) ? void (0) : __assert_fail ("DefIterator != OriginalAccess->defs_end() && \"Tried to access past the end of the iterator\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 1228, __extension__ __PRETTY_FUNCTION__))
1228 "Tried to access past the end of the iterator")(static_cast <bool> (DefIterator != OriginalAccess->
defs_end() && "Tried to access past the end of the iterator"
) ? void (0) : __assert_fail ("DefIterator != OriginalAccess->defs_end() && \"Tried to access past the end of the iterator\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 1228, __extension__ __PRETTY_FUNCTION__))
;
1229 ++DefIterator;
1230 if (DefIterator != OriginalAccess->defs_end())
1231 fillInCurrentPair();
1232 return *this;
1233 }
1234
1235 BasicBlock *getPhiArgBlock() const { return DefIterator.getPhiArgBlock(); }
1236
1237private:
1238 /// Returns true if \p Ptr is guaranteed to be loop invariant for any possible
1239 /// loop. In particular, this guarantees that it only references a single
1240 /// MemoryLocation during execution of the containing function.
1241 bool IsGuaranteedLoopInvariant(Value *Ptr) const;
1242
1243 void fillInCurrentPair() {
1244 CurrentPair.first = *DefIterator;
1245 CurrentPair.second = Location;
1246 if (WalkingPhi && Location.Ptr) {
1247 // Mark size as unknown, if the location is not guaranteed to be
1248 // loop-invariant for any possible loop in the function. Setting the size
1249 // to unknown guarantees that any memory accesses that access locations
1250 // after the pointer are considered as clobbers, which is important to
1251 // catch loop carried dependences.
1252 if (Location.Ptr &&
1253 !IsGuaranteedLoopInvariant(const_cast<Value *>(Location.Ptr)))
1254 CurrentPair.second =
1255 Location.getWithNewSize(LocationSize::beforeOrAfterPointer());
1256 PHITransAddr Translator(
1257 const_cast<Value *>(Location.Ptr),
1258 OriginalAccess->getBlock()->getModule()->getDataLayout(), nullptr);
1259
1260 if (!Translator.PHITranslateValue(OriginalAccess->getBlock(),
1261 DefIterator.getPhiArgBlock(), DT,
1262 true)) {
1263 Value *TransAddr = Translator.getAddr();
1264 if (TransAddr != Location.Ptr) {
1265 CurrentPair.second = CurrentPair.second.getWithNewPtr(TransAddr);
1266
1267 if (TransAddr &&
1268 !IsGuaranteedLoopInvariant(const_cast<Value *>(TransAddr)))
1269 CurrentPair.second = CurrentPair.second.getWithNewSize(
1270 LocationSize::beforeOrAfterPointer());
1271
1272 if (PerformedPhiTranslation)
1273 *PerformedPhiTranslation = true;
1274 }
1275 }
1276 }
1277 }
1278
1279 MemoryAccessPair CurrentPair;
1280 memoryaccess_def_iterator DefIterator;
1281 MemoryLocation Location;
1282 MemoryAccess *OriginalAccess = nullptr;
1283 DominatorTree *DT = nullptr;
1284 bool WalkingPhi = false;
1285 bool *PerformedPhiTranslation = nullptr;
1286};
1287
1288inline upward_defs_iterator
1289upward_defs_begin(const MemoryAccessPair &Pair, DominatorTree &DT,
1290 bool *PerformedPhiTranslation = nullptr) {
1291 return upward_defs_iterator(Pair, &DT, PerformedPhiTranslation);
1292}
1293
1294inline upward_defs_iterator upward_defs_end() { return upward_defs_iterator(); }
1295
1296inline iterator_range<upward_defs_iterator>
1297upward_defs(const MemoryAccessPair &Pair, DominatorTree &DT) {
1298 return make_range(upward_defs_begin(Pair, DT), upward_defs_end());
1299}
1300
1301/// Walks the defining accesses of MemoryDefs. Stops after we hit something that
1302/// has no defining use (e.g. a MemoryPhi or liveOnEntry). Note that, when
1303/// comparing against a null def_chain_iterator, this will compare equal only
1304/// after walking said Phi/liveOnEntry.
1305///
1306/// The UseOptimizedChain flag specifies whether to walk the clobbering
1307/// access chain, or all the accesses.
1308///
1309/// Normally, MemoryDef are all just def/use linked together, so a def_chain on
1310/// a MemoryDef will walk all MemoryDefs above it in the program until it hits
1311/// a phi node. The optimized chain walks the clobbering access of a store.
1312/// So if you are just trying to find, given a store, what the next
1313/// thing that would clobber the same memory is, you want the optimized chain.
1314template <class T, bool UseOptimizedChain = false>
1315struct def_chain_iterator
1316 : public iterator_facade_base<def_chain_iterator<T, UseOptimizedChain>,
1317 std::forward_iterator_tag, MemoryAccess *> {
1318 def_chain_iterator() : MA(nullptr) {}
1319 def_chain_iterator(T MA) : MA(MA) {}
1320
1321 T operator*() const { return MA; }
1322
1323 def_chain_iterator &operator++() {
1324 // N.B. liveOnEntry has a null defining access.
1325 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
1326 if (UseOptimizedChain && MUD->isOptimized())
1327 MA = MUD->getOptimized();
1328 else
1329 MA = MUD->getDefiningAccess();
1330 } else {
1331 MA = nullptr;
1332 }
1333
1334 return *this;
1335 }
1336
1337 bool operator==(const def_chain_iterator &O) const { return MA == O.MA; }
1338
1339private:
1340 T MA;
1341};
1342
1343template <class T>
1344inline iterator_range<def_chain_iterator<T>>
1345def_chain(T MA, MemoryAccess *UpTo = nullptr) {
1346#ifdef EXPENSIVE_CHECKS
1347 assert((!UpTo || find(def_chain(MA), UpTo) != def_chain_iterator<T>()) &&(static_cast <bool> ((!UpTo || find(def_chain(MA), UpTo
) != def_chain_iterator<T>()) && "UpTo isn't in the def chain!"
) ? void (0) : __assert_fail ("(!UpTo || find(def_chain(MA), UpTo) != def_chain_iterator<T>()) && \"UpTo isn't in the def chain!\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 1348, __extension__ __PRETTY_FUNCTION__))
1348 "UpTo isn't in the def chain!")(static_cast <bool> ((!UpTo || find(def_chain(MA), UpTo
) != def_chain_iterator<T>()) && "UpTo isn't in the def chain!"
) ? void (0) : __assert_fail ("(!UpTo || find(def_chain(MA), UpTo) != def_chain_iterator<T>()) && \"UpTo isn't in the def chain!\""
, "/build/llvm-toolchain-snapshot-14~++20211016100712+8e1d532707fd/llvm/include/llvm/Analysis/MemorySSA.h"
, 1348, __extension__ __PRETTY_FUNCTION__))
;
1349#endif
1350 return make_range(def_chain_iterator<T>(MA), def_chain_iterator<T>(UpTo));
1351}
1352
1353template <class T>
1354inline iterator_range<def_chain_iterator<T, true>> optimized_def_chain(T MA) {
1355 return make_range(def_chain_iterator<T, true>(MA),
1356 def_chain_iterator<T, true>(nullptr));
1357}
1358
1359} // end namespace llvm
1360
1361#endif // LLVM_ANALYSIS_MEMORYSSA_H