Bug Summary

File:build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/lib/Analysis/MemorySSA.cpp
Warning:line 2037, 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-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 -ffp-contract=on -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-16~++20220904122748+c444af1c20b3/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.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-16~++20220904122748+c444af1c20b3/llvm/lib/Analysis -I include -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/include -D _FORTIFY_SOURCE=2 -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-16/lib/clang/16.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 -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -O3 -Wno-unused-command-line-argument -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 -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -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-2022-09-04-125545-48738-1 -x c++ /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/lib/Analysis/MemorySSA.cpp

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

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