Bug Summary

File:lib/Transforms/Utils/MemorySSA.cpp
Warning:line 1297, column 5
Value stored to 'Walker' is never read

Annotated Source Code

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