Bug Summary

File: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 -disable-llvm-verifier -discard-value-names -main-file-name MemorySSA.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/build-llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/build-llvm/lib/Analysis -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2021-01-16-002530-32805-1 -x c++ /build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/llvm/lib/Analysis/MemorySSA.cpp

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

/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/llvm/include/llvm/Analysis/MemorySSA.h

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