blob: 5130c21cde9055edc9f1581e5ce576d15266e99f [file] [log] [blame]
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001//===- MemorySSA.cpp - Memory SSA Builder ---------------------------------===//
George Burgess IVe1100f52016-02-02 22:46:49 +00002//
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//
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00008//===----------------------------------------------------------------------===//
George Burgess IVe1100f52016-02-02 22:46:49 +00009//
10// This file implements the MemorySSA class.
11//
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000012//===----------------------------------------------------------------------===//
13
Daniel Berlin554dcd82017-04-11 20:06:36 +000014#include "llvm/Analysis/MemorySSA.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000015#include "llvm/ADT/DenseMap.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000016#include "llvm/ADT/DenseMapInfo.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000017#include "llvm/ADT/DenseSet.h"
18#include "llvm/ADT/DepthFirstIterator.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000019#include "llvm/ADT/Hashing.h"
20#include "llvm/ADT/None.h"
21#include "llvm/ADT/Optional.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000022#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000024#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/iterator.h"
26#include "llvm/ADT/iterator_range.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000027#include "llvm/Analysis/AliasAnalysis.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000028#include "llvm/Analysis/IteratedDominanceFrontier.h"
29#include "llvm/Analysis/MemoryLocation.h"
Nico Weber432a3882018-04-30 14:59:11 +000030#include "llvm/Config/llvm-config.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000031#include "llvm/IR/AssemblyAnnotationWriter.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000032#include "llvm/IR/BasicBlock.h"
33#include "llvm/IR/CallSite.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000034#include "llvm/IR/Dominators.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000035#include "llvm/IR/Function.h"
36#include "llvm/IR/Instruction.h"
37#include "llvm/IR/Instructions.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000038#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000039#include "llvm/IR/Intrinsics.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000040#include "llvm/IR/LLVMContext.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000041#include "llvm/IR/PassManager.h"
42#include "llvm/IR/Use.h"
43#include "llvm/Pass.h"
44#include "llvm/Support/AtomicOrdering.h"
45#include "llvm/Support/Casting.h"
46#include "llvm/Support/CommandLine.h"
47#include "llvm/Support/Compiler.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000048#include "llvm/Support/Debug.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000049#include "llvm/Support/ErrorHandling.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000050#include "llvm/Support/FormattedStream.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000051#include "llvm/Support/raw_ostream.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000052#include <algorithm>
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000053#include <cassert>
54#include <iterator>
55#include <memory>
56#include <utility>
57
58using namespace llvm;
George Burgess IVe1100f52016-02-02 22:46:49 +000059
60#define DEBUG_TYPE "memoryssa"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000061
Geoff Berryefb0dd12016-06-14 21:19:40 +000062INITIALIZE_PASS_BEGIN(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
Geoff Berryb96d3b22016-06-01 21:30:40 +000063 true)
George Burgess IVe1100f52016-02-02 22:46:49 +000064INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
65INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Geoff Berryefb0dd12016-06-14 21:19:40 +000066INITIALIZE_PASS_END(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
67 true)
George Burgess IVe1100f52016-02-02 22:46:49 +000068
Chad Rosier232e29e2016-07-06 21:20:47 +000069INITIALIZE_PASS_BEGIN(MemorySSAPrinterLegacyPass, "print-memoryssa",
70 "Memory SSA Printer", false, false)
71INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
72INITIALIZE_PASS_END(MemorySSAPrinterLegacyPass, "print-memoryssa",
73 "Memory SSA Printer", false, false)
74
Daniel Berlinc43aa5a2016-08-02 16:24:03 +000075static cl::opt<unsigned> MaxCheckLimit(
76 "memssa-check-limit", cl::Hidden, cl::init(100),
77 cl::desc("The maximum number of stores/phis MemorySSA"
78 "will consider trying to walk past (default = 100)"));
79
Chad Rosier232e29e2016-07-06 21:20:47 +000080static cl::opt<bool>
81 VerifyMemorySSA("verify-memoryssa", cl::init(false), cl::Hidden,
82 cl::desc("Verify MemorySSA in legacy printer pass."));
83
George Burgess IVe1100f52016-02-02 22:46:49 +000084namespace llvm {
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000085
George Burgess IVe1100f52016-02-02 22:46:49 +000086/// \brief An assembly annotator class to print Memory SSA information in
87/// comments.
88class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter {
89 friend class MemorySSA;
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000090
George Burgess IVe1100f52016-02-02 22:46:49 +000091 const MemorySSA *MSSA;
92
93public:
94 MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {}
95
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000096 void emitBasicBlockStartAnnot(const BasicBlock *BB,
97 formatted_raw_ostream &OS) override {
George Burgess IVe1100f52016-02-02 22:46:49 +000098 if (MemoryAccess *MA = MSSA->getMemoryAccess(BB))
99 OS << "; " << *MA << "\n";
100 }
101
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000102 void emitInstructionAnnot(const Instruction *I,
103 formatted_raw_ostream &OS) override {
George Burgess IVe1100f52016-02-02 22:46:49 +0000104 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
105 OS << "; " << *MA << "\n";
106 }
107};
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000108
109} // end namespace llvm
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000110
George Burgess IV5f308972016-07-19 01:29:15 +0000111namespace {
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000112
Daniel Berlindff31de2016-08-02 21:57:52 +0000113/// Our current alias analysis API differentiates heavily between calls and
114/// non-calls, and functions called on one usually assert on the other.
115/// This class encapsulates the distinction to simplify other code that wants
116/// "Memory affecting instructions and related data" to use as a key.
117/// For example, this class is used as a densemap key in the use optimizer.
118class MemoryLocOrCall {
119public:
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000120 bool IsCall = false;
121
122 MemoryLocOrCall() = default;
Daniel Berlindff31de2016-08-02 21:57:52 +0000123 MemoryLocOrCall(MemoryUseOrDef *MUD)
124 : MemoryLocOrCall(MUD->getMemoryInst()) {}
Sebastian Pop5068d7a2016-10-13 03:23:33 +0000125 MemoryLocOrCall(const MemoryUseOrDef *MUD)
126 : MemoryLocOrCall(MUD->getMemoryInst()) {}
Daniel Berlindff31de2016-08-02 21:57:52 +0000127
128 MemoryLocOrCall(Instruction *Inst) {
129 if (ImmutableCallSite(Inst)) {
130 IsCall = true;
131 CS = ImmutableCallSite(Inst);
132 } else {
133 IsCall = false;
134 // There is no such thing as a memorylocation for a fence inst, and it is
135 // unique in that regard.
136 if (!isa<FenceInst>(Inst))
137 Loc = MemoryLocation::get(Inst);
138 }
139 }
140
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000141 explicit MemoryLocOrCall(const MemoryLocation &Loc) : Loc(Loc) {}
Daniel Berlindff31de2016-08-02 21:57:52 +0000142
Daniel Berlindff31de2016-08-02 21:57:52 +0000143 ImmutableCallSite getCS() const {
144 assert(IsCall);
145 return CS;
146 }
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000147
Daniel Berlindff31de2016-08-02 21:57:52 +0000148 MemoryLocation getLoc() const {
149 assert(!IsCall);
150 return Loc;
151 }
152
153 bool operator==(const MemoryLocOrCall &Other) const {
154 if (IsCall != Other.IsCall)
155 return false;
156
George Burgess IV3588fd42018-03-29 00:54:39 +0000157 if (!IsCall)
158 return Loc == Other.Loc;
159
160 if (CS.getCalledValue() != Other.CS.getCalledValue())
161 return false;
162
George Burgess IVaf0b06f2018-03-29 03:12:03 +0000163 return CS.arg_size() == Other.CS.arg_size() &&
164 std::equal(CS.arg_begin(), CS.arg_end(), Other.CS.arg_begin());
Daniel Berlindff31de2016-08-02 21:57:52 +0000165 }
166
167private:
Daniel Berlinf5361132016-10-22 04:15:41 +0000168 union {
Daniel Berlind602e042017-01-25 20:56:19 +0000169 ImmutableCallSite CS;
170 MemoryLocation Loc;
Daniel Berlinf5361132016-10-22 04:15:41 +0000171 };
Daniel Berlindff31de2016-08-02 21:57:52 +0000172};
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000173
174} // end anonymous namespace
Daniel Berlindff31de2016-08-02 21:57:52 +0000175
176namespace llvm {
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000177
Daniel Berlindff31de2016-08-02 21:57:52 +0000178template <> struct DenseMapInfo<MemoryLocOrCall> {
179 static inline MemoryLocOrCall getEmptyKey() {
180 return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getEmptyKey());
181 }
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000182
Daniel Berlindff31de2016-08-02 21:57:52 +0000183 static inline MemoryLocOrCall getTombstoneKey() {
184 return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getTombstoneKey());
185 }
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000186
Daniel Berlindff31de2016-08-02 21:57:52 +0000187 static unsigned getHashValue(const MemoryLocOrCall &MLOC) {
George Burgess IV3588fd42018-03-29 00:54:39 +0000188 if (!MLOC.IsCall)
189 return hash_combine(
190 MLOC.IsCall,
191 DenseMapInfo<MemoryLocation>::getHashValue(MLOC.getLoc()));
192
193 hash_code hash =
194 hash_combine(MLOC.IsCall, DenseMapInfo<const Value *>::getHashValue(
195 MLOC.getCS().getCalledValue()));
196
197 for (const Value *Arg : MLOC.getCS().args())
198 hash = hash_combine(hash, DenseMapInfo<const Value *>::getHashValue(Arg));
199 return hash;
Daniel Berlindff31de2016-08-02 21:57:52 +0000200 }
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000201
Daniel Berlindff31de2016-08-02 21:57:52 +0000202 static bool isEqual(const MemoryLocOrCall &LHS, const MemoryLocOrCall &RHS) {
203 return LHS == RHS;
204 }
205};
Daniel Berlindf101192016-08-03 00:01:46 +0000206
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000207} // end namespace llvm
208
George Burgess IV82e355c2016-08-03 19:39:54 +0000209/// This does one-way checks to see if Use could theoretically be hoisted above
210/// MayClobber. This will not check the other way around.
211///
212/// This assumes that, for the purposes of MemorySSA, Use comes directly after
213/// MayClobber, with no potentially clobbering operations in between them.
214/// (Where potentially clobbering ops are memory barriers, aliased stores, etc.)
Alina Sbirleaca741a82017-12-22 19:54:03 +0000215static bool areLoadsReorderable(const LoadInst *Use,
216 const LoadInst *MayClobber) {
George Burgess IV82e355c2016-08-03 19:39:54 +0000217 bool VolatileUse = Use->isVolatile();
218 bool VolatileClobber = MayClobber->isVolatile();
219 // Volatile operations may never be reordered with other volatile operations.
220 if (VolatileUse && VolatileClobber)
Alina Sbirleaca741a82017-12-22 19:54:03 +0000221 return false;
222 // Otherwise, volatile doesn't matter here. From the language reference:
223 // 'optimizers may change the order of volatile operations relative to
224 // non-volatile operations.'"
George Burgess IV82e355c2016-08-03 19:39:54 +0000225
226 // If a load is seq_cst, it cannot be moved above other loads. If its ordering
227 // is weaker, it can be moved above other loads. We just need to be sure that
228 // MayClobber isn't an acquire load, because loads can't be moved above
229 // acquire loads.
230 //
231 // Note that this explicitly *does* allow the free reordering of monotonic (or
232 // weaker) loads of the same address.
233 bool SeqCstUse = Use->getOrdering() == AtomicOrdering::SequentiallyConsistent;
234 bool MayClobberIsAcquire = isAtLeastOrStrongerThan(MayClobber->getOrdering(),
235 AtomicOrdering::Acquire);
Alina Sbirleaca741a82017-12-22 19:54:03 +0000236 return !(SeqCstUse || MayClobberIsAcquire);
George Burgess IV82e355c2016-08-03 19:39:54 +0000237}
238
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000239namespace {
240
241struct ClobberAlias {
242 bool IsClobber;
243 Optional<AliasResult> AR;
244};
245
246} // end anonymous namespace
247
248// Return a pair of {IsClobber (bool), AR (AliasResult)}. It relies on AR being
249// ignored if IsClobber = false.
250static ClobberAlias instructionClobbersQuery(MemoryDef *MD,
251 const MemoryLocation &UseLoc,
252 const Instruction *UseInst,
253 AliasAnalysis &AA) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000254 Instruction *DefInst = MD->getMemoryInst();
255 assert(DefInst && "Defining instruction not actually an instruction");
Daniel Berlin74603a62017-04-10 18:46:00 +0000256 ImmutableCallSite UseCS(UseInst);
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000257 Optional<AliasResult> AR;
George Burgess IV5f308972016-07-19 01:29:15 +0000258
Daniel Berlindf101192016-08-03 00:01:46 +0000259 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) {
260 // These intrinsics will show up as affecting memory, but they are just
261 // markers.
262 switch (II->getIntrinsicID()) {
263 case Intrinsic::lifetime_start:
Daniel Berlin74603a62017-04-10 18:46:00 +0000264 if (UseCS)
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000265 return {false, NoAlias};
266 AR = AA.alias(MemoryLocation(II->getArgOperand(1)), UseLoc);
267 return {AR == MustAlias, AR};
Daniel Berlindf101192016-08-03 00:01:46 +0000268 case Intrinsic::lifetime_end:
269 case Intrinsic::invariant_start:
270 case Intrinsic::invariant_end:
271 case Intrinsic::assume:
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000272 return {false, NoAlias};
Daniel Berlindf101192016-08-03 00:01:46 +0000273 default:
274 break;
275 }
276 }
277
Hans Wennborg70e22d12017-11-21 18:00:01 +0000278 if (UseCS) {
Daniel Berlindff31de2016-08-02 21:57:52 +0000279 ModRefInfo I = AA.getModRefInfo(DefInst, UseCS);
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000280 AR = isMustSet(I) ? MustAlias : MayAlias;
281 return {isModOrRefSet(I), AR};
Hans Wennborg70e22d12017-11-21 18:00:01 +0000282 }
George Burgess IV82e355c2016-08-03 19:39:54 +0000283
Alina Sbirleaca741a82017-12-22 19:54:03 +0000284 if (auto *DefLoad = dyn_cast<LoadInst>(DefInst))
285 if (auto *UseLoad = dyn_cast<LoadInst>(UseInst))
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000286 return {!areLoadsReorderable(UseLoad, DefLoad), MayAlias};
George Burgess IV82e355c2016-08-03 19:39:54 +0000287
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000288 ModRefInfo I = AA.getModRefInfo(DefInst, UseLoc);
289 AR = isMustSet(I) ? MustAlias : MayAlias;
290 return {isModSet(I), AR};
Daniel Berlindff31de2016-08-02 21:57:52 +0000291}
292
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000293static ClobberAlias instructionClobbersQuery(MemoryDef *MD,
294 const MemoryUseOrDef *MU,
295 const MemoryLocOrCall &UseMLOC,
296 AliasAnalysis &AA) {
Sebastian Pop5068d7a2016-10-13 03:23:33 +0000297 // FIXME: This is a temporary hack to allow a single instructionClobbersQuery
298 // to exist while MemoryLocOrCall is pushed through places.
299 if (UseMLOC.IsCall)
300 return instructionClobbersQuery(MD, MemoryLocation(), MU->getMemoryInst(),
301 AA);
302 return instructionClobbersQuery(MD, UseMLOC.getLoc(), MU->getMemoryInst(),
303 AA);
304}
305
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000306// Return true when MD may alias MU, return false otherwise.
Daniel Berlindcb004f2017-03-02 23:06:46 +0000307bool MemorySSAUtil::defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU,
308 AliasAnalysis &AA) {
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000309 return instructionClobbersQuery(MD, MU, MemoryLocOrCall(MU), AA).IsClobber;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000310}
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000311
312namespace {
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000313
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000314struct UpwardsMemoryQuery {
315 // True if our original query started off as a call
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000316 bool IsCall = false;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000317 // The pointer location we started the query with. This will be empty if
318 // IsCall is true.
319 MemoryLocation StartingLoc;
320 // This is the instruction we were querying about.
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000321 const Instruction *Inst = nullptr;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000322 // The MemoryAccess we actually got called with, used to test local domination
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000323 const MemoryAccess *OriginalAccess = nullptr;
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000324 Optional<AliasResult> AR = MayAlias;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000325
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000326 UpwardsMemoryQuery() = default;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000327
328 UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access)
329 : IsCall(ImmutableCallSite(Inst)), Inst(Inst), OriginalAccess(Access) {
330 if (!IsCall)
331 StartingLoc = MemoryLocation::get(Inst);
332 }
333};
334
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000335} // end anonymous namespace
336
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000337static bool lifetimeEndsAt(MemoryDef *MD, const MemoryLocation &Loc,
338 AliasAnalysis &AA) {
339 Instruction *Inst = MD->getMemoryInst();
340 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
341 switch (II->getIntrinsicID()) {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000342 case Intrinsic::lifetime_end:
343 return AA.isMustAlias(MemoryLocation(II->getArgOperand(1)), Loc);
344 default:
345 return false;
346 }
347 }
348 return false;
349}
350
351static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysis &AA,
352 const Instruction *I) {
353 // If the memory can't be changed, then loads of the memory can't be
354 // clobbered.
355 //
356 // FIXME: We should handle invariant groups, as well. It's a bit harder,
357 // because we need to pay close attention to invariant group barriers.
358 return isa<LoadInst>(I) && (I->getMetadata(LLVMContext::MD_invariant_load) ||
Hal Finkela9d67cf2017-04-09 12:57:50 +0000359 AA.pointsToConstantMemory(cast<LoadInst>(I)->
360 getPointerOperand()));
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000361}
362
George Burgess IV5f308972016-07-19 01:29:15 +0000363/// Verifies that `Start` is clobbered by `ClobberAt`, and that nothing
364/// inbetween `Start` and `ClobberAt` can clobbers `Start`.
365///
366/// This is meant to be as simple and self-contained as possible. Because it
367/// uses no cache, etc., it can be relatively expensive.
368///
369/// \param Start The MemoryAccess that we want to walk from.
370/// \param ClobberAt A clobber for Start.
371/// \param StartLoc The MemoryLocation for Start.
372/// \param MSSA The MemorySSA isntance that Start and ClobberAt belong to.
373/// \param Query The UpwardsMemoryQuery we used for our search.
374/// \param AA The AliasAnalysis we used for our search.
375static void LLVM_ATTRIBUTE_UNUSED
376checkClobberSanity(MemoryAccess *Start, MemoryAccess *ClobberAt,
377 const MemoryLocation &StartLoc, const MemorySSA &MSSA,
378 const UpwardsMemoryQuery &Query, AliasAnalysis &AA) {
379 assert(MSSA.dominates(ClobberAt, Start) && "Clobber doesn't dominate start?");
380
381 if (MSSA.isLiveOnEntryDef(Start)) {
382 assert(MSSA.isLiveOnEntryDef(ClobberAt) &&
383 "liveOnEntry must clobber itself");
384 return;
385 }
386
George Burgess IV5f308972016-07-19 01:29:15 +0000387 bool FoundClobber = false;
388 DenseSet<MemoryAccessPair> VisitedPhis;
389 SmallVector<MemoryAccessPair, 8> Worklist;
390 Worklist.emplace_back(Start, StartLoc);
391 // Walk all paths from Start to ClobberAt, while looking for clobbers. If one
392 // is found, complain.
393 while (!Worklist.empty()) {
394 MemoryAccessPair MAP = Worklist.pop_back_val();
395 // All we care about is that nothing from Start to ClobberAt clobbers Start.
396 // We learn nothing from revisiting nodes.
397 if (!VisitedPhis.insert(MAP).second)
398 continue;
399
400 for (MemoryAccess *MA : def_chain(MAP.first)) {
401 if (MA == ClobberAt) {
402 if (auto *MD = dyn_cast<MemoryDef>(MA)) {
403 // instructionClobbersQuery isn't essentially free, so don't use `|=`,
404 // since it won't let us short-circuit.
405 //
406 // Also, note that this can't be hoisted out of the `Worklist` loop,
407 // since MD may only act as a clobber for 1 of N MemoryLocations.
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000408 FoundClobber = FoundClobber || MSSA.isLiveOnEntryDef(MD);
409 if (!FoundClobber) {
410 ClobberAlias CA =
411 instructionClobbersQuery(MD, MAP.second, Query.Inst, AA);
412 if (CA.IsClobber) {
413 FoundClobber = true;
414 // Not used: CA.AR;
415 }
416 }
George Burgess IV5f308972016-07-19 01:29:15 +0000417 }
418 break;
419 }
420
421 // We should never hit liveOnEntry, unless it's the clobber.
422 assert(!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?");
423
424 if (auto *MD = dyn_cast<MemoryDef>(MA)) {
425 (void)MD;
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000426 assert(!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA)
427 .IsClobber &&
George Burgess IV5f308972016-07-19 01:29:15 +0000428 "Found clobber before reaching ClobberAt!");
429 continue;
430 }
431
432 assert(isa<MemoryPhi>(MA));
433 Worklist.append(upward_defs_begin({MA, MAP.second}), upward_defs_end());
434 }
435 }
436
437 // If ClobberAt is a MemoryPhi, we can assume something above it acted as a
438 // clobber. Otherwise, `ClobberAt` should've acted as a clobber at some point.
439 assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&
440 "ClobberAt never acted as a clobber");
441}
442
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000443namespace {
444
George Burgess IV5f308972016-07-19 01:29:15 +0000445/// Our algorithm for walking (and trying to optimize) clobbers, all wrapped up
446/// in one class.
447class ClobberWalker {
448 /// Save a few bytes by using unsigned instead of size_t.
449 using ListIndex = unsigned;
450
451 /// Represents a span of contiguous MemoryDefs, potentially ending in a
452 /// MemoryPhi.
453 struct DefPath {
454 MemoryLocation Loc;
455 // Note that, because we always walk in reverse, Last will always dominate
456 // First. Also note that First and Last are inclusive.
457 MemoryAccess *First;
458 MemoryAccess *Last;
George Burgess IV5f308972016-07-19 01:29:15 +0000459 Optional<ListIndex> Previous;
460
461 DefPath(const MemoryLocation &Loc, MemoryAccess *First, MemoryAccess *Last,
462 Optional<ListIndex> Previous)
463 : Loc(Loc), First(First), Last(Last), Previous(Previous) {}
464
465 DefPath(const MemoryLocation &Loc, MemoryAccess *Init,
466 Optional<ListIndex> Previous)
467 : DefPath(Loc, Init, Init, Previous) {}
468 };
469
470 const MemorySSA &MSSA;
471 AliasAnalysis &AA;
472 DominatorTree &DT;
George Burgess IV5f308972016-07-19 01:29:15 +0000473 UpwardsMemoryQuery *Query;
George Burgess IV5f308972016-07-19 01:29:15 +0000474
475 // Phi optimization bookkeeping
476 SmallVector<DefPath, 32> Paths;
477 DenseSet<ConstMemoryAccessPair> VisitedPhis;
George Burgess IV5f308972016-07-19 01:29:15 +0000478
George Burgess IV5f308972016-07-19 01:29:15 +0000479 /// Find the nearest def or phi that `From` can legally be optimized to.
Daniel Berlind0420312017-04-01 09:01:12 +0000480 const MemoryAccess *getWalkTarget(const MemoryPhi *From) const {
George Burgess IV5f308972016-07-19 01:29:15 +0000481 assert(From->getNumOperands() && "Phi with no operands?");
482
483 BasicBlock *BB = From->getBlock();
George Burgess IV5f308972016-07-19 01:29:15 +0000484 MemoryAccess *Result = MSSA.getLiveOnEntryDef();
485 DomTreeNode *Node = DT.getNode(BB);
486 while ((Node = Node->getIDom())) {
Daniel Berlin7500c562017-04-01 08:59:45 +0000487 auto *Defs = MSSA.getBlockDefs(Node->getBlock());
488 if (Defs)
Daniel Berlind0420312017-04-01 09:01:12 +0000489 return &*Defs->rbegin();
George Burgess IV5f308972016-07-19 01:29:15 +0000490 }
George Burgess IV5f308972016-07-19 01:29:15 +0000491 return Result;
492 }
493
494 /// Result of calling walkToPhiOrClobber.
495 struct UpwardsWalkResult {
496 /// The "Result" of the walk. Either a clobber, the last thing we walked, or
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000497 /// both. Include alias info when clobber found.
George Burgess IV5f308972016-07-19 01:29:15 +0000498 MemoryAccess *Result;
499 bool IsKnownClobber;
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000500 Optional<AliasResult> AR;
George Burgess IV5f308972016-07-19 01:29:15 +0000501 };
502
503 /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last.
504 /// This will update Desc.Last as it walks. It will (optionally) also stop at
505 /// StopAt.
506 ///
507 /// This does not test for whether StopAt is a clobber
Daniel Berlind0420312017-04-01 09:01:12 +0000508 UpwardsWalkResult
509 walkToPhiOrClobber(DefPath &Desc,
510 const MemoryAccess *StopAt = nullptr) const {
George Burgess IV5f308972016-07-19 01:29:15 +0000511 assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");
512
513 for (MemoryAccess *Current : def_chain(Desc.Last)) {
514 Desc.Last = Current;
515 if (Current == StopAt)
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000516 return {Current, false, MayAlias};
George Burgess IV5f308972016-07-19 01:29:15 +0000517
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000518 if (auto *MD = dyn_cast<MemoryDef>(Current)) {
519 if (MSSA.isLiveOnEntryDef(MD))
520 return {MD, true, MustAlias};
521 ClobberAlias CA =
522 instructionClobbersQuery(MD, Desc.Loc, Query->Inst, AA);
523 if (CA.IsClobber)
524 return {MD, true, CA.AR};
525 }
George Burgess IV5f308972016-07-19 01:29:15 +0000526 }
527
528 assert(isa<MemoryPhi>(Desc.Last) &&
529 "Ended at a non-clobber that's not a phi?");
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000530 return {Desc.Last, false, MayAlias};
George Burgess IV5f308972016-07-19 01:29:15 +0000531 }
532
533 void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches,
534 ListIndex PriorNode) {
535 auto UpwardDefs = make_range(upward_defs_begin({Phi, Paths[PriorNode].Loc}),
536 upward_defs_end());
537 for (const MemoryAccessPair &P : UpwardDefs) {
538 PausedSearches.push_back(Paths.size());
539 Paths.emplace_back(P.second, P.first, PriorNode);
540 }
541 }
542
543 /// Represents a search that terminated after finding a clobber. This clobber
544 /// may or may not be present in the path of defs from LastNode..SearchStart,
545 /// since it may have been retrieved from cache.
546 struct TerminatedPath {
547 MemoryAccess *Clobber;
548 ListIndex LastNode;
549 };
550
551 /// Get an access that keeps us from optimizing to the given phi.
552 ///
553 /// PausedSearches is an array of indices into the Paths array. Its incoming
554 /// value is the indices of searches that stopped at the last phi optimization
555 /// target. It's left in an unspecified state.
556 ///
557 /// If this returns None, NewPaused is a vector of searches that terminated
558 /// at StopWhere. Otherwise, NewPaused is left in an unspecified state.
George Burgess IV14633b52016-08-03 01:22:19 +0000559 Optional<TerminatedPath>
Daniel Berlind0420312017-04-01 09:01:12 +0000560 getBlockingAccess(const MemoryAccess *StopWhere,
George Burgess IV5f308972016-07-19 01:29:15 +0000561 SmallVectorImpl<ListIndex> &PausedSearches,
562 SmallVectorImpl<ListIndex> &NewPaused,
563 SmallVectorImpl<TerminatedPath> &Terminated) {
564 assert(!PausedSearches.empty() && "No searches to continue?");
565
566 // BFS vs DFS really doesn't make a difference here, so just do a DFS with
567 // PausedSearches as our stack.
568 while (!PausedSearches.empty()) {
569 ListIndex PathIndex = PausedSearches.pop_back_val();
570 DefPath &Node = Paths[PathIndex];
571
572 // If we've already visited this path with this MemoryLocation, we don't
573 // need to do so again.
574 //
575 // NOTE: That we just drop these paths on the ground makes caching
576 // behavior sporadic. e.g. given a diamond:
577 // A
578 // B C
579 // D
580 //
581 // ...If we walk D, B, A, C, we'll only cache the result of phi
582 // optimization for A, B, and D; C will be skipped because it dies here.
583 // This arguably isn't the worst thing ever, since:
584 // - We generally query things in a top-down order, so if we got below D
585 // without needing cache entries for {C, MemLoc}, then chances are
586 // that those cache entries would end up ultimately unused.
587 // - We still cache things for A, so C only needs to walk up a bit.
588 // If this behavior becomes problematic, we can fix without a ton of extra
589 // work.
590 if (!VisitedPhis.insert({Node.Last, Node.Loc}).second)
591 continue;
592
593 UpwardsWalkResult Res = walkToPhiOrClobber(Node, /*StopAt=*/StopWhere);
594 if (Res.IsKnownClobber) {
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000595 assert(Res.Result != StopWhere);
George Burgess IV5f308972016-07-19 01:29:15 +0000596 // If this wasn't a cache hit, we hit a clobber when walking. That's a
597 // failure.
George Burgess IV14633b52016-08-03 01:22:19 +0000598 TerminatedPath Term{Res.Result, PathIndex};
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000599 if (!MSSA.dominates(Res.Result, StopWhere))
George Burgess IV14633b52016-08-03 01:22:19 +0000600 return Term;
George Burgess IV5f308972016-07-19 01:29:15 +0000601
602 // Otherwise, it's a valid thing to potentially optimize to.
George Burgess IV14633b52016-08-03 01:22:19 +0000603 Terminated.push_back(Term);
George Burgess IV5f308972016-07-19 01:29:15 +0000604 continue;
605 }
606
607 if (Res.Result == StopWhere) {
608 // We've hit our target. Save this path off for if we want to continue
609 // walking.
610 NewPaused.push_back(PathIndex);
611 continue;
612 }
613
614 assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");
615 addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
616 }
617
618 return None;
619 }
620
621 template <typename T, typename Walker>
622 struct generic_def_path_iterator
623 : public iterator_facade_base<generic_def_path_iterator<T, Walker>,
624 std::forward_iterator_tag, T *> {
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000625 generic_def_path_iterator() = default;
George Burgess IV5f308972016-07-19 01:29:15 +0000626 generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}
627
628 T &operator*() const { return curNode(); }
629
630 generic_def_path_iterator &operator++() {
631 N = curNode().Previous;
632 return *this;
633 }
634
635 bool operator==(const generic_def_path_iterator &O) const {
636 if (N.hasValue() != O.N.hasValue())
637 return false;
638 return !N.hasValue() || *N == *O.N;
639 }
640
641 private:
642 T &curNode() const { return W->Paths[*N]; }
643
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000644 Walker *W = nullptr;
645 Optional<ListIndex> N = None;
George Burgess IV5f308972016-07-19 01:29:15 +0000646 };
647
648 using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
649 using const_def_path_iterator =
650 generic_def_path_iterator<const DefPath, const ClobberWalker>;
651
652 iterator_range<def_path_iterator> def_path(ListIndex From) {
653 return make_range(def_path_iterator(this, From), def_path_iterator());
654 }
655
656 iterator_range<const_def_path_iterator> const_def_path(ListIndex From) const {
657 return make_range(const_def_path_iterator(this, From),
658 const_def_path_iterator());
659 }
660
661 struct OptznResult {
662 /// The path that contains our result.
663 TerminatedPath PrimaryClobber;
664 /// The paths that we can legally cache back from, but that aren't
665 /// necessarily the result of the Phi optimization.
666 SmallVector<TerminatedPath, 4> OtherClobbers;
667 };
668
669 ListIndex defPathIndex(const DefPath &N) const {
670 // The assert looks nicer if we don't need to do &N
671 const DefPath *NP = &N;
672 assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
673 "Out of bounds DefPath!");
674 return NP - &Paths.front();
675 }
676
677 /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths
678 /// that act as legal clobbers. Note that this won't return *all* clobbers.
679 ///
680 /// Phi optimization algorithm tl;dr:
681 /// - Find the earliest def/phi, A, we can optimize to
682 /// - Find if all paths from the starting memory access ultimately reach A
683 /// - If not, optimization isn't possible.
684 /// - Otherwise, walk from A to another clobber or phi, A'.
685 /// - If A' is a def, we're done.
686 /// - If A' is a phi, try to optimize it.
687 ///
688 /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path
689 /// terminates when a MemoryAccess that clobbers said MemoryLocation is found.
690 OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start,
691 const MemoryLocation &Loc) {
692 assert(Paths.empty() && VisitedPhis.empty() &&
693 "Reset the optimization state.");
694
695 Paths.emplace_back(Loc, Start, Phi, None);
696 // Stores how many "valid" optimization nodes we had prior to calling
697 // addSearches/getBlockingAccess. Necessary for caching if we had a blocker.
698 auto PriorPathsSize = Paths.size();
699
700 SmallVector<ListIndex, 16> PausedSearches;
701 SmallVector<ListIndex, 8> NewPaused;
702 SmallVector<TerminatedPath, 4> TerminatedPaths;
703
704 addSearches(Phi, PausedSearches, 0);
705
706 // Moves the TerminatedPath with the "most dominated" Clobber to the end of
707 // Paths.
708 auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
709 assert(!Paths.empty() && "Need a path to move");
George Burgess IV5f308972016-07-19 01:29:15 +0000710 auto Dom = Paths.begin();
711 for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I)
712 if (!MSSA.dominates(I->Clobber, Dom->Clobber))
713 Dom = I;
714 auto Last = Paths.end() - 1;
715 if (Last != Dom)
716 std::iter_swap(Last, Dom);
717 };
718
719 MemoryPhi *Current = Phi;
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000720 while (true) {
George Burgess IV5f308972016-07-19 01:29:15 +0000721 assert(!MSSA.isLiveOnEntryDef(Current) &&
722 "liveOnEntry wasn't treated as a clobber?");
723
Daniel Berlind0420312017-04-01 09:01:12 +0000724 const auto *Target = getWalkTarget(Current);
George Burgess IV5f308972016-07-19 01:29:15 +0000725 // If a TerminatedPath doesn't dominate Target, then it wasn't a legal
726 // optimization for the prior phi.
727 assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {
728 return MSSA.dominates(P.Clobber, Target);
729 }));
730
731 // FIXME: This is broken, because the Blocker may be reported to be
732 // liveOnEntry, and we'll happily wait for that to disappear (read: never)
George Burgess IV7f414b92016-08-22 23:40:01 +0000733 // For the moment, this is fine, since we do nothing with blocker info.
George Burgess IV14633b52016-08-03 01:22:19 +0000734 if (Optional<TerminatedPath> Blocker = getBlockingAccess(
George Burgess IV5f308972016-07-19 01:29:15 +0000735 Target, PausedSearches, NewPaused, TerminatedPaths)) {
George Burgess IV5f308972016-07-19 01:29:15 +0000736
737 // Find the node we started at. We can't search based on N->Last, since
738 // we may have gone around a loop with a different MemoryLocation.
George Burgess IV14633b52016-08-03 01:22:19 +0000739 auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) {
George Burgess IV5f308972016-07-19 01:29:15 +0000740 return defPathIndex(N) < PriorPathsSize;
741 });
742 assert(Iter != def_path_iterator());
743
744 DefPath &CurNode = *Iter;
745 assert(CurNode.Last == Current);
George Burgess IV5f308972016-07-19 01:29:15 +0000746
747 // Two things:
748 // A. We can't reliably cache all of NewPaused back. Consider a case
749 // where we have two paths in NewPaused; one of which can't optimize
750 // above this phi, whereas the other can. If we cache the second path
751 // back, we'll end up with suboptimal cache entries. We can handle
752 // cases like this a bit better when we either try to find all
753 // clobbers that block phi optimization, or when our cache starts
754 // supporting unfinished searches.
755 // B. We can't reliably cache TerminatedPaths back here without doing
756 // extra checks; consider a case like:
757 // T
758 // / \
759 // D C
760 // \ /
761 // S
762 // Where T is our target, C is a node with a clobber on it, D is a
763 // diamond (with a clobber *only* on the left or right node, N), and
764 // S is our start. Say we walk to D, through the node opposite N
765 // (read: ignoring the clobber), and see a cache entry in the top
766 // node of D. That cache entry gets put into TerminatedPaths. We then
767 // walk up to C (N is later in our worklist), find the clobber, and
768 // quit. If we append TerminatedPaths to OtherClobbers, we'll cache
769 // the bottom part of D to the cached clobber, ignoring the clobber
770 // in N. Again, this problem goes away if we start tracking all
771 // blockers for a given phi optimization.
772 TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
773 return {Result, {}};
774 }
775
776 // If there's nothing left to search, then all paths led to valid clobbers
777 // that we got from our cache; pick the nearest to the start, and allow
778 // the rest to be cached back.
779 if (NewPaused.empty()) {
780 MoveDominatedPathToEnd(TerminatedPaths);
781 TerminatedPath Result = TerminatedPaths.pop_back_val();
782 return {Result, std::move(TerminatedPaths)};
783 }
784
785 MemoryAccess *DefChainEnd = nullptr;
786 SmallVector<TerminatedPath, 4> Clobbers;
787 for (ListIndex Paused : NewPaused) {
788 UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
789 if (WR.IsKnownClobber)
790 Clobbers.push_back({WR.Result, Paused});
791 else
792 // Micro-opt: If we hit the end of the chain, save it.
793 DefChainEnd = WR.Result;
794 }
795
796 if (!TerminatedPaths.empty()) {
797 // If we couldn't find the dominating phi/liveOnEntry in the above loop,
798 // do it now.
799 if (!DefChainEnd)
Daniel Berlind0420312017-04-01 09:01:12 +0000800 for (auto *MA : def_chain(const_cast<MemoryAccess *>(Target)))
George Burgess IV5f308972016-07-19 01:29:15 +0000801 DefChainEnd = MA;
802
803 // If any of the terminated paths don't dominate the phi we'll try to
804 // optimize, we need to figure out what they are and quit.
805 const BasicBlock *ChainBB = DefChainEnd->getBlock();
806 for (const TerminatedPath &TP : TerminatedPaths) {
807 // Because we know that DefChainEnd is as "high" as we can go, we
808 // don't need local dominance checks; BB dominance is sufficient.
809 if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
810 Clobbers.push_back(TP);
811 }
812 }
813
814 // If we have clobbers in the def chain, find the one closest to Current
815 // and quit.
816 if (!Clobbers.empty()) {
817 MoveDominatedPathToEnd(Clobbers);
818 TerminatedPath Result = Clobbers.pop_back_val();
819 return {Result, std::move(Clobbers)};
820 }
821
822 assert(all_of(NewPaused,
823 [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
824
825 // Because liveOnEntry is a clobber, this must be a phi.
826 auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
827
828 PriorPathsSize = Paths.size();
829 PausedSearches.clear();
830 for (ListIndex I : NewPaused)
831 addSearches(DefChainPhi, PausedSearches, I);
832 NewPaused.clear();
833
834 Current = DefChainPhi;
835 }
836 }
837
George Burgess IV5f308972016-07-19 01:29:15 +0000838 void verifyOptResult(const OptznResult &R) const {
839 assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
840 return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
841 }));
842 }
843
844 void resetPhiOptznState() {
845 Paths.clear();
846 VisitedPhis.clear();
847 }
848
849public:
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000850 ClobberWalker(const MemorySSA &MSSA, AliasAnalysis &AA, DominatorTree &DT)
851 : MSSA(MSSA), AA(AA), DT(DT) {}
George Burgess IV5f308972016-07-19 01:29:15 +0000852
George Burgess IV5f308972016-07-19 01:29:15 +0000853 /// Finds the nearest clobber for the given query, optimizing phis if
854 /// possible.
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000855 MemoryAccess *findClobber(MemoryAccess *Start, UpwardsMemoryQuery &Q) {
George Burgess IV5f308972016-07-19 01:29:15 +0000856 Query = &Q;
857
858 MemoryAccess *Current = Start;
859 // This walker pretends uses don't exist. If we're handed one, silently grab
860 // its def. (This has the nice side-effect of ensuring we never cache uses)
861 if (auto *MU = dyn_cast<MemoryUse>(Start))
862 Current = MU->getDefiningAccess();
863
864 DefPath FirstDesc(Q.StartingLoc, Current, Current, None);
865 // Fast path for the overly-common case (no crazy phi optimization
866 // necessary)
867 UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
George Burgess IV93ea19b2016-07-24 07:03:49 +0000868 MemoryAccess *Result;
George Burgess IV5f308972016-07-19 01:29:15 +0000869 if (WalkResult.IsKnownClobber) {
George Burgess IV93ea19b2016-07-24 07:03:49 +0000870 Result = WalkResult.Result;
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000871 Q.AR = WalkResult.AR;
George Burgess IV93ea19b2016-07-24 07:03:49 +0000872 } else {
873 OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
874 Current, Q.StartingLoc);
875 verifyOptResult(OptRes);
George Burgess IV93ea19b2016-07-24 07:03:49 +0000876 resetPhiOptznState();
877 Result = OptRes.PrimaryClobber.Clobber;
George Burgess IV5f308972016-07-19 01:29:15 +0000878 }
879
George Burgess IV5f308972016-07-19 01:29:15 +0000880#ifdef EXPENSIVE_CHECKS
George Burgess IV93ea19b2016-07-24 07:03:49 +0000881 checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, AA);
George Burgess IV5f308972016-07-19 01:29:15 +0000882#endif
George Burgess IV93ea19b2016-07-24 07:03:49 +0000883 return Result;
George Burgess IV5f308972016-07-19 01:29:15 +0000884 }
Geoff Berrycdf53332016-08-08 17:52:01 +0000885
886 void verify(const MemorySSA *MSSA) { assert(MSSA == &this->MSSA); }
George Burgess IV5f308972016-07-19 01:29:15 +0000887};
888
889struct RenamePassData {
890 DomTreeNode *DTN;
891 DomTreeNode::const_iterator ChildIt;
892 MemoryAccess *IncomingVal;
893
894 RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
895 MemoryAccess *M)
896 : DTN(D), ChildIt(It), IncomingVal(M) {}
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000897
George Burgess IV5f308972016-07-19 01:29:15 +0000898 void swap(RenamePassData &RHS) {
899 std::swap(DTN, RHS.DTN);
900 std::swap(ChildIt, RHS.ChildIt);
901 std::swap(IncomingVal, RHS.IncomingVal);
902 }
903};
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000904
905} // end anonymous namespace
George Burgess IV5f308972016-07-19 01:29:15 +0000906
907namespace llvm {
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000908
Daniel Berlind952cea2017-04-07 01:28:36 +0000909/// \brief A MemorySSAWalker that does AA walks to disambiguate accesses. It no
910/// longer does caching on its own,
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000911/// but the name has been retained for the moment.
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000912class MemorySSA::CachingWalker final : public MemorySSAWalker {
George Burgess IV5f308972016-07-19 01:29:15 +0000913 ClobberWalker Walker;
George Burgess IV5f308972016-07-19 01:29:15 +0000914
915 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *, UpwardsMemoryQuery &);
George Burgess IV5f308972016-07-19 01:29:15 +0000916
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000917public:
918 CachingWalker(MemorySSA *, AliasAnalysis *, DominatorTree *);
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000919 ~CachingWalker() override = default;
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000920
George Burgess IV400ae402016-07-20 19:51:34 +0000921 using MemorySSAWalker::getClobberingMemoryAccess;
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000922
George Burgess IV400ae402016-07-20 19:51:34 +0000923 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) override;
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000924 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
George Burgess IV013fd732016-10-28 19:22:46 +0000925 const MemoryLocation &) override;
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000926 void invalidateInfo(MemoryAccess *) override;
927
Geoff Berrycdf53332016-08-08 17:52:01 +0000928 void verify(const MemorySSA *MSSA) override {
929 MemorySSAWalker::verify(MSSA);
930 Walker.verify(MSSA);
931 }
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000932};
George Burgess IVe1100f52016-02-02 22:46:49 +0000933
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000934} // end namespace llvm
935
Daniel Berlin78cbd282017-02-20 22:26:03 +0000936void MemorySSA::renameSuccessorPhis(BasicBlock *BB, MemoryAccess *IncomingVal,
937 bool RenameAllUses) {
George Burgess IVe1100f52016-02-02 22:46:49 +0000938 // Pass through values to our successors
939 for (const BasicBlock *S : successors(BB)) {
940 auto It = PerBlockAccesses.find(S);
941 // Rename the phi nodes in our successor block
942 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
943 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +0000944 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +0000945 auto *Phi = cast<MemoryPhi>(&Accesses->front());
Daniel Berlin78cbd282017-02-20 22:26:03 +0000946 if (RenameAllUses) {
947 int PhiIndex = Phi->getBasicBlockIndex(BB);
948 assert(PhiIndex != -1 && "Incomplete phi during partial rename");
949 Phi->setIncomingValue(PhiIndex, IncomingVal);
950 } else
951 Phi->addIncoming(IncomingVal, BB);
George Burgess IVe1100f52016-02-02 22:46:49 +0000952 }
Daniel Berlin78cbd282017-02-20 22:26:03 +0000953}
George Burgess IVe1100f52016-02-02 22:46:49 +0000954
Daniel Berlin78cbd282017-02-20 22:26:03 +0000955/// \brief Rename a single basic block into MemorySSA form.
956/// Uses the standard SSA renaming algorithm.
957/// \returns The new incoming value.
958MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB, MemoryAccess *IncomingVal,
959 bool RenameAllUses) {
960 auto It = PerBlockAccesses.find(BB);
961 // Skip most processing if the list is empty.
962 if (It != PerBlockAccesses.end()) {
963 AccessList *Accesses = It->second.get();
964 for (MemoryAccess &L : *Accesses) {
965 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&L)) {
966 if (MUD->getDefiningAccess() == nullptr || RenameAllUses)
967 MUD->setDefiningAccess(IncomingVal);
968 if (isa<MemoryDef>(&L))
969 IncomingVal = &L;
970 } else {
971 IncomingVal = &L;
972 }
973 }
974 }
George Burgess IVe1100f52016-02-02 22:46:49 +0000975 return IncomingVal;
976}
977
978/// \brief This is the standard SSA renaming algorithm.
979///
980/// We walk the dominator tree in preorder, renaming accesses, and then filling
981/// in phi nodes in our successors.
982void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
Daniel Berlin78cbd282017-02-20 22:26:03 +0000983 SmallPtrSetImpl<BasicBlock *> &Visited,
984 bool SkipVisited, bool RenameAllUses) {
George Burgess IVe1100f52016-02-02 22:46:49 +0000985 SmallVector<RenamePassData, 32> WorkStack;
Daniel Berlin78cbd282017-02-20 22:26:03 +0000986 // Skip everything if we already renamed this block and we are skipping.
987 // Note: You can't sink this into the if, because we need it to occur
988 // regardless of whether we skip blocks or not.
989 bool AlreadyVisited = !Visited.insert(Root->getBlock()).second;
990 if (SkipVisited && AlreadyVisited)
991 return;
992
993 IncomingVal = renameBlock(Root->getBlock(), IncomingVal, RenameAllUses);
994 renameSuccessorPhis(Root->getBlock(), IncomingVal, RenameAllUses);
George Burgess IVe1100f52016-02-02 22:46:49 +0000995 WorkStack.push_back({Root, Root->begin(), IncomingVal});
George Burgess IVe1100f52016-02-02 22:46:49 +0000996
997 while (!WorkStack.empty()) {
998 DomTreeNode *Node = WorkStack.back().DTN;
999 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
1000 IncomingVal = WorkStack.back().IncomingVal;
1001
1002 if (ChildIt == Node->end()) {
1003 WorkStack.pop_back();
1004 } else {
1005 DomTreeNode *Child = *ChildIt;
1006 ++WorkStack.back().ChildIt;
1007 BasicBlock *BB = Child->getBlock();
Daniel Berlin78cbd282017-02-20 22:26:03 +00001008 // Note: You can't sink this into the if, because we need it to occur
1009 // regardless of whether we skip blocks or not.
1010 AlreadyVisited = !Visited.insert(BB).second;
1011 if (SkipVisited && AlreadyVisited) {
1012 // We already visited this during our renaming, which can happen when
1013 // being asked to rename multiple blocks. Figure out the incoming val,
1014 // which is the last def.
1015 // Incoming value can only change if there is a block def, and in that
1016 // case, it's the last block def in the list.
1017 if (auto *BlockDefs = getWritableBlockDefs(BB))
1018 IncomingVal = &*BlockDefs->rbegin();
1019 } else
1020 IncomingVal = renameBlock(BB, IncomingVal, RenameAllUses);
1021 renameSuccessorPhis(BB, IncomingVal, RenameAllUses);
George Burgess IVe1100f52016-02-02 22:46:49 +00001022 WorkStack.push_back({Child, Child->begin(), IncomingVal});
1023 }
1024 }
1025}
1026
George Burgess IVa362b092016-07-06 00:28:43 +00001027/// \brief This handles unreachable block accesses by deleting phi nodes in
George Burgess IVe1100f52016-02-02 22:46:49 +00001028/// unreachable blocks, and marking all other unreachable MemoryAccess's as
1029/// being uses of the live on entry definition.
1030void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
1031 assert(!DT->isReachableFromEntry(BB) &&
1032 "Reachable block found while handling unreachable blocks");
1033
Daniel Berlinfc7e6512016-07-06 05:32:05 +00001034 // Make sure phi nodes in our reachable successors end up with a
1035 // LiveOnEntryDef for our incoming edge, even though our block is forward
1036 // unreachable. We could just disconnect these blocks from the CFG fully,
1037 // but we do not right now.
1038 for (const BasicBlock *S : successors(BB)) {
1039 if (!DT->isReachableFromEntry(S))
1040 continue;
1041 auto It = PerBlockAccesses.find(S);
1042 // Rename the phi nodes in our successor block
1043 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1044 continue;
1045 AccessList *Accesses = It->second.get();
1046 auto *Phi = cast<MemoryPhi>(&Accesses->front());
1047 Phi->addIncoming(LiveOnEntryDef.get(), BB);
1048 }
1049
George Burgess IVe1100f52016-02-02 22:46:49 +00001050 auto It = PerBlockAccesses.find(BB);
1051 if (It == PerBlockAccesses.end())
1052 return;
1053
1054 auto &Accesses = It->second;
1055 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1056 auto Next = std::next(AI);
1057 // If we have a phi, just remove it. We are going to replace all
1058 // users with live on entry.
1059 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1060 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1061 else
1062 Accesses->erase(AI);
1063 AI = Next;
1064 }
1065}
1066
Geoff Berryb96d3b22016-06-01 21:30:40 +00001067MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
1068 : AA(AA), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
George Burgess IV68ac9412018-02-23 23:07:18 +00001069 NextID(0) {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001070 buildMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001071}
1072
George Burgess IVe1100f52016-02-02 22:46:49 +00001073MemorySSA::~MemorySSA() {
1074 // Drop all our references
1075 for (const auto &Pair : PerBlockAccesses)
1076 for (MemoryAccess &MA : *Pair.second)
1077 MA.dropAllReferences();
1078}
1079
Daniel Berlin14300262016-06-21 18:39:20 +00001080MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001081 auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
1082
1083 if (Res.second)
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001084 Res.first->second = llvm::make_unique<AccessList>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001085 return Res.first->second.get();
1086}
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001087
Daniel Berlind602e042017-01-25 20:56:19 +00001088MemorySSA::DefsList *MemorySSA::getOrCreateDefsList(const BasicBlock *BB) {
1089 auto Res = PerBlockDefs.insert(std::make_pair(BB, nullptr));
1090
1091 if (Res.second)
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001092 Res.first->second = llvm::make_unique<DefsList>();
Daniel Berlind602e042017-01-25 20:56:19 +00001093 return Res.first->second.get();
1094}
George Burgess IVe1100f52016-02-02 22:46:49 +00001095
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001096namespace llvm {
1097
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001098/// This class is a batch walker of all MemoryUse's in the program, and points
1099/// their defining access at the thing that actually clobbers them. Because it
1100/// is a batch walker that touches everything, it does not operate like the
1101/// other walkers. This walker is basically performing a top-down SSA renaming
1102/// pass, where the version stack is used as the cache. This enables it to be
1103/// significantly more time and memory efficient than using the regular walker,
1104/// which is walking bottom-up.
1105class MemorySSA::OptimizeUses {
1106public:
1107 OptimizeUses(MemorySSA *MSSA, MemorySSAWalker *Walker, AliasAnalysis *AA,
1108 DominatorTree *DT)
1109 : MSSA(MSSA), Walker(Walker), AA(AA), DT(DT) {
1110 Walker = MSSA->getWalker();
1111 }
1112
1113 void optimizeUses();
1114
1115private:
1116 /// This represents where a given memorylocation is in the stack.
1117 struct MemlocStackInfo {
1118 // This essentially is keeping track of versions of the stack. Whenever
1119 // the stack changes due to pushes or pops, these versions increase.
1120 unsigned long StackEpoch;
1121 unsigned long PopEpoch;
1122 // This is the lower bound of places on the stack to check. It is equal to
1123 // the place the last stack walk ended.
1124 // Note: Correctness depends on this being initialized to 0, which densemap
1125 // does
1126 unsigned long LowerBound;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001127 const BasicBlock *LowerBoundBlock;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001128 // This is where the last walk for this memory location ended.
1129 unsigned long LastKill;
1130 bool LastKillValid;
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001131 Optional<AliasResult> AR;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001132 };
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001133
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001134 void optimizeUsesInBlock(const BasicBlock *, unsigned long &, unsigned long &,
1135 SmallVectorImpl<MemoryAccess *> &,
1136 DenseMap<MemoryLocOrCall, MemlocStackInfo> &);
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001137
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001138 MemorySSA *MSSA;
1139 MemorySSAWalker *Walker;
1140 AliasAnalysis *AA;
1141 DominatorTree *DT;
1142};
1143
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001144} // end namespace llvm
1145
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001146/// Optimize the uses in a given block This is basically the SSA renaming
1147/// algorithm, with one caveat: We are able to use a single stack for all
1148/// MemoryUses. This is because the set of *possible* reaching MemoryDefs is
1149/// the same for every MemoryUse. The *actual* clobbering MemoryDef is just
1150/// going to be some position in that stack of possible ones.
1151///
1152/// We track the stack positions that each MemoryLocation needs
1153/// to check, and last ended at. This is because we only want to check the
1154/// things that changed since last time. The same MemoryLocation should
1155/// get clobbered by the same store (getModRefInfo does not use invariantness or
1156/// things like this, and if they start, we can modify MemoryLocOrCall to
1157/// include relevant data)
1158void MemorySSA::OptimizeUses::optimizeUsesInBlock(
1159 const BasicBlock *BB, unsigned long &StackEpoch, unsigned long &PopEpoch,
1160 SmallVectorImpl<MemoryAccess *> &VersionStack,
1161 DenseMap<MemoryLocOrCall, MemlocStackInfo> &LocStackInfo) {
1162
1163 /// If no accesses, nothing to do.
1164 MemorySSA::AccessList *Accesses = MSSA->getWritableBlockAccesses(BB);
1165 if (Accesses == nullptr)
1166 return;
1167
1168 // Pop everything that doesn't dominate the current block off the stack,
1169 // increment the PopEpoch to account for this.
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001170 while (true) {
1171 assert(
1172 !VersionStack.empty() &&
1173 "Version stack should have liveOnEntry sentinel dominating everything");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001174 BasicBlock *BackBlock = VersionStack.back()->getBlock();
1175 if (DT->dominates(BackBlock, BB))
1176 break;
1177 while (VersionStack.back()->getBlock() == BackBlock)
1178 VersionStack.pop_back();
1179 ++PopEpoch;
1180 }
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001181
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001182 for (MemoryAccess &MA : *Accesses) {
1183 auto *MU = dyn_cast<MemoryUse>(&MA);
1184 if (!MU) {
1185 VersionStack.push_back(&MA);
1186 ++StackEpoch;
1187 continue;
1188 }
1189
George Burgess IV024f3d22016-08-03 19:57:02 +00001190 if (isUseTriviallyOptimizableToLiveOnEntry(*AA, MU->getMemoryInst())) {
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001191 MU->setDefiningAccess(MSSA->getLiveOnEntryDef(), true, None);
George Burgess IV024f3d22016-08-03 19:57:02 +00001192 continue;
1193 }
1194
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001195 MemoryLocOrCall UseMLOC(MU);
1196 auto &LocInfo = LocStackInfo[UseMLOC];
Daniel Berlin26fcea92016-08-02 20:02:21 +00001197 // If the pop epoch changed, it means we've removed stuff from top of
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001198 // stack due to changing blocks. We may have to reset the lower bound or
1199 // last kill info.
1200 if (LocInfo.PopEpoch != PopEpoch) {
1201 LocInfo.PopEpoch = PopEpoch;
1202 LocInfo.StackEpoch = StackEpoch;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001203 // If the lower bound was in something that no longer dominates us, we
1204 // have to reset it.
1205 // We can't simply track stack size, because the stack may have had
1206 // pushes/pops in the meantime.
1207 // XXX: This is non-optimal, but only is slower cases with heavily
1208 // branching dominator trees. To get the optimal number of queries would
1209 // be to make lowerbound and lastkill a per-loc stack, and pop it until
1210 // the top of that stack dominates us. This does not seem worth it ATM.
1211 // A much cheaper optimization would be to always explore the deepest
1212 // branch of the dominator tree first. This will guarantee this resets on
1213 // the smallest set of blocks.
1214 if (LocInfo.LowerBoundBlock && LocInfo.LowerBoundBlock != BB &&
Daniel Berlin1e98c042016-09-26 17:22:54 +00001215 !DT->dominates(LocInfo.LowerBoundBlock, BB)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001216 // Reset the lower bound of things to check.
1217 // TODO: Some day we should be able to reset to last kill, rather than
1218 // 0.
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001219 LocInfo.LowerBound = 0;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001220 LocInfo.LowerBoundBlock = VersionStack[0]->getBlock();
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001221 LocInfo.LastKillValid = false;
1222 }
1223 } else if (LocInfo.StackEpoch != StackEpoch) {
1224 // If all that has changed is the StackEpoch, we only have to check the
1225 // new things on the stack, because we've checked everything before. In
1226 // this case, the lower bound of things to check remains the same.
1227 LocInfo.PopEpoch = PopEpoch;
1228 LocInfo.StackEpoch = StackEpoch;
1229 }
1230 if (!LocInfo.LastKillValid) {
1231 LocInfo.LastKill = VersionStack.size() - 1;
1232 LocInfo.LastKillValid = true;
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001233 LocInfo.AR = MayAlias;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001234 }
1235
1236 // At this point, we should have corrected last kill and LowerBound to be
1237 // in bounds.
1238 assert(LocInfo.LowerBound < VersionStack.size() &&
1239 "Lower bound out of range");
1240 assert(LocInfo.LastKill < VersionStack.size() &&
1241 "Last kill info out of range");
1242 // In any case, the new upper bound is the top of the stack.
1243 unsigned long UpperBound = VersionStack.size() - 1;
1244
1245 if (UpperBound - LocInfo.LowerBound > MaxCheckLimit) {
Daniel Berlin26fcea92016-08-02 20:02:21 +00001246 DEBUG(dbgs() << "MemorySSA skipping optimization of " << *MU << " ("
1247 << *(MU->getMemoryInst()) << ")"
1248 << " because there are " << UpperBound - LocInfo.LowerBound
1249 << " stores to disambiguate\n");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001250 // Because we did not walk, LastKill is no longer valid, as this may
1251 // have been a kill.
1252 LocInfo.LastKillValid = false;
1253 continue;
1254 }
1255 bool FoundClobberResult = false;
1256 while (UpperBound > LocInfo.LowerBound) {
1257 if (isa<MemoryPhi>(VersionStack[UpperBound])) {
1258 // For phis, use the walker, see where we ended up, go there
1259 Instruction *UseInst = MU->getMemoryInst();
1260 MemoryAccess *Result = Walker->getClobberingMemoryAccess(UseInst);
1261 // We are guaranteed to find it or something is wrong
1262 while (VersionStack[UpperBound] != Result) {
1263 assert(UpperBound != 0);
1264 --UpperBound;
1265 }
1266 FoundClobberResult = true;
1267 break;
1268 }
1269
1270 MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]);
Daniel Berlindf101192016-08-03 00:01:46 +00001271 // If the lifetime of the pointer ends at this instruction, it's live on
1272 // entry.
1273 if (!UseMLOC.IsCall && lifetimeEndsAt(MD, UseMLOC.getLoc(), *AA)) {
1274 // Reset UpperBound to liveOnEntryDef's place in the stack
1275 UpperBound = 0;
1276 FoundClobberResult = true;
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001277 LocInfo.AR = MustAlias;
Daniel Berlindf101192016-08-03 00:01:46 +00001278 break;
1279 }
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001280 ClobberAlias CA = instructionClobbersQuery(MD, MU, UseMLOC, *AA);
1281 if (CA.IsClobber) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001282 FoundClobberResult = true;
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001283 LocInfo.AR = CA.AR;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001284 break;
1285 }
1286 --UpperBound;
1287 }
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001288
1289 // Note: Phis always have AliasResult AR set to MayAlias ATM.
1290
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001291 // At the end of this loop, UpperBound is either a clobber, or lower bound
1292 // PHI walking may cause it to be < LowerBound, and in fact, < LastKill.
1293 if (FoundClobberResult || UpperBound < LocInfo.LastKill) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001294 // We were last killed now by where we got to
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001295 if (MSSA->isLiveOnEntryDef(VersionStack[UpperBound]))
1296 LocInfo.AR = None;
1297 MU->setDefiningAccess(VersionStack[UpperBound], true, LocInfo.AR);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001298 LocInfo.LastKill = UpperBound;
1299 } else {
1300 // Otherwise, we checked all the new ones, and now we know we can get to
1301 // LastKill.
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001302 MU->setDefiningAccess(VersionStack[LocInfo.LastKill], true, LocInfo.AR);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001303 }
1304 LocInfo.LowerBound = VersionStack.size() - 1;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001305 LocInfo.LowerBoundBlock = BB;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001306 }
1307}
1308
1309/// Optimize uses to point to their actual clobbering definitions.
1310void MemorySSA::OptimizeUses::optimizeUses() {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001311 SmallVector<MemoryAccess *, 16> VersionStack;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001312 DenseMap<MemoryLocOrCall, MemlocStackInfo> LocStackInfo;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001313 VersionStack.push_back(MSSA->getLiveOnEntryDef());
1314
1315 unsigned long StackEpoch = 1;
1316 unsigned long PopEpoch = 1;
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001317 // We perform a non-recursive top-down dominator tree walk.
Daniel Berlin7ac3d742016-08-05 22:09:14 +00001318 for (const auto *DomNode : depth_first(DT->getRootNode()))
1319 optimizeUsesInBlock(DomNode->getBlock(), StackEpoch, PopEpoch, VersionStack,
1320 LocStackInfo);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001321}
1322
Daniel Berlin3d512a22016-08-22 19:14:30 +00001323void MemorySSA::placePHINodes(
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001324 const SmallPtrSetImpl<BasicBlock *> &DefiningBlocks,
1325 const DenseMap<const BasicBlock *, unsigned int> &BBNumbers) {
Daniel Berlin3d512a22016-08-22 19:14:30 +00001326 // Determine where our MemoryPhi's should go
1327 ForwardIDFCalculator IDFs(*DT);
1328 IDFs.setDefiningBlocks(DefiningBlocks);
Daniel Berlin3d512a22016-08-22 19:14:30 +00001329 SmallVector<BasicBlock *, 32> IDFBlocks;
1330 IDFs.calculate(IDFBlocks);
1331
Mandeep Singh Grang97bcade2018-04-01 01:46:51 +00001332 llvm::sort(IDFBlocks.begin(), IDFBlocks.end(),
1333 [&BBNumbers](const BasicBlock *A, const BasicBlock *B) {
1334 return BBNumbers.lookup(A) < BBNumbers.lookup(B);
1335 });
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001336
Daniel Berlin3d512a22016-08-22 19:14:30 +00001337 // Now place MemoryPhi nodes.
Daniel Berlind602e042017-01-25 20:56:19 +00001338 for (auto &BB : IDFBlocks)
1339 createMemoryPhi(BB);
Daniel Berlin3d512a22016-08-22 19:14:30 +00001340}
1341
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001342void MemorySSA::buildMemorySSA() {
George Burgess IVe1100f52016-02-02 22:46:49 +00001343 // We create an access to represent "live on entry", for things like
1344 // arguments or users of globals, where the memory they use is defined before
1345 // the beginning of the function. We do not actually insert it into the IR.
1346 // We do not define a live on exit for the immediate uses, and thus our
1347 // semantics do *not* imply that something with no immediate uses can simply
1348 // be removed.
1349 BasicBlock &StartingPoint = F.getEntryBlock();
George Burgess IV612cf212018-02-27 06:43:19 +00001350 LiveOnEntryDef.reset(new MemoryDef(F.getContext(), nullptr, nullptr,
1351 &StartingPoint, NextID++));
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001352 DenseMap<const BasicBlock *, unsigned int> BBNumbers;
1353 unsigned NextBBNum = 0;
George Burgess IVe1100f52016-02-02 22:46:49 +00001354
1355 // We maintain lists of memory accesses per-block, trading memory for time. We
1356 // could just look up the memory access for every possible instruction in the
1357 // stream.
1358 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
George Burgess IVe1100f52016-02-02 22:46:49 +00001359 // Go through each block, figure out where defs occur, and chain together all
1360 // the accesses.
1361 for (BasicBlock &B : F) {
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001362 BBNumbers[&B] = NextBBNum++;
Daniel Berlin7898ca62016-02-07 01:52:15 +00001363 bool InsertIntoDef = false;
Daniel Berlinada263d2016-06-20 20:21:33 +00001364 AccessList *Accesses = nullptr;
Daniel Berlind602e042017-01-25 20:56:19 +00001365 DefsList *Defs = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +00001366 for (Instruction &I : B) {
Peter Collingbourneffecb142016-05-26 01:19:17 +00001367 MemoryUseOrDef *MUD = createNewAccess(&I);
George Burgess IVb42b7622016-03-11 19:34:03 +00001368 if (!MUD)
George Burgess IVe1100f52016-02-02 22:46:49 +00001369 continue;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001370
George Burgess IVe1100f52016-02-02 22:46:49 +00001371 if (!Accesses)
1372 Accesses = getOrCreateAccessList(&B);
George Burgess IVb42b7622016-03-11 19:34:03 +00001373 Accesses->push_back(MUD);
Daniel Berlind602e042017-01-25 20:56:19 +00001374 if (isa<MemoryDef>(MUD)) {
1375 InsertIntoDef = true;
1376 if (!Defs)
1377 Defs = getOrCreateDefsList(&B);
1378 Defs->push_back(*MUD);
1379 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001380 }
Daniel Berlin7898ca62016-02-07 01:52:15 +00001381 if (InsertIntoDef)
1382 DefiningBlocks.insert(&B);
Daniel Berlin1b51a292016-02-07 01:52:19 +00001383 }
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001384 placePHINodes(DefiningBlocks, BBNumbers);
George Burgess IVe1100f52016-02-02 22:46:49 +00001385
1386 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
1387 // filled in with all blocks.
1388 SmallPtrSet<BasicBlock *, 16> Visited;
1389 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1390
George Burgess IV5f308972016-07-19 01:29:15 +00001391 CachingWalker *Walker = getWalkerImpl();
1392
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001393 OptimizeUses(this, Walker, AA, DT).optimizeUses();
George Burgess IV5f308972016-07-19 01:29:15 +00001394
George Burgess IVe1100f52016-02-02 22:46:49 +00001395 // Mark the uses in unreachable blocks as live on entry, so that they go
1396 // somewhere.
1397 for (auto &BB : F)
1398 if (!Visited.count(&BB))
1399 markUnreachableAsLiveOnEntry(&BB);
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001400}
George Burgess IVe1100f52016-02-02 22:46:49 +00001401
George Burgess IV5f308972016-07-19 01:29:15 +00001402MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
1403
1404MemorySSA::CachingWalker *MemorySSA::getWalkerImpl() {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001405 if (Walker)
1406 return Walker.get();
1407
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001408 Walker = llvm::make_unique<CachingWalker>(this, AA, DT);
Geoff Berryb96d3b22016-06-01 21:30:40 +00001409 return Walker.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001410}
1411
Daniel Berlind602e042017-01-25 20:56:19 +00001412// This is a helper function used by the creation routines. It places NewAccess
1413// into the access and defs lists for a given basic block, at the given
1414// insertion point.
1415void MemorySSA::insertIntoListsForBlock(MemoryAccess *NewAccess,
1416 const BasicBlock *BB,
1417 InsertionPlace Point) {
1418 auto *Accesses = getOrCreateAccessList(BB);
1419 if (Point == Beginning) {
1420 // If it's a phi node, it goes first, otherwise, it goes after any phi
1421 // nodes.
1422 if (isa<MemoryPhi>(NewAccess)) {
1423 Accesses->push_front(NewAccess);
1424 auto *Defs = getOrCreateDefsList(BB);
1425 Defs->push_front(*NewAccess);
1426 } else {
1427 auto AI = find_if_not(
1428 *Accesses, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1429 Accesses->insert(AI, NewAccess);
1430 if (!isa<MemoryUse>(NewAccess)) {
1431 auto *Defs = getOrCreateDefsList(BB);
1432 auto DI = find_if_not(
1433 *Defs, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1434 Defs->insert(DI, *NewAccess);
1435 }
1436 }
1437 } else {
1438 Accesses->push_back(NewAccess);
1439 if (!isa<MemoryUse>(NewAccess)) {
1440 auto *Defs = getOrCreateDefsList(BB);
1441 Defs->push_back(*NewAccess);
1442 }
1443 }
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001444 BlockNumberingValid.erase(BB);
Daniel Berlind602e042017-01-25 20:56:19 +00001445}
1446
1447void MemorySSA::insertIntoListsBefore(MemoryAccess *What, const BasicBlock *BB,
1448 AccessList::iterator InsertPt) {
1449 auto *Accesses = getWritableBlockAccesses(BB);
1450 bool WasEnd = InsertPt == Accesses->end();
1451 Accesses->insert(AccessList::iterator(InsertPt), What);
1452 if (!isa<MemoryUse>(What)) {
1453 auto *Defs = getOrCreateDefsList(BB);
1454 // If we got asked to insert at the end, we have an easy job, just shove it
1455 // at the end. If we got asked to insert before an existing def, we also get
Zhaoshi Zhenga5531f22018-04-04 21:08:11 +00001456 // an iterator. If we got asked to insert before a use, we have to hunt for
Daniel Berlind602e042017-01-25 20:56:19 +00001457 // the next def.
1458 if (WasEnd) {
1459 Defs->push_back(*What);
1460 } else if (isa<MemoryDef>(InsertPt)) {
1461 Defs->insert(InsertPt->getDefsIterator(), *What);
1462 } else {
1463 while (InsertPt != Accesses->end() && !isa<MemoryDef>(InsertPt))
1464 ++InsertPt;
1465 // Either we found a def, or we are inserting at the end
1466 if (InsertPt == Accesses->end())
1467 Defs->push_back(*What);
1468 else
1469 Defs->insert(InsertPt->getDefsIterator(), *What);
1470 }
1471 }
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001472 BlockNumberingValid.erase(BB);
Daniel Berlind602e042017-01-25 20:56:19 +00001473}
1474
Zhaoshi Zhenga5531f22018-04-04 21:08:11 +00001475// Move What before Where in the IR. The end result is that What will belong to
Daniel Berlin60ead052017-01-28 01:23:13 +00001476// the right lists and have the right Block set, but will not otherwise be
1477// correct. It will not have the right defining access, and if it is a def,
1478// things below it will not properly be updated.
1479void MemorySSA::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
1480 AccessList::iterator Where) {
1481 // Keep it in the lookup tables, remove from the lists
1482 removeFromLists(What, false);
1483 What->setBlock(BB);
1484 insertIntoListsBefore(What, BB, Where);
1485}
1486
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001487void MemorySSA::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
1488 InsertionPlace Point) {
1489 removeFromLists(What, false);
1490 What->setBlock(BB);
1491 insertIntoListsForBlock(What, BB, Point);
1492}
1493
Daniel Berlin14300262016-06-21 18:39:20 +00001494MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
1495 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
Daniel Berlin14300262016-06-21 18:39:20 +00001496 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001497 // Phi's always are placed at the front of the block.
Daniel Berlind602e042017-01-25 20:56:19 +00001498 insertIntoListsForBlock(Phi, BB, Beginning);
Daniel Berlin5130cc82016-07-31 21:08:20 +00001499 ValueToMemoryAccess[BB] = Phi;
Daniel Berlin14300262016-06-21 18:39:20 +00001500 return Phi;
1501}
1502
1503MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
1504 MemoryAccess *Definition) {
1505 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
1506 MemoryUseOrDef *NewAccess = createNewAccess(I);
1507 assert(
1508 NewAccess != nullptr &&
1509 "Tried to create a memory access for a non-memory touching instruction");
1510 NewAccess->setDefiningAccess(Definition);
1511 return NewAccess;
1512}
1513
Daniel Berlind952cea2017-04-07 01:28:36 +00001514// Return true if the instruction has ordering constraints.
1515// Note specifically that this only considers stores and loads
1516// because others are still considered ModRef by getModRefInfo.
1517static inline bool isOrdered(const Instruction *I) {
1518 if (auto *SI = dyn_cast<StoreInst>(I)) {
1519 if (!SI->isUnordered())
1520 return true;
1521 } else if (auto *LI = dyn_cast<LoadInst>(I)) {
1522 if (!LI->isUnordered())
1523 return true;
1524 }
1525 return false;
1526}
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001527
George Burgess IVe1100f52016-02-02 22:46:49 +00001528/// \brief Helper function to create new memory accesses
Peter Collingbourneffecb142016-05-26 01:19:17 +00001529MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I) {
Peter Collingbourneb9aa1f42016-05-26 04:58:46 +00001530 // The assume intrinsic has a control dependency which we model by claiming
1531 // that it writes arbitrarily. Ignore that fake memory dependency here.
1532 // FIXME: Replace this special casing with a more accurate modelling of
1533 // assume's control dependency.
1534 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1535 if (II->getIntrinsicID() == Intrinsic::assume)
1536 return nullptr;
1537
George Burgess IVe1100f52016-02-02 22:46:49 +00001538 // Find out what affect this instruction has on memory.
Alina Sbirlea967e7962017-08-01 00:28:29 +00001539 ModRefInfo ModRef = AA->getModRefInfo(I, None);
Daniel Berlind952cea2017-04-07 01:28:36 +00001540 // The isOrdered check is used to ensure that volatiles end up as defs
1541 // (atomics end up as ModRef right now anyway). Until we separate the
1542 // ordering chain from the memory chain, this enables people to see at least
1543 // some relative ordering to volatiles. Note that getClobberingMemoryAccess
1544 // will still give an answer that bypasses other volatile loads. TODO:
1545 // Separate memory aliasing and ordering into two different chains so that we
1546 // can precisely represent both "what memory will this read/write/is clobbered
1547 // by" and "what instructions can I move this past".
Alina Sbirlea63d22502017-12-05 20:12:23 +00001548 bool Def = isModSet(ModRef) || isOrdered(I);
1549 bool Use = isRefSet(ModRef);
George Burgess IVe1100f52016-02-02 22:46:49 +00001550
1551 // It's possible for an instruction to not modify memory at all. During
1552 // construction, we ignore them.
Peter Collingbourneffecb142016-05-26 01:19:17 +00001553 if (!Def && !Use)
George Burgess IVe1100f52016-02-02 22:46:49 +00001554 return nullptr;
1555
George Burgess IVb42b7622016-03-11 19:34:03 +00001556 MemoryUseOrDef *MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001557 if (Def)
George Burgess IVb42b7622016-03-11 19:34:03 +00001558 MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
George Burgess IVe1100f52016-02-02 22:46:49 +00001559 else
George Burgess IVb42b7622016-03-11 19:34:03 +00001560 MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
Daniel Berlin5130cc82016-07-31 21:08:20 +00001561 ValueToMemoryAccess[I] = MUD;
George Burgess IVb42b7622016-03-11 19:34:03 +00001562 return MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001563}
1564
George Burgess IVe1100f52016-02-02 22:46:49 +00001565/// \brief Returns true if \p Replacer dominates \p Replacee .
1566bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
1567 const MemoryAccess *Replacee) const {
1568 if (isa<MemoryUseOrDef>(Replacee))
1569 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
1570 const auto *MP = cast<MemoryPhi>(Replacee);
1571 // For a phi node, the use occurs in the predecessor block of the phi node.
1572 // Since we may occur multiple times in the phi node, we have to check each
1573 // operand to ensure Replacer dominates each operand where Replacee occurs.
1574 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +00001575 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +00001576 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
1577 return false;
1578 }
1579 return true;
1580}
1581
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001582/// \brief Properly remove \p MA from all of MemorySSA's lookup tables.
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001583void MemorySSA::removeFromLookups(MemoryAccess *MA) {
1584 assert(MA->use_empty() &&
1585 "Trying to remove memory access that still has uses");
Daniel Berlin5c46b942016-07-19 22:49:43 +00001586 BlockNumbering.erase(MA);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001587 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA))
1588 MUD->setDefiningAccess(nullptr);
1589 // Invalidate our walker's cache if necessary
1590 if (!isa<MemoryUse>(MA))
1591 Walker->invalidateInfo(MA);
1592 // The call below to erase will destroy MA, so we can't change the order we
1593 // are doing things here
1594 Value *MemoryInst;
1595 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
1596 MemoryInst = MUD->getMemoryInst();
1597 } else {
1598 MemoryInst = MA->getBlock();
1599 }
Daniel Berlin5130cc82016-07-31 21:08:20 +00001600 auto VMA = ValueToMemoryAccess.find(MemoryInst);
1601 if (VMA->second == MA)
1602 ValueToMemoryAccess.erase(VMA);
Daniel Berlin60ead052017-01-28 01:23:13 +00001603}
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001604
Daniel Berlin60ead052017-01-28 01:23:13 +00001605/// \brief Properly remove \p MA from all of MemorySSA's lists.
1606///
1607/// Because of the way the intrusive list and use lists work, it is important to
1608/// do removal in the right order.
1609/// ShouldDelete defaults to true, and will cause the memory access to also be
1610/// deleted, not just removed.
1611void MemorySSA::removeFromLists(MemoryAccess *MA, bool ShouldDelete) {
Daniel Berlind602e042017-01-25 20:56:19 +00001612 // The access list owns the reference, so we erase it from the non-owning list
1613 // first.
1614 if (!isa<MemoryUse>(MA)) {
1615 auto DefsIt = PerBlockDefs.find(MA->getBlock());
1616 std::unique_ptr<DefsList> &Defs = DefsIt->second;
1617 Defs->remove(*MA);
1618 if (Defs->empty())
1619 PerBlockDefs.erase(DefsIt);
1620 }
1621
Daniel Berlin60ead052017-01-28 01:23:13 +00001622 // The erase call here will delete it. If we don't want it deleted, we call
1623 // remove instead.
George Burgess IVe0e6e482016-03-02 02:35:04 +00001624 auto AccessIt = PerBlockAccesses.find(MA->getBlock());
Daniel Berlinada263d2016-06-20 20:21:33 +00001625 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
Daniel Berlin60ead052017-01-28 01:23:13 +00001626 if (ShouldDelete)
1627 Accesses->erase(MA);
1628 else
1629 Accesses->remove(MA);
1630
George Burgess IVe0e6e482016-03-02 02:35:04 +00001631 if (Accesses->empty())
1632 PerBlockAccesses.erase(AccessIt);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001633}
1634
George Burgess IVe1100f52016-02-02 22:46:49 +00001635void MemorySSA::print(raw_ostream &OS) const {
1636 MemorySSAAnnotatedWriter Writer(this);
1637 F.print(OS, &Writer);
1638}
1639
Aaron Ballman615eb472017-10-15 14:32:27 +00001640#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Daniel Berlin78cbd282017-02-20 22:26:03 +00001641LLVM_DUMP_METHOD void MemorySSA::dump() const { print(dbgs()); }
Matthias Braun8c209aa2017-01-28 02:02:38 +00001642#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001643
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001644void MemorySSA::verifyMemorySSA() const {
1645 verifyDefUses(F);
1646 verifyDomination(F);
Daniel Berlin14300262016-06-21 18:39:20 +00001647 verifyOrdering(F);
Geoff Berrycdf53332016-08-08 17:52:01 +00001648 Walker->verify(this);
Daniel Berlin14300262016-06-21 18:39:20 +00001649}
1650
1651/// \brief Verify that the order and existence of MemoryAccesses matches the
1652/// order and existence of memory affecting instructions.
1653void MemorySSA::verifyOrdering(Function &F) const {
1654 // Walk all the blocks, comparing what the lookups think and what the access
1655 // lists think, as well as the order in the blocks vs the order in the access
1656 // lists.
1657 SmallVector<MemoryAccess *, 32> ActualAccesses;
Daniel Berlind602e042017-01-25 20:56:19 +00001658 SmallVector<MemoryAccess *, 32> ActualDefs;
Daniel Berlin14300262016-06-21 18:39:20 +00001659 for (BasicBlock &B : F) {
1660 const AccessList *AL = getBlockAccesses(&B);
Daniel Berlind602e042017-01-25 20:56:19 +00001661 const auto *DL = getBlockDefs(&B);
Daniel Berlin14300262016-06-21 18:39:20 +00001662 MemoryAccess *Phi = getMemoryAccess(&B);
Daniel Berlind602e042017-01-25 20:56:19 +00001663 if (Phi) {
Daniel Berlin14300262016-06-21 18:39:20 +00001664 ActualAccesses.push_back(Phi);
Daniel Berlind602e042017-01-25 20:56:19 +00001665 ActualDefs.push_back(Phi);
1666 }
1667
Daniel Berlin14300262016-06-21 18:39:20 +00001668 for (Instruction &I : B) {
1669 MemoryAccess *MA = getMemoryAccess(&I);
Daniel Berlind602e042017-01-25 20:56:19 +00001670 assert((!MA || (AL && (isa<MemoryUse>(MA) || DL))) &&
1671 "We have memory affecting instructions "
1672 "in this block but they are not in the "
1673 "access list or defs list");
1674 if (MA) {
Daniel Berlin14300262016-06-21 18:39:20 +00001675 ActualAccesses.push_back(MA);
Daniel Berlind602e042017-01-25 20:56:19 +00001676 if (isa<MemoryDef>(MA))
1677 ActualDefs.push_back(MA);
1678 }
Daniel Berlin14300262016-06-21 18:39:20 +00001679 }
1680 // Either we hit the assert, really have no accesses, or we have both
Daniel Berlind602e042017-01-25 20:56:19 +00001681 // accesses and an access list.
1682 // Same with defs.
1683 if (!AL && !DL)
Daniel Berlin14300262016-06-21 18:39:20 +00001684 continue;
1685 assert(AL->size() == ActualAccesses.size() &&
1686 "We don't have the same number of accesses in the block as on the "
1687 "access list");
Davide Italiano6c77de02017-01-30 03:16:43 +00001688 assert((DL || ActualDefs.size() == 0) &&
1689 "Either we should have a defs list, or we should have no defs");
Daniel Berlind602e042017-01-25 20:56:19 +00001690 assert((!DL || DL->size() == ActualDefs.size()) &&
1691 "We don't have the same number of defs in the block as on the "
1692 "def list");
Daniel Berlin14300262016-06-21 18:39:20 +00001693 auto ALI = AL->begin();
1694 auto AAI = ActualAccesses.begin();
1695 while (ALI != AL->end() && AAI != ActualAccesses.end()) {
1696 assert(&*ALI == *AAI && "Not the same accesses in the same order");
1697 ++ALI;
1698 ++AAI;
1699 }
1700 ActualAccesses.clear();
Daniel Berlind602e042017-01-25 20:56:19 +00001701 if (DL) {
1702 auto DLI = DL->begin();
1703 auto ADI = ActualDefs.begin();
1704 while (DLI != DL->end() && ADI != ActualDefs.end()) {
1705 assert(&*DLI == *ADI && "Not the same defs in the same order");
1706 ++DLI;
1707 ++ADI;
1708 }
1709 }
1710 ActualDefs.clear();
Daniel Berlin14300262016-06-21 18:39:20 +00001711 }
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001712}
1713
George Burgess IVe1100f52016-02-02 22:46:49 +00001714/// \brief Verify the domination properties of MemorySSA by checking that each
1715/// definition dominates all of its uses.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001716void MemorySSA::verifyDomination(Function &F) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001717#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001718 for (BasicBlock &B : F) {
1719 // Phi nodes are attached to basic blocks
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001720 if (MemoryPhi *MP = getMemoryAccess(&B))
1721 for (const Use &U : MP->uses())
1722 assert(dominates(MP, U) && "Memory PHI does not dominate it's uses");
Daniel Berlin7af95872016-08-05 21:47:20 +00001723
George Burgess IVe1100f52016-02-02 22:46:49 +00001724 for (Instruction &I : B) {
1725 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
1726 if (!MD)
1727 continue;
1728
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001729 for (const Use &U : MD->uses())
1730 assert(dominates(MD, U) && "Memory Def does not dominate it's uses");
George Burgess IVe1100f52016-02-02 22:46:49 +00001731 }
1732 }
Daniel Berlin7af95872016-08-05 21:47:20 +00001733#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001734}
1735
1736/// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use
1737/// appears in the use list of \p Def.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001738void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001739#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001740 // The live on entry use may cause us to get a NULL def here
Daniel Berlin7af95872016-08-05 21:47:20 +00001741 if (!Def)
1742 assert(isLiveOnEntryDef(Use) &&
1743 "Null def but use not point to live on entry def");
1744 else
Daniel Berlinda2f38e2016-08-11 21:26:50 +00001745 assert(is_contained(Def->users(), Use) &&
Daniel Berlin7af95872016-08-05 21:47:20 +00001746 "Did not find use in def's use list");
1747#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001748}
1749
1750/// \brief Verify the immediate use information, by walking all the memory
1751/// accesses and verifying that, for each use, it appears in the
1752/// appropriate def's use list
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001753void MemorySSA::verifyDefUses(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001754 for (BasicBlock &B : F) {
1755 // Phi nodes are attached to basic blocks
Daniel Berlin14300262016-06-21 18:39:20 +00001756 if (MemoryPhi *Phi = getMemoryAccess(&B)) {
David Majnemer580e7542016-06-25 00:04:06 +00001757 assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
1758 pred_begin(&B), pred_end(&B))) &&
Daniel Berlin14300262016-06-21 18:39:20 +00001759 "Incomplete MemoryPhi Node");
George Burgess IVe1100f52016-02-02 22:46:49 +00001760 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
1761 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
Daniel Berlin14300262016-06-21 18:39:20 +00001762 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001763
1764 for (Instruction &I : B) {
George Burgess IV66837ab2016-11-01 21:17:46 +00001765 if (MemoryUseOrDef *MA = getMemoryAccess(&I)) {
1766 verifyUseInDefs(MA->getDefiningAccess(), MA);
George Burgess IVe1100f52016-02-02 22:46:49 +00001767 }
1768 }
1769 }
1770}
1771
George Burgess IV66837ab2016-11-01 21:17:46 +00001772MemoryUseOrDef *MemorySSA::getMemoryAccess(const Instruction *I) const {
1773 return cast_or_null<MemoryUseOrDef>(ValueToMemoryAccess.lookup(I));
George Burgess IVe1100f52016-02-02 22:46:49 +00001774}
1775
1776MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const {
George Burgess IV66837ab2016-11-01 21:17:46 +00001777 return cast_or_null<MemoryPhi>(ValueToMemoryAccess.lookup(cast<Value>(BB)));
George Burgess IVe1100f52016-02-02 22:46:49 +00001778}
1779
Daniel Berlin5c46b942016-07-19 22:49:43 +00001780/// Perform a local numbering on blocks so that instruction ordering can be
1781/// determined in constant time.
1782/// TODO: We currently just number in order. If we numbered by N, we could
1783/// allow at least N-1 sequences of insertBefore or insertAfter (and at least
1784/// log2(N) sequences of mixed before and after) without needing to invalidate
1785/// the numbering.
1786void MemorySSA::renumberBlock(const BasicBlock *B) const {
1787 // The pre-increment ensures the numbers really start at 1.
1788 unsigned long CurrentNumber = 0;
1789 const AccessList *AL = getBlockAccesses(B);
1790 assert(AL != nullptr && "Asking to renumber an empty block");
1791 for (const auto &I : *AL)
1792 BlockNumbering[&I] = ++CurrentNumber;
1793 BlockNumberingValid.insert(B);
1794}
1795
George Burgess IVe1100f52016-02-02 22:46:49 +00001796/// \brief Determine, for two memory accesses in the same block,
1797/// whether \p Dominator dominates \p Dominatee.
1798/// \returns True if \p Dominator dominates \p Dominatee.
1799bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
1800 const MemoryAccess *Dominatee) const {
Daniel Berlin5c46b942016-07-19 22:49:43 +00001801 const BasicBlock *DominatorBlock = Dominator->getBlock();
Daniel Berlin5c46b942016-07-19 22:49:43 +00001802
Daniel Berlin19860302016-07-19 23:08:08 +00001803 assert((DominatorBlock == Dominatee->getBlock()) &&
Daniel Berlin5c46b942016-07-19 22:49:43 +00001804 "Asking for local domination when accesses are in different blocks!");
Sebastian Pope1f60b12016-06-10 21:36:41 +00001805 // A node dominates itself.
1806 if (Dominatee == Dominator)
1807 return true;
1808
1809 // When Dominatee is defined on function entry, it is not dominated by another
1810 // memory access.
1811 if (isLiveOnEntryDef(Dominatee))
1812 return false;
1813
1814 // When Dominator is defined on function entry, it dominates the other memory
1815 // access.
1816 if (isLiveOnEntryDef(Dominator))
1817 return true;
1818
Daniel Berlin5c46b942016-07-19 22:49:43 +00001819 if (!BlockNumberingValid.count(DominatorBlock))
1820 renumberBlock(DominatorBlock);
George Burgess IVe1100f52016-02-02 22:46:49 +00001821
Daniel Berlin5c46b942016-07-19 22:49:43 +00001822 unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
1823 // All numbers start with 1
1824 assert(DominatorNum != 0 && "Block was not numbered properly");
1825 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
1826 assert(DominateeNum != 0 && "Block was not numbered properly");
1827 return DominatorNum < DominateeNum;
George Burgess IVe1100f52016-02-02 22:46:49 +00001828}
1829
George Burgess IV5f308972016-07-19 01:29:15 +00001830bool MemorySSA::dominates(const MemoryAccess *Dominator,
1831 const MemoryAccess *Dominatee) const {
1832 if (Dominator == Dominatee)
1833 return true;
1834
1835 if (isLiveOnEntryDef(Dominatee))
1836 return false;
1837
1838 if (Dominator->getBlock() != Dominatee->getBlock())
1839 return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
1840 return locallyDominates(Dominator, Dominatee);
1841}
1842
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001843bool MemorySSA::dominates(const MemoryAccess *Dominator,
1844 const Use &Dominatee) const {
1845 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Dominatee.getUser())) {
1846 BasicBlock *UseBB = MP->getIncomingBlock(Dominatee);
1847 // The def must dominate the incoming block of the phi.
1848 if (UseBB != Dominator->getBlock())
1849 return DT->dominates(Dominator->getBlock(), UseBB);
1850 // If the UseBB and the DefBB are the same, compare locally.
1851 return locallyDominates(Dominator, cast<MemoryAccess>(Dominatee));
1852 }
1853 // If it's not a PHI node use, the normal dominates can already handle it.
1854 return dominates(Dominator, cast<MemoryAccess>(Dominatee.getUser()));
1855}
1856
George Burgess IVe1100f52016-02-02 22:46:49 +00001857const static char LiveOnEntryStr[] = "liveOnEntry";
1858
Reid Kleckner96ab8722017-05-18 17:24:10 +00001859void MemoryAccess::print(raw_ostream &OS) const {
1860 switch (getValueID()) {
1861 case MemoryPhiVal: return static_cast<const MemoryPhi *>(this)->print(OS);
1862 case MemoryDefVal: return static_cast<const MemoryDef *>(this)->print(OS);
1863 case MemoryUseVal: return static_cast<const MemoryUse *>(this)->print(OS);
1864 }
1865 llvm_unreachable("invalid value id");
1866}
1867
George Burgess IVe1100f52016-02-02 22:46:49 +00001868void MemoryDef::print(raw_ostream &OS) const {
1869 MemoryAccess *UO = getDefiningAccess();
1870
1871 OS << getID() << " = MemoryDef(";
1872 if (UO && UO->getID())
1873 OS << UO->getID();
1874 else
1875 OS << LiveOnEntryStr;
1876 OS << ')';
1877}
1878
1879void MemoryPhi::print(raw_ostream &OS) const {
1880 bool First = true;
1881 OS << getID() << " = MemoryPhi(";
1882 for (const auto &Op : operands()) {
1883 BasicBlock *BB = getIncomingBlock(Op);
1884 MemoryAccess *MA = cast<MemoryAccess>(Op);
1885 if (!First)
1886 OS << ',';
1887 else
1888 First = false;
1889
1890 OS << '{';
1891 if (BB->hasName())
1892 OS << BB->getName();
1893 else
1894 BB->printAsOperand(OS, false);
1895 OS << ',';
1896 if (unsigned ID = MA->getID())
1897 OS << ID;
1898 else
1899 OS << LiveOnEntryStr;
1900 OS << '}';
1901 }
1902 OS << ')';
1903}
1904
George Burgess IVe1100f52016-02-02 22:46:49 +00001905void MemoryUse::print(raw_ostream &OS) const {
1906 MemoryAccess *UO = getDefiningAccess();
1907 OS << "MemoryUse(";
1908 if (UO && UO->getID())
1909 OS << UO->getID();
1910 else
1911 OS << LiveOnEntryStr;
1912 OS << ')';
1913}
1914
1915void MemoryAccess::dump() const {
Daniel Berlin78cbd282017-02-20 22:26:03 +00001916// Cannot completely remove virtual function even in release mode.
Aaron Ballman615eb472017-10-15 14:32:27 +00001917#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
George Burgess IVe1100f52016-02-02 22:46:49 +00001918 print(dbgs());
1919 dbgs() << "\n";
Matthias Braun8c209aa2017-01-28 02:02:38 +00001920#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001921}
1922
Chad Rosier232e29e2016-07-06 21:20:47 +00001923char MemorySSAPrinterLegacyPass::ID = 0;
1924
1925MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) {
1926 initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
1927}
1928
1929void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
1930 AU.setPreservesAll();
1931 AU.addRequired<MemorySSAWrapperPass>();
Chad Rosier232e29e2016-07-06 21:20:47 +00001932}
1933
1934bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) {
1935 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
1936 MSSA.print(dbgs());
1937 if (VerifyMemorySSA)
1938 MSSA.verifyMemorySSA();
1939 return false;
1940}
1941
Chandler Carruthdab4eae2016-11-23 17:53:26 +00001942AnalysisKey MemorySSAAnalysis::Key;
George Burgess IVe1100f52016-02-02 22:46:49 +00001943
Daniel Berlin1e98c042016-09-26 17:22:54 +00001944MemorySSAAnalysis::Result MemorySSAAnalysis::run(Function &F,
1945 FunctionAnalysisManager &AM) {
Geoff Berryb96d3b22016-06-01 21:30:40 +00001946 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1947 auto &AA = AM.getResult<AAManager>(F);
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001948 return MemorySSAAnalysis::Result(llvm::make_unique<MemorySSA>(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00001949}
1950
Geoff Berryb96d3b22016-06-01 21:30:40 +00001951PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
1952 FunctionAnalysisManager &AM) {
1953 OS << "MemorySSA for function: " << F.getName() << "\n";
Geoff Berry290a13e2016-08-08 18:27:22 +00001954 AM.getResult<MemorySSAAnalysis>(F).getMSSA().print(OS);
Geoff Berryb96d3b22016-06-01 21:30:40 +00001955
1956 return PreservedAnalyses::all();
George Burgess IVe1100f52016-02-02 22:46:49 +00001957}
1958
Geoff Berryb96d3b22016-06-01 21:30:40 +00001959PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
1960 FunctionAnalysisManager &AM) {
Geoff Berry290a13e2016-08-08 18:27:22 +00001961 AM.getResult<MemorySSAAnalysis>(F).getMSSA().verifyMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001962
1963 return PreservedAnalyses::all();
1964}
1965
1966char MemorySSAWrapperPass::ID = 0;
1967
1968MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
1969 initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
1970}
1971
1972void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
1973
1974void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001975 AU.setPreservesAll();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001976 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
1977 AU.addRequiredTransitive<AAResultsWrapperPass>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001978}
1979
Geoff Berryb96d3b22016-06-01 21:30:40 +00001980bool MemorySSAWrapperPass::runOnFunction(Function &F) {
1981 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1982 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1983 MSSA.reset(new MemorySSA(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00001984 return false;
1985}
1986
Geoff Berryb96d3b22016-06-01 21:30:40 +00001987void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); }
George Burgess IVe1100f52016-02-02 22:46:49 +00001988
Geoff Berryb96d3b22016-06-01 21:30:40 +00001989void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001990 MSSA->print(OS);
1991}
1992
George Burgess IVe1100f52016-02-02 22:46:49 +00001993MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
1994
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001995MemorySSA::CachingWalker::CachingWalker(MemorySSA *M, AliasAnalysis *A,
1996 DominatorTree *D)
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001997 : MemorySSAWalker(M), Walker(*M, *A, *D) {}
George Burgess IVe1100f52016-02-02 22:46:49 +00001998
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001999void MemorySSA::CachingWalker::invalidateInfo(MemoryAccess *MA) {
Daniel Berlind7a7ae02017-04-05 19:01:58 +00002000 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
2001 MUD->resetOptimized();
Daniel Berlin83fc77b2016-03-01 18:46:54 +00002002}
2003
George Burgess IVe1100f52016-02-02 22:46:49 +00002004/// \brief Walk the use-def chains starting at \p MA and find
2005/// the MemoryAccess that actually clobbers Loc.
2006///
2007/// \returns our clobbering memory access
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002008MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
2009 MemoryAccess *StartingAccess, UpwardsMemoryQuery &Q) {
George Burgess IV0034e392018-04-09 23:09:27 +00002010 return Walker.findClobber(StartingAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00002011}
2012
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002013MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
George Burgess IV013fd732016-10-28 19:22:46 +00002014 MemoryAccess *StartingAccess, const MemoryLocation &Loc) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002015 if (isa<MemoryPhi>(StartingAccess))
2016 return StartingAccess;
2017
2018 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
2019 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
2020 return StartingUseOrDef;
2021
2022 Instruction *I = StartingUseOrDef->getMemoryInst();
2023
2024 // Conservatively, fences are always clobbers, so don't perform the walk if we
2025 // hit a fence.
David Majnemera940f362016-07-15 17:19:24 +00002026 if (!ImmutableCallSite(I) && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002027 return StartingUseOrDef;
2028
2029 UpwardsMemoryQuery Q;
2030 Q.OriginalAccess = StartingUseOrDef;
2031 Q.StartingLoc = Loc;
George Burgess IV5f308972016-07-19 01:29:15 +00002032 Q.Inst = I;
George Burgess IVe1100f52016-02-02 22:46:49 +00002033 Q.IsCall = false;
George Burgess IVe1100f52016-02-02 22:46:49 +00002034
George Burgess IVe1100f52016-02-02 22:46:49 +00002035 // Unlike the other function, do not walk to the def of a def, because we are
2036 // handed something we already believe is the clobbering access.
2037 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
2038 ? StartingUseOrDef->getDefiningAccess()
2039 : StartingUseOrDef;
2040
2041 MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00002042 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2043 DEBUG(dbgs() << *StartingUseOrDef << "\n");
2044 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2045 DEBUG(dbgs() << *Clobber << "\n");
2046 return Clobber;
2047}
2048
2049MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002050MemorySSA::CachingWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
2051 auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
2052 // If this is a MemoryPhi, we can't do anything.
2053 if (!StartingAccess)
2054 return MA;
George Burgess IVe1100f52016-02-02 22:46:49 +00002055
Daniel Berlincd2deac2016-10-20 20:13:45 +00002056 // If this is an already optimized use or def, return the optimized result.
Alina Sbirlead90c9f42018-03-08 18:03:14 +00002057 // Note: Currently, we store the optimized def result in a separate field,
2058 // since we can't use the defining access.
George Burgess IV6f49f4a2018-02-24 00:15:21 +00002059 if (StartingAccess->isOptimized())
2060 return StartingAccess->getOptimized();
Daniel Berlincd2deac2016-10-20 20:13:45 +00002061
George Burgess IV400ae402016-07-20 19:51:34 +00002062 const Instruction *I = StartingAccess->getMemoryInst();
George Burgess IV5f308972016-07-19 01:29:15 +00002063 UpwardsMemoryQuery Q(I, StartingAccess);
George Burgess IV44477c62018-03-11 04:16:12 +00002064 // We can't sanely do anything with a fence, since they conservatively clobber
2065 // all memory, and have no locations to get pointers from to try to
2066 // disambiguate.
George Burgess IV5f308972016-07-19 01:29:15 +00002067 if (!Q.IsCall && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002068 return StartingAccess;
2069
George Burgess IV024f3d22016-08-03 19:57:02 +00002070 if (isUseTriviallyOptimizableToLiveOnEntry(*MSSA->AA, I)) {
2071 MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef();
George Burgess IV44477c62018-03-11 04:16:12 +00002072 StartingAccess->setOptimized(LiveOnEntry);
2073 StartingAccess->setOptimizedAccessType(None);
George Burgess IV024f3d22016-08-03 19:57:02 +00002074 return LiveOnEntry;
2075 }
2076
George Burgess IVe1100f52016-02-02 22:46:49 +00002077 // Start with the thing we already think clobbers this location
2078 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
2079
2080 // At this point, DefiningAccess may be the live on entry def.
2081 // If it is, we will not get a better result.
Alina Sbirlead90c9f42018-03-08 18:03:14 +00002082 if (MSSA->isLiveOnEntryDef(DefiningAccess)) {
George Burgess IV44477c62018-03-11 04:16:12 +00002083 StartingAccess->setOptimized(DefiningAccess);
2084 StartingAccess->setOptimizedAccessType(None);
George Burgess IVe1100f52016-02-02 22:46:49 +00002085 return DefiningAccess;
Alina Sbirlead90c9f42018-03-08 18:03:14 +00002086 }
George Burgess IVe1100f52016-02-02 22:46:49 +00002087
2088 MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00002089 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2090 DEBUG(dbgs() << *DefiningAccess << "\n");
2091 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2092 DEBUG(dbgs() << *Result << "\n");
Alina Sbirlead90c9f42018-03-08 18:03:14 +00002093
George Burgess IV44477c62018-03-11 04:16:12 +00002094 StartingAccess->setOptimized(Result);
2095 if (MSSA->isLiveOnEntryDef(Result))
2096 StartingAccess->setOptimizedAccessType(None);
2097 else if (Q.AR == MustAlias)
2098 StartingAccess->setOptimizedAccessType(MustAlias);
George Burgess IVe1100f52016-02-02 22:46:49 +00002099
2100 return Result;
2101}
2102
George Burgess IVe1100f52016-02-02 22:46:49 +00002103MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002104DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002105 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
2106 return Use->getDefiningAccess();
2107 return MA;
2108}
2109
2110MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
George Burgess IV013fd732016-10-28 19:22:46 +00002111 MemoryAccess *StartingAccess, const MemoryLocation &) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002112 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
2113 return Use->getDefiningAccess();
2114 return StartingAccess;
2115}
Reid Kleckner96ab8722017-05-18 17:24:10 +00002116
2117void MemoryPhi::deleteMe(DerivedUser *Self) {
2118 delete static_cast<MemoryPhi *>(Self);
2119}
2120
2121void MemoryDef::deleteMe(DerivedUser *Self) {
2122 delete static_cast<MemoryDef *>(Self);
2123}
2124
2125void MemoryUse::deleteMe(DerivedUser *Self) {
2126 delete static_cast<MemoryUse *>(Self);
2127}