blob: ea68faa7fc7f96cc00f974a32d2d1ab850da4c41 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
George Burgess IVe1100f52016-02-02 22:46:49 +00006//
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00007//===----------------------------------------------------------------------===//
George Burgess IVe1100f52016-02-02 22:46:49 +00008//
9// This file implements the MemorySSA class.
10//
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000011//===----------------------------------------------------------------------===//
12
Daniel Berlin554dcd82017-04-11 20:06:36 +000013#include "llvm/Analysis/MemorySSA.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000014#include "llvm/ADT/DenseMap.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000015#include "llvm/ADT/DenseMapInfo.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000016#include "llvm/ADT/DenseSet.h"
17#include "llvm/ADT/DepthFirstIterator.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000018#include "llvm/ADT/Hashing.h"
19#include "llvm/ADT/None.h"
20#include "llvm/ADT/Optional.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000021#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000023#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/iterator.h"
25#include "llvm/ADT/iterator_range.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000026#include "llvm/Analysis/AliasAnalysis.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000027#include "llvm/Analysis/IteratedDominanceFrontier.h"
28#include "llvm/Analysis/MemoryLocation.h"
Nico Weber432a3882018-04-30 14:59:11 +000029#include "llvm/Config/llvm-config.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000030#include "llvm/IR/AssemblyAnnotationWriter.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000031#include "llvm/IR/BasicBlock.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000032#include "llvm/IR/Dominators.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000033#include "llvm/IR/Function.h"
34#include "llvm/IR/Instruction.h"
35#include "llvm/IR/Instructions.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000036#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000037#include "llvm/IR/Intrinsics.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000038#include "llvm/IR/LLVMContext.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000039#include "llvm/IR/PassManager.h"
40#include "llvm/IR/Use.h"
41#include "llvm/Pass.h"
42#include "llvm/Support/AtomicOrdering.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/CommandLine.h"
45#include "llvm/Support/Compiler.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000046#include "llvm/Support/Debug.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000047#include "llvm/Support/ErrorHandling.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000048#include "llvm/Support/FormattedStream.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000049#include "llvm/Support/raw_ostream.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000050#include <algorithm>
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000051#include <cassert>
52#include <iterator>
53#include <memory>
54#include <utility>
55
56using namespace llvm;
George Burgess IVe1100f52016-02-02 22:46:49 +000057
58#define DEBUG_TYPE "memoryssa"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000059
Geoff Berryefb0dd12016-06-14 21:19:40 +000060INITIALIZE_PASS_BEGIN(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
Geoff Berryb96d3b22016-06-01 21:30:40 +000061 true)
George Burgess IVe1100f52016-02-02 22:46:49 +000062INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
63INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Geoff Berryefb0dd12016-06-14 21:19:40 +000064INITIALIZE_PASS_END(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
65 true)
George Burgess IVe1100f52016-02-02 22:46:49 +000066
Chad Rosier232e29e2016-07-06 21:20:47 +000067INITIALIZE_PASS_BEGIN(MemorySSAPrinterLegacyPass, "print-memoryssa",
68 "Memory SSA Printer", false, false)
69INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
70INITIALIZE_PASS_END(MemorySSAPrinterLegacyPass, "print-memoryssa",
71 "Memory SSA Printer", false, false)
72
Daniel Berlinc43aa5a2016-08-02 16:24:03 +000073static cl::opt<unsigned> MaxCheckLimit(
74 "memssa-check-limit", cl::Hidden, cl::init(100),
75 cl::desc("The maximum number of stores/phis MemorySSA"
76 "will consider trying to walk past (default = 100)"));
77
Alina Sbirleacc2e8cc2018-08-15 17:34:55 +000078// Always verify MemorySSA if expensive checking is enabled.
79#ifdef EXPENSIVE_CHECKS
80bool llvm::VerifyMemorySSA = true;
81#else
82bool llvm::VerifyMemorySSA = false;
83#endif
84static cl::opt<bool, true>
85 VerifyMemorySSAX("verify-memoryssa", cl::location(VerifyMemorySSA),
86 cl::Hidden, cl::desc("Enable verification of MemorySSA."));
Chad Rosier232e29e2016-07-06 21:20:47 +000087
George Burgess IVe1100f52016-02-02 22:46:49 +000088namespace llvm {
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000089
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000090/// An assembly annotator class to print Memory SSA information in
George Burgess IVe1100f52016-02-02 22:46:49 +000091/// comments.
92class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter {
93 friend class MemorySSA;
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000094
George Burgess IVe1100f52016-02-02 22:46:49 +000095 const MemorySSA *MSSA;
96
97public:
98 MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {}
99
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000100 void emitBasicBlockStartAnnot(const BasicBlock *BB,
101 formatted_raw_ostream &OS) override {
George Burgess IVe1100f52016-02-02 22:46:49 +0000102 if (MemoryAccess *MA = MSSA->getMemoryAccess(BB))
103 OS << "; " << *MA << "\n";
104 }
105
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000106 void emitInstructionAnnot(const Instruction *I,
107 formatted_raw_ostream &OS) override {
George Burgess IVe1100f52016-02-02 22:46:49 +0000108 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
109 OS << "; " << *MA << "\n";
110 }
111};
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000112
113} // end namespace llvm
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000114
George Burgess IV5f308972016-07-19 01:29:15 +0000115namespace {
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000116
Daniel Berlindff31de2016-08-02 21:57:52 +0000117/// Our current alias analysis API differentiates heavily between calls and
118/// non-calls, and functions called on one usually assert on the other.
119/// This class encapsulates the distinction to simplify other code that wants
120/// "Memory affecting instructions and related data" to use as a key.
121/// For example, this class is used as a densemap key in the use optimizer.
122class MemoryLocOrCall {
123public:
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000124 bool IsCall = false;
125
Daniel Berlindff31de2016-08-02 21:57:52 +0000126 MemoryLocOrCall(MemoryUseOrDef *MUD)
127 : MemoryLocOrCall(MUD->getMemoryInst()) {}
Sebastian Pop5068d7a2016-10-13 03:23:33 +0000128 MemoryLocOrCall(const MemoryUseOrDef *MUD)
129 : MemoryLocOrCall(MUD->getMemoryInst()) {}
Daniel Berlindff31de2016-08-02 21:57:52 +0000130
131 MemoryLocOrCall(Instruction *Inst) {
Chandler Carruth363ac682019-01-07 05:42:51 +0000132 if (auto *C = dyn_cast<CallBase>(Inst)) {
Daniel Berlindff31de2016-08-02 21:57:52 +0000133 IsCall = true;
Chandler Carruth363ac682019-01-07 05:42:51 +0000134 Call = C;
Daniel Berlindff31de2016-08-02 21:57:52 +0000135 } else {
136 IsCall = false;
137 // There is no such thing as a memorylocation for a fence inst, and it is
138 // unique in that regard.
139 if (!isa<FenceInst>(Inst))
140 Loc = MemoryLocation::get(Inst);
141 }
142 }
143
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000144 explicit MemoryLocOrCall(const MemoryLocation &Loc) : Loc(Loc) {}
Daniel Berlindff31de2016-08-02 21:57:52 +0000145
Chandler Carruth363ac682019-01-07 05:42:51 +0000146 const CallBase *getCall() const {
Daniel Berlindff31de2016-08-02 21:57:52 +0000147 assert(IsCall);
Chandler Carruth363ac682019-01-07 05:42:51 +0000148 return Call;
Daniel Berlindff31de2016-08-02 21:57:52 +0000149 }
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000150
Daniel Berlindff31de2016-08-02 21:57:52 +0000151 MemoryLocation getLoc() const {
152 assert(!IsCall);
153 return Loc;
154 }
155
156 bool operator==(const MemoryLocOrCall &Other) const {
157 if (IsCall != Other.IsCall)
158 return false;
159
George Burgess IV3588fd42018-03-29 00:54:39 +0000160 if (!IsCall)
161 return Loc == Other.Loc;
162
Chandler Carruth363ac682019-01-07 05:42:51 +0000163 if (Call->getCalledValue() != Other.Call->getCalledValue())
George Burgess IV3588fd42018-03-29 00:54:39 +0000164 return false;
165
Chandler Carruth363ac682019-01-07 05:42:51 +0000166 return Call->arg_size() == Other.Call->arg_size() &&
167 std::equal(Call->arg_begin(), Call->arg_end(),
168 Other.Call->arg_begin());
Daniel Berlindff31de2016-08-02 21:57:52 +0000169 }
170
171private:
Daniel Berlinf5361132016-10-22 04:15:41 +0000172 union {
Chandler Carruth363ac682019-01-07 05:42:51 +0000173 const CallBase *Call;
Daniel Berlind602e042017-01-25 20:56:19 +0000174 MemoryLocation Loc;
Daniel Berlinf5361132016-10-22 04:15:41 +0000175 };
Daniel Berlindff31de2016-08-02 21:57:52 +0000176};
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000177
178} // end anonymous namespace
Daniel Berlindff31de2016-08-02 21:57:52 +0000179
180namespace llvm {
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000181
Daniel Berlindff31de2016-08-02 21:57:52 +0000182template <> struct DenseMapInfo<MemoryLocOrCall> {
183 static inline MemoryLocOrCall getEmptyKey() {
184 return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getEmptyKey());
185 }
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000186
Daniel Berlindff31de2016-08-02 21:57:52 +0000187 static inline MemoryLocOrCall getTombstoneKey() {
188 return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getTombstoneKey());
189 }
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000190
Daniel Berlindff31de2016-08-02 21:57:52 +0000191 static unsigned getHashValue(const MemoryLocOrCall &MLOC) {
George Burgess IV3588fd42018-03-29 00:54:39 +0000192 if (!MLOC.IsCall)
193 return hash_combine(
194 MLOC.IsCall,
195 DenseMapInfo<MemoryLocation>::getHashValue(MLOC.getLoc()));
196
197 hash_code hash =
198 hash_combine(MLOC.IsCall, DenseMapInfo<const Value *>::getHashValue(
Chandler Carruth363ac682019-01-07 05:42:51 +0000199 MLOC.getCall()->getCalledValue()));
George Burgess IV3588fd42018-03-29 00:54:39 +0000200
Chandler Carruth363ac682019-01-07 05:42:51 +0000201 for (const Value *Arg : MLOC.getCall()->args())
George Burgess IV3588fd42018-03-29 00:54:39 +0000202 hash = hash_combine(hash, DenseMapInfo<const Value *>::getHashValue(Arg));
203 return hash;
Daniel Berlindff31de2016-08-02 21:57:52 +0000204 }
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000205
Daniel Berlindff31de2016-08-02 21:57:52 +0000206 static bool isEqual(const MemoryLocOrCall &LHS, const MemoryLocOrCall &RHS) {
207 return LHS == RHS;
208 }
209};
Daniel Berlindf101192016-08-03 00:01:46 +0000210
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000211} // end namespace llvm
212
George Burgess IV82e355c2016-08-03 19:39:54 +0000213/// This does one-way checks to see if Use could theoretically be hoisted above
214/// MayClobber. This will not check the other way around.
215///
216/// This assumes that, for the purposes of MemorySSA, Use comes directly after
217/// MayClobber, with no potentially clobbering operations in between them.
218/// (Where potentially clobbering ops are memory barriers, aliased stores, etc.)
Alina Sbirleaca741a82017-12-22 19:54:03 +0000219static bool areLoadsReorderable(const LoadInst *Use,
220 const LoadInst *MayClobber) {
George Burgess IV82e355c2016-08-03 19:39:54 +0000221 bool VolatileUse = Use->isVolatile();
222 bool VolatileClobber = MayClobber->isVolatile();
223 // Volatile operations may never be reordered with other volatile operations.
224 if (VolatileUse && VolatileClobber)
Alina Sbirleaca741a82017-12-22 19:54:03 +0000225 return false;
226 // Otherwise, volatile doesn't matter here. From the language reference:
227 // 'optimizers may change the order of volatile operations relative to
228 // non-volatile operations.'"
George Burgess IV82e355c2016-08-03 19:39:54 +0000229
230 // If a load is seq_cst, it cannot be moved above other loads. If its ordering
231 // is weaker, it can be moved above other loads. We just need to be sure that
232 // MayClobber isn't an acquire load, because loads can't be moved above
233 // acquire loads.
234 //
235 // Note that this explicitly *does* allow the free reordering of monotonic (or
236 // weaker) loads of the same address.
237 bool SeqCstUse = Use->getOrdering() == AtomicOrdering::SequentiallyConsistent;
238 bool MayClobberIsAcquire = isAtLeastOrStrongerThan(MayClobber->getOrdering(),
239 AtomicOrdering::Acquire);
Alina Sbirleaca741a82017-12-22 19:54:03 +0000240 return !(SeqCstUse || MayClobberIsAcquire);
George Burgess IV82e355c2016-08-03 19:39:54 +0000241}
242
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000243namespace {
244
245struct ClobberAlias {
246 bool IsClobber;
247 Optional<AliasResult> AR;
248};
249
250} // end anonymous namespace
251
252// Return a pair of {IsClobber (bool), AR (AliasResult)}. It relies on AR being
253// ignored if IsClobber = false.
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000254template <typename AliasAnalysisType>
255static ClobberAlias
256instructionClobbersQuery(const MemoryDef *MD, const MemoryLocation &UseLoc,
257 const Instruction *UseInst, AliasAnalysisType &AA) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000258 Instruction *DefInst = MD->getMemoryInst();
259 assert(DefInst && "Defining instruction not actually an instruction");
Chandler Carruth363ac682019-01-07 05:42:51 +0000260 const auto *UseCall = dyn_cast<CallBase>(UseInst);
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000261 Optional<AliasResult> AR;
George Burgess IV5f308972016-07-19 01:29:15 +0000262
Daniel Berlindf101192016-08-03 00:01:46 +0000263 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) {
264 // These intrinsics will show up as affecting memory, but they are just
George Burgess IVff08c802018-08-10 05:14:43 +0000265 // markers, mostly.
266 //
267 // FIXME: We probably don't actually want MemorySSA to model these at all
268 // (including creating MemoryAccesses for them): we just end up inventing
269 // clobbers where they don't really exist at all. Please see D43269 for
270 // context.
Daniel Berlindf101192016-08-03 00:01:46 +0000271 switch (II->getIntrinsicID()) {
272 case Intrinsic::lifetime_start:
Chandler Carruth363ac682019-01-07 05:42:51 +0000273 if (UseCall)
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000274 return {false, NoAlias};
275 AR = AA.alias(MemoryLocation(II->getArgOperand(1)), UseLoc);
George Burgess IVff08c802018-08-10 05:14:43 +0000276 return {AR != NoAlias, AR};
Daniel Berlindf101192016-08-03 00:01:46 +0000277 case Intrinsic::lifetime_end:
278 case Intrinsic::invariant_start:
279 case Intrinsic::invariant_end:
280 case Intrinsic::assume:
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000281 return {false, NoAlias};
Daniel Berlindf101192016-08-03 00:01:46 +0000282 default:
283 break;
284 }
285 }
286
Chandler Carruth363ac682019-01-07 05:42:51 +0000287 if (UseCall) {
288 ModRefInfo I = AA.getModRefInfo(DefInst, UseCall);
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000289 AR = isMustSet(I) ? MustAlias : MayAlias;
290 return {isModOrRefSet(I), AR};
Hans Wennborg70e22d12017-11-21 18:00:01 +0000291 }
George Burgess IV82e355c2016-08-03 19:39:54 +0000292
Alina Sbirleaca741a82017-12-22 19:54:03 +0000293 if (auto *DefLoad = dyn_cast<LoadInst>(DefInst))
294 if (auto *UseLoad = dyn_cast<LoadInst>(UseInst))
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000295 return {!areLoadsReorderable(UseLoad, DefLoad), MayAlias};
George Burgess IV82e355c2016-08-03 19:39:54 +0000296
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000297 ModRefInfo I = AA.getModRefInfo(DefInst, UseLoc);
298 AR = isMustSet(I) ? MustAlias : MayAlias;
299 return {isModSet(I), AR};
Daniel Berlindff31de2016-08-02 21:57:52 +0000300}
301
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000302template <typename AliasAnalysisType>
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000303static ClobberAlias instructionClobbersQuery(MemoryDef *MD,
304 const MemoryUseOrDef *MU,
305 const MemoryLocOrCall &UseMLOC,
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000306 AliasAnalysisType &AA) {
Sebastian Pop5068d7a2016-10-13 03:23:33 +0000307 // FIXME: This is a temporary hack to allow a single instructionClobbersQuery
308 // to exist while MemoryLocOrCall is pushed through places.
309 if (UseMLOC.IsCall)
310 return instructionClobbersQuery(MD, MemoryLocation(), MU->getMemoryInst(),
311 AA);
312 return instructionClobbersQuery(MD, UseMLOC.getLoc(), MU->getMemoryInst(),
313 AA);
314}
315
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000316// Return true when MD may alias MU, return false otherwise.
Daniel Berlindcb004f2017-03-02 23:06:46 +0000317bool MemorySSAUtil::defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU,
318 AliasAnalysis &AA) {
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000319 return instructionClobbersQuery(MD, MU, MemoryLocOrCall(MU), AA).IsClobber;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000320}
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000321
322namespace {
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000323
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000324struct UpwardsMemoryQuery {
325 // True if our original query started off as a call
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000326 bool IsCall = false;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000327 // The pointer location we started the query with. This will be empty if
328 // IsCall is true.
329 MemoryLocation StartingLoc;
330 // This is the instruction we were querying about.
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000331 const Instruction *Inst = nullptr;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000332 // The MemoryAccess we actually got called with, used to test local domination
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000333 const MemoryAccess *OriginalAccess = nullptr;
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000334 Optional<AliasResult> AR = MayAlias;
Alina Sbirleaf7230202019-01-07 18:40:27 +0000335 bool SkipSelfAccess = false;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000336
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000337 UpwardsMemoryQuery() = default;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000338
339 UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access)
Chandler Carruth363ac682019-01-07 05:42:51 +0000340 : IsCall(isa<CallBase>(Inst)), Inst(Inst), OriginalAccess(Access) {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000341 if (!IsCall)
342 StartingLoc = MemoryLocation::get(Inst);
343 }
344};
345
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000346} // end anonymous namespace
347
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000348static bool lifetimeEndsAt(MemoryDef *MD, const MemoryLocation &Loc,
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000349 BatchAAResults &AA) {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000350 Instruction *Inst = MD->getMemoryInst();
351 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
352 switch (II->getIntrinsicID()) {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000353 case Intrinsic::lifetime_end:
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000354 return AA.alias(MemoryLocation(II->getArgOperand(1)), Loc) == MustAlias;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000355 default:
356 return false;
357 }
358 }
359 return false;
360}
361
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000362template <typename AliasAnalysisType>
363static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysisType &AA,
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000364 const Instruction *I) {
365 // If the memory can't be changed, then loads of the memory can't be
366 // clobbered.
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000367 return isa<LoadInst>(I) && (I->getMetadata(LLVMContext::MD_invariant_load) ||
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000368 AA.pointsToConstantMemory(MemoryLocation(
369 cast<LoadInst>(I)->getPointerOperand())));
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000370}
371
George Burgess IV5f308972016-07-19 01:29:15 +0000372/// Verifies that `Start` is clobbered by `ClobberAt`, and that nothing
373/// inbetween `Start` and `ClobberAt` can clobbers `Start`.
374///
375/// This is meant to be as simple and self-contained as possible. Because it
376/// uses no cache, etc., it can be relatively expensive.
377///
378/// \param Start The MemoryAccess that we want to walk from.
379/// \param ClobberAt A clobber for Start.
380/// \param StartLoc The MemoryLocation for Start.
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000381/// \param MSSA The MemorySSA instance that Start and ClobberAt belong to.
George Burgess IV5f308972016-07-19 01:29:15 +0000382/// \param Query The UpwardsMemoryQuery we used for our search.
383/// \param AA The AliasAnalysis we used for our search.
Alina Sbirlea65f385d2018-09-07 23:51:41 +0000384/// \param AllowImpreciseClobber Always false, unless we do relaxed verify.
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000385
386template <typename AliasAnalysisType>
Alina Sbirlead77edc02019-02-11 19:51:21 +0000387LLVM_ATTRIBUTE_UNUSED static void
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000388checkClobberSanity(const MemoryAccess *Start, MemoryAccess *ClobberAt,
George Burgess IV5f308972016-07-19 01:29:15 +0000389 const MemoryLocation &StartLoc, const MemorySSA &MSSA,
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000390 const UpwardsMemoryQuery &Query, AliasAnalysisType &AA,
Alina Sbirlea65f385d2018-09-07 23:51:41 +0000391 bool AllowImpreciseClobber = false) {
George Burgess IV5f308972016-07-19 01:29:15 +0000392 assert(MSSA.dominates(ClobberAt, Start) && "Clobber doesn't dominate start?");
393
394 if (MSSA.isLiveOnEntryDef(Start)) {
395 assert(MSSA.isLiveOnEntryDef(ClobberAt) &&
396 "liveOnEntry must clobber itself");
397 return;
398 }
399
George Burgess IV5f308972016-07-19 01:29:15 +0000400 bool FoundClobber = false;
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000401 DenseSet<ConstMemoryAccessPair> VisitedPhis;
402 SmallVector<ConstMemoryAccessPair, 8> Worklist;
George Burgess IV5f308972016-07-19 01:29:15 +0000403 Worklist.emplace_back(Start, StartLoc);
404 // Walk all paths from Start to ClobberAt, while looking for clobbers. If one
405 // is found, complain.
406 while (!Worklist.empty()) {
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000407 auto MAP = Worklist.pop_back_val();
George Burgess IV5f308972016-07-19 01:29:15 +0000408 // All we care about is that nothing from Start to ClobberAt clobbers Start.
409 // We learn nothing from revisiting nodes.
410 if (!VisitedPhis.insert(MAP).second)
411 continue;
412
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000413 for (const auto *MA : def_chain(MAP.first)) {
George Burgess IV5f308972016-07-19 01:29:15 +0000414 if (MA == ClobberAt) {
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000415 if (const auto *MD = dyn_cast<MemoryDef>(MA)) {
George Burgess IV5f308972016-07-19 01:29:15 +0000416 // instructionClobbersQuery isn't essentially free, so don't use `|=`,
417 // since it won't let us short-circuit.
418 //
419 // Also, note that this can't be hoisted out of the `Worklist` loop,
420 // since MD may only act as a clobber for 1 of N MemoryLocations.
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000421 FoundClobber = FoundClobber || MSSA.isLiveOnEntryDef(MD);
422 if (!FoundClobber) {
423 ClobberAlias CA =
424 instructionClobbersQuery(MD, MAP.second, Query.Inst, AA);
425 if (CA.IsClobber) {
426 FoundClobber = true;
427 // Not used: CA.AR;
428 }
429 }
George Burgess IV5f308972016-07-19 01:29:15 +0000430 }
431 break;
432 }
433
434 // We should never hit liveOnEntry, unless it's the clobber.
435 assert(!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?");
436
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000437 if (const auto *MD = dyn_cast<MemoryDef>(MA)) {
Alina Sbirlea5bce4d52018-08-29 22:38:51 +0000438 // If Start is a Def, skip self.
439 if (MD == Start)
440 continue;
441
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000442 assert(!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA)
443 .IsClobber &&
George Burgess IV5f308972016-07-19 01:29:15 +0000444 "Found clobber before reaching ClobberAt!");
445 continue;
446 }
447
Alina Sbirlea5bce4d52018-08-29 22:38:51 +0000448 if (const auto *MU = dyn_cast<MemoryUse>(MA)) {
Alina Sbirlea6edcc9e2018-08-29 23:20:29 +0000449 (void)MU;
Alina Sbirlea5bce4d52018-08-29 22:38:51 +0000450 assert (MU == Start &&
451 "Can only find use in def chain if Start is a use");
452 continue;
453 }
454
George Burgess IV5f308972016-07-19 01:29:15 +0000455 assert(isa<MemoryPhi>(MA));
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000456 Worklist.append(
457 upward_defs_begin({const_cast<MemoryAccess *>(MA), MAP.second}),
458 upward_defs_end());
George Burgess IV5f308972016-07-19 01:29:15 +0000459 }
460 }
461
Alina Sbirlea65f385d2018-09-07 23:51:41 +0000462 // If the verify is done following an optimization, it's possible that
463 // ClobberAt was a conservative clobbering, that we can now infer is not a
464 // true clobbering access. Don't fail the verify if that's the case.
465 // We do have accesses that claim they're optimized, but could be optimized
466 // further. Updating all these can be expensive, so allow it for now (FIXME).
467 if (AllowImpreciseClobber)
468 return;
469
George Burgess IV5f308972016-07-19 01:29:15 +0000470 // If ClobberAt is a MemoryPhi, we can assume something above it acted as a
471 // clobber. Otherwise, `ClobberAt` should've acted as a clobber at some point.
472 assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&
473 "ClobberAt never acted as a clobber");
474}
475
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000476namespace {
477
George Burgess IV5f308972016-07-19 01:29:15 +0000478/// Our algorithm for walking (and trying to optimize) clobbers, all wrapped up
479/// in one class.
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000480template <class AliasAnalysisType> class ClobberWalker {
George Burgess IV5f308972016-07-19 01:29:15 +0000481 /// Save a few bytes by using unsigned instead of size_t.
482 using ListIndex = unsigned;
483
484 /// Represents a span of contiguous MemoryDefs, potentially ending in a
485 /// MemoryPhi.
486 struct DefPath {
487 MemoryLocation Loc;
488 // Note that, because we always walk in reverse, Last will always dominate
489 // First. Also note that First and Last are inclusive.
490 MemoryAccess *First;
491 MemoryAccess *Last;
George Burgess IV5f308972016-07-19 01:29:15 +0000492 Optional<ListIndex> Previous;
493
494 DefPath(const MemoryLocation &Loc, MemoryAccess *First, MemoryAccess *Last,
495 Optional<ListIndex> Previous)
496 : Loc(Loc), First(First), Last(Last), Previous(Previous) {}
497
498 DefPath(const MemoryLocation &Loc, MemoryAccess *Init,
499 Optional<ListIndex> Previous)
500 : DefPath(Loc, Init, Init, Previous) {}
501 };
502
503 const MemorySSA &MSSA;
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000504 AliasAnalysisType &AA;
George Burgess IV5f308972016-07-19 01:29:15 +0000505 DominatorTree &DT;
George Burgess IV5f308972016-07-19 01:29:15 +0000506 UpwardsMemoryQuery *Query;
George Burgess IV5f308972016-07-19 01:29:15 +0000507
508 // Phi optimization bookkeeping
509 SmallVector<DefPath, 32> Paths;
510 DenseSet<ConstMemoryAccessPair> VisitedPhis;
George Burgess IV5f308972016-07-19 01:29:15 +0000511
George Burgess IV5f308972016-07-19 01:29:15 +0000512 /// Find the nearest def or phi that `From` can legally be optimized to.
Daniel Berlind0420312017-04-01 09:01:12 +0000513 const MemoryAccess *getWalkTarget(const MemoryPhi *From) const {
George Burgess IV5f308972016-07-19 01:29:15 +0000514 assert(From->getNumOperands() && "Phi with no operands?");
515
516 BasicBlock *BB = From->getBlock();
George Burgess IV5f308972016-07-19 01:29:15 +0000517 MemoryAccess *Result = MSSA.getLiveOnEntryDef();
518 DomTreeNode *Node = DT.getNode(BB);
519 while ((Node = Node->getIDom())) {
Daniel Berlin7500c562017-04-01 08:59:45 +0000520 auto *Defs = MSSA.getBlockDefs(Node->getBlock());
521 if (Defs)
Daniel Berlind0420312017-04-01 09:01:12 +0000522 return &*Defs->rbegin();
George Burgess IV5f308972016-07-19 01:29:15 +0000523 }
George Burgess IV5f308972016-07-19 01:29:15 +0000524 return Result;
525 }
526
527 /// Result of calling walkToPhiOrClobber.
528 struct UpwardsWalkResult {
529 /// The "Result" of the walk. Either a clobber, the last thing we walked, or
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000530 /// both. Include alias info when clobber found.
George Burgess IV5f308972016-07-19 01:29:15 +0000531 MemoryAccess *Result;
532 bool IsKnownClobber;
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000533 Optional<AliasResult> AR;
George Burgess IV5f308972016-07-19 01:29:15 +0000534 };
535
536 /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last.
537 /// This will update Desc.Last as it walks. It will (optionally) also stop at
538 /// StopAt.
539 ///
540 /// This does not test for whether StopAt is a clobber
Daniel Berlind0420312017-04-01 09:01:12 +0000541 UpwardsWalkResult
Alina Sbirleaf7230202019-01-07 18:40:27 +0000542 walkToPhiOrClobber(DefPath &Desc, const MemoryAccess *StopAt = nullptr,
543 const MemoryAccess *SkipStopAt = nullptr) const {
George Burgess IV5f308972016-07-19 01:29:15 +0000544 assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");
545
546 for (MemoryAccess *Current : def_chain(Desc.Last)) {
547 Desc.Last = Current;
Alina Sbirleaf7230202019-01-07 18:40:27 +0000548 if (Current == StopAt || Current == SkipStopAt)
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000549 return {Current, false, MayAlias};
George Burgess IV5f308972016-07-19 01:29:15 +0000550
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000551 if (auto *MD = dyn_cast<MemoryDef>(Current)) {
552 if (MSSA.isLiveOnEntryDef(MD))
553 return {MD, true, MustAlias};
554 ClobberAlias CA =
555 instructionClobbersQuery(MD, Desc.Loc, Query->Inst, AA);
556 if (CA.IsClobber)
557 return {MD, true, CA.AR};
558 }
George Burgess IV5f308972016-07-19 01:29:15 +0000559 }
560
561 assert(isa<MemoryPhi>(Desc.Last) &&
562 "Ended at a non-clobber that's not a phi?");
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000563 return {Desc.Last, false, MayAlias};
George Burgess IV5f308972016-07-19 01:29:15 +0000564 }
565
566 void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches,
567 ListIndex PriorNode) {
568 auto UpwardDefs = make_range(upward_defs_begin({Phi, Paths[PriorNode].Loc}),
569 upward_defs_end());
570 for (const MemoryAccessPair &P : UpwardDefs) {
571 PausedSearches.push_back(Paths.size());
572 Paths.emplace_back(P.second, P.first, PriorNode);
573 }
574 }
575
576 /// Represents a search that terminated after finding a clobber. This clobber
577 /// may or may not be present in the path of defs from LastNode..SearchStart,
578 /// since it may have been retrieved from cache.
579 struct TerminatedPath {
580 MemoryAccess *Clobber;
581 ListIndex LastNode;
582 };
583
584 /// Get an access that keeps us from optimizing to the given phi.
585 ///
586 /// PausedSearches is an array of indices into the Paths array. Its incoming
587 /// value is the indices of searches that stopped at the last phi optimization
588 /// target. It's left in an unspecified state.
589 ///
590 /// If this returns None, NewPaused is a vector of searches that terminated
591 /// at StopWhere. Otherwise, NewPaused is left in an unspecified state.
George Burgess IV14633b52016-08-03 01:22:19 +0000592 Optional<TerminatedPath>
Daniel Berlind0420312017-04-01 09:01:12 +0000593 getBlockingAccess(const MemoryAccess *StopWhere,
George Burgess IV5f308972016-07-19 01:29:15 +0000594 SmallVectorImpl<ListIndex> &PausedSearches,
595 SmallVectorImpl<ListIndex> &NewPaused,
596 SmallVectorImpl<TerminatedPath> &Terminated) {
597 assert(!PausedSearches.empty() && "No searches to continue?");
598
599 // BFS vs DFS really doesn't make a difference here, so just do a DFS with
600 // PausedSearches as our stack.
601 while (!PausedSearches.empty()) {
602 ListIndex PathIndex = PausedSearches.pop_back_val();
603 DefPath &Node = Paths[PathIndex];
604
605 // If we've already visited this path with this MemoryLocation, we don't
606 // need to do so again.
607 //
608 // NOTE: That we just drop these paths on the ground makes caching
609 // behavior sporadic. e.g. given a diamond:
610 // A
611 // B C
612 // D
613 //
614 // ...If we walk D, B, A, C, we'll only cache the result of phi
615 // optimization for A, B, and D; C will be skipped because it dies here.
616 // This arguably isn't the worst thing ever, since:
617 // - We generally query things in a top-down order, so if we got below D
618 // without needing cache entries for {C, MemLoc}, then chances are
619 // that those cache entries would end up ultimately unused.
620 // - We still cache things for A, so C only needs to walk up a bit.
621 // If this behavior becomes problematic, we can fix without a ton of extra
622 // work.
623 if (!VisitedPhis.insert({Node.Last, Node.Loc}).second)
624 continue;
625
Alina Sbirleaf7230202019-01-07 18:40:27 +0000626 const MemoryAccess *SkipStopWhere = nullptr;
627 if (Query->SkipSelfAccess && Node.Loc == Query->StartingLoc) {
628 assert(isa<MemoryDef>(Query->OriginalAccess));
629 SkipStopWhere = Query->OriginalAccess;
630 }
631
632 UpwardsWalkResult Res = walkToPhiOrClobber(Node, /*StopAt=*/StopWhere,
633 /*SkipStopAt=*/SkipStopWhere);
George Burgess IV5f308972016-07-19 01:29:15 +0000634 if (Res.IsKnownClobber) {
Alina Sbirleaf7230202019-01-07 18:40:27 +0000635 assert(Res.Result != StopWhere && Res.Result != SkipStopWhere);
George Burgess IV5f308972016-07-19 01:29:15 +0000636 // If this wasn't a cache hit, we hit a clobber when walking. That's a
637 // failure.
George Burgess IV14633b52016-08-03 01:22:19 +0000638 TerminatedPath Term{Res.Result, PathIndex};
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000639 if (!MSSA.dominates(Res.Result, StopWhere))
George Burgess IV14633b52016-08-03 01:22:19 +0000640 return Term;
George Burgess IV5f308972016-07-19 01:29:15 +0000641
642 // Otherwise, it's a valid thing to potentially optimize to.
George Burgess IV14633b52016-08-03 01:22:19 +0000643 Terminated.push_back(Term);
George Burgess IV5f308972016-07-19 01:29:15 +0000644 continue;
645 }
646
Alina Sbirleaf7230202019-01-07 18:40:27 +0000647 if (Res.Result == StopWhere || Res.Result == SkipStopWhere) {
George Burgess IV5f308972016-07-19 01:29:15 +0000648 // We've hit our target. Save this path off for if we want to continue
Alina Sbirleaf7230202019-01-07 18:40:27 +0000649 // walking. If we are in the mode of skipping the OriginalAccess, and
650 // we've reached back to the OriginalAccess, do not save path, we've
651 // just looped back to self.
652 if (Res.Result != SkipStopWhere)
653 NewPaused.push_back(PathIndex);
George Burgess IV5f308972016-07-19 01:29:15 +0000654 continue;
655 }
656
657 assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");
658 addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
659 }
660
661 return None;
662 }
663
664 template <typename T, typename Walker>
665 struct generic_def_path_iterator
666 : public iterator_facade_base<generic_def_path_iterator<T, Walker>,
667 std::forward_iterator_tag, T *> {
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000668 generic_def_path_iterator() = default;
George Burgess IV5f308972016-07-19 01:29:15 +0000669 generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}
670
671 T &operator*() const { return curNode(); }
672
673 generic_def_path_iterator &operator++() {
674 N = curNode().Previous;
675 return *this;
676 }
677
678 bool operator==(const generic_def_path_iterator &O) const {
679 if (N.hasValue() != O.N.hasValue())
680 return false;
681 return !N.hasValue() || *N == *O.N;
682 }
683
684 private:
685 T &curNode() const { return W->Paths[*N]; }
686
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000687 Walker *W = nullptr;
688 Optional<ListIndex> N = None;
George Burgess IV5f308972016-07-19 01:29:15 +0000689 };
690
691 using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
692 using const_def_path_iterator =
693 generic_def_path_iterator<const DefPath, const ClobberWalker>;
694
695 iterator_range<def_path_iterator> def_path(ListIndex From) {
696 return make_range(def_path_iterator(this, From), def_path_iterator());
697 }
698
699 iterator_range<const_def_path_iterator> const_def_path(ListIndex From) const {
700 return make_range(const_def_path_iterator(this, From),
701 const_def_path_iterator());
702 }
703
704 struct OptznResult {
705 /// The path that contains our result.
706 TerminatedPath PrimaryClobber;
707 /// The paths that we can legally cache back from, but that aren't
708 /// necessarily the result of the Phi optimization.
709 SmallVector<TerminatedPath, 4> OtherClobbers;
710 };
711
712 ListIndex defPathIndex(const DefPath &N) const {
713 // The assert looks nicer if we don't need to do &N
714 const DefPath *NP = &N;
715 assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
716 "Out of bounds DefPath!");
717 return NP - &Paths.front();
718 }
719
720 /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths
721 /// that act as legal clobbers. Note that this won't return *all* clobbers.
722 ///
723 /// Phi optimization algorithm tl;dr:
724 /// - Find the earliest def/phi, A, we can optimize to
725 /// - Find if all paths from the starting memory access ultimately reach A
726 /// - If not, optimization isn't possible.
727 /// - Otherwise, walk from A to another clobber or phi, A'.
728 /// - If A' is a def, we're done.
729 /// - If A' is a phi, try to optimize it.
730 ///
731 /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path
732 /// terminates when a MemoryAccess that clobbers said MemoryLocation is found.
733 OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start,
734 const MemoryLocation &Loc) {
735 assert(Paths.empty() && VisitedPhis.empty() &&
736 "Reset the optimization state.");
737
738 Paths.emplace_back(Loc, Start, Phi, None);
739 // Stores how many "valid" optimization nodes we had prior to calling
740 // addSearches/getBlockingAccess. Necessary for caching if we had a blocker.
741 auto PriorPathsSize = Paths.size();
742
743 SmallVector<ListIndex, 16> PausedSearches;
744 SmallVector<ListIndex, 8> NewPaused;
745 SmallVector<TerminatedPath, 4> TerminatedPaths;
746
747 addSearches(Phi, PausedSearches, 0);
748
749 // Moves the TerminatedPath with the "most dominated" Clobber to the end of
750 // Paths.
751 auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
752 assert(!Paths.empty() && "Need a path to move");
George Burgess IV5f308972016-07-19 01:29:15 +0000753 auto Dom = Paths.begin();
754 for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I)
755 if (!MSSA.dominates(I->Clobber, Dom->Clobber))
756 Dom = I;
757 auto Last = Paths.end() - 1;
758 if (Last != Dom)
759 std::iter_swap(Last, Dom);
760 };
761
762 MemoryPhi *Current = Phi;
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000763 while (true) {
George Burgess IV5f308972016-07-19 01:29:15 +0000764 assert(!MSSA.isLiveOnEntryDef(Current) &&
765 "liveOnEntry wasn't treated as a clobber?");
766
Daniel Berlind0420312017-04-01 09:01:12 +0000767 const auto *Target = getWalkTarget(Current);
George Burgess IV5f308972016-07-19 01:29:15 +0000768 // If a TerminatedPath doesn't dominate Target, then it wasn't a legal
769 // optimization for the prior phi.
770 assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {
771 return MSSA.dominates(P.Clobber, Target);
772 }));
773
774 // FIXME: This is broken, because the Blocker may be reported to be
775 // liveOnEntry, and we'll happily wait for that to disappear (read: never)
George Burgess IV7f414b92016-08-22 23:40:01 +0000776 // For the moment, this is fine, since we do nothing with blocker info.
George Burgess IV14633b52016-08-03 01:22:19 +0000777 if (Optional<TerminatedPath> Blocker = getBlockingAccess(
George Burgess IV5f308972016-07-19 01:29:15 +0000778 Target, PausedSearches, NewPaused, TerminatedPaths)) {
George Burgess IV5f308972016-07-19 01:29:15 +0000779
780 // Find the node we started at. We can't search based on N->Last, since
781 // we may have gone around a loop with a different MemoryLocation.
George Burgess IV14633b52016-08-03 01:22:19 +0000782 auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) {
George Burgess IV5f308972016-07-19 01:29:15 +0000783 return defPathIndex(N) < PriorPathsSize;
784 });
785 assert(Iter != def_path_iterator());
786
787 DefPath &CurNode = *Iter;
788 assert(CurNode.Last == Current);
George Burgess IV5f308972016-07-19 01:29:15 +0000789
790 // Two things:
791 // A. We can't reliably cache all of NewPaused back. Consider a case
792 // where we have two paths in NewPaused; one of which can't optimize
793 // above this phi, whereas the other can. If we cache the second path
794 // back, we'll end up with suboptimal cache entries. We can handle
795 // cases like this a bit better when we either try to find all
796 // clobbers that block phi optimization, or when our cache starts
797 // supporting unfinished searches.
798 // B. We can't reliably cache TerminatedPaths back here without doing
799 // extra checks; consider a case like:
800 // T
801 // / \
802 // D C
803 // \ /
804 // S
805 // Where T is our target, C is a node with a clobber on it, D is a
806 // diamond (with a clobber *only* on the left or right node, N), and
807 // S is our start. Say we walk to D, through the node opposite N
808 // (read: ignoring the clobber), and see a cache entry in the top
809 // node of D. That cache entry gets put into TerminatedPaths. We then
810 // walk up to C (N is later in our worklist), find the clobber, and
811 // quit. If we append TerminatedPaths to OtherClobbers, we'll cache
812 // the bottom part of D to the cached clobber, ignoring the clobber
813 // in N. Again, this problem goes away if we start tracking all
814 // blockers for a given phi optimization.
815 TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
816 return {Result, {}};
817 }
818
819 // If there's nothing left to search, then all paths led to valid clobbers
820 // that we got from our cache; pick the nearest to the start, and allow
821 // the rest to be cached back.
822 if (NewPaused.empty()) {
823 MoveDominatedPathToEnd(TerminatedPaths);
824 TerminatedPath Result = TerminatedPaths.pop_back_val();
825 return {Result, std::move(TerminatedPaths)};
826 }
827
828 MemoryAccess *DefChainEnd = nullptr;
829 SmallVector<TerminatedPath, 4> Clobbers;
830 for (ListIndex Paused : NewPaused) {
831 UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
832 if (WR.IsKnownClobber)
833 Clobbers.push_back({WR.Result, Paused});
834 else
835 // Micro-opt: If we hit the end of the chain, save it.
836 DefChainEnd = WR.Result;
837 }
838
839 if (!TerminatedPaths.empty()) {
840 // If we couldn't find the dominating phi/liveOnEntry in the above loop,
841 // do it now.
842 if (!DefChainEnd)
Daniel Berlind0420312017-04-01 09:01:12 +0000843 for (auto *MA : def_chain(const_cast<MemoryAccess *>(Target)))
George Burgess IV5f308972016-07-19 01:29:15 +0000844 DefChainEnd = MA;
845
846 // If any of the terminated paths don't dominate the phi we'll try to
847 // optimize, we need to figure out what they are and quit.
848 const BasicBlock *ChainBB = DefChainEnd->getBlock();
849 for (const TerminatedPath &TP : TerminatedPaths) {
850 // Because we know that DefChainEnd is as "high" as we can go, we
851 // don't need local dominance checks; BB dominance is sufficient.
852 if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
853 Clobbers.push_back(TP);
854 }
855 }
856
857 // If we have clobbers in the def chain, find the one closest to Current
858 // and quit.
859 if (!Clobbers.empty()) {
860 MoveDominatedPathToEnd(Clobbers);
861 TerminatedPath Result = Clobbers.pop_back_val();
862 return {Result, std::move(Clobbers)};
863 }
864
865 assert(all_of(NewPaused,
866 [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
867
868 // Because liveOnEntry is a clobber, this must be a phi.
869 auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
870
871 PriorPathsSize = Paths.size();
872 PausedSearches.clear();
873 for (ListIndex I : NewPaused)
874 addSearches(DefChainPhi, PausedSearches, I);
875 NewPaused.clear();
876
877 Current = DefChainPhi;
878 }
879 }
880
George Burgess IV5f308972016-07-19 01:29:15 +0000881 void verifyOptResult(const OptznResult &R) const {
882 assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
883 return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
884 }));
885 }
886
887 void resetPhiOptznState() {
888 Paths.clear();
889 VisitedPhis.clear();
890 }
891
892public:
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000893 ClobberWalker(const MemorySSA &MSSA, AliasAnalysisType &AA, DominatorTree &DT)
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000894 : MSSA(MSSA), AA(AA), DT(DT) {}
George Burgess IV5f308972016-07-19 01:29:15 +0000895
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000896 AliasAnalysisType *getAA() { return &AA; }
George Burgess IV5f308972016-07-19 01:29:15 +0000897 /// Finds the nearest clobber for the given query, optimizing phis if
898 /// possible.
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000899 MemoryAccess *findClobber(MemoryAccess *Start, UpwardsMemoryQuery &Q) {
George Burgess IV5f308972016-07-19 01:29:15 +0000900 Query = &Q;
901
902 MemoryAccess *Current = Start;
903 // This walker pretends uses don't exist. If we're handed one, silently grab
904 // its def. (This has the nice side-effect of ensuring we never cache uses)
905 if (auto *MU = dyn_cast<MemoryUse>(Start))
906 Current = MU->getDefiningAccess();
907
908 DefPath FirstDesc(Q.StartingLoc, Current, Current, None);
909 // Fast path for the overly-common case (no crazy phi optimization
910 // necessary)
911 UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
George Burgess IV93ea19b2016-07-24 07:03:49 +0000912 MemoryAccess *Result;
George Burgess IV5f308972016-07-19 01:29:15 +0000913 if (WalkResult.IsKnownClobber) {
George Burgess IV93ea19b2016-07-24 07:03:49 +0000914 Result = WalkResult.Result;
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000915 Q.AR = WalkResult.AR;
George Burgess IV93ea19b2016-07-24 07:03:49 +0000916 } else {
917 OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
918 Current, Q.StartingLoc);
919 verifyOptResult(OptRes);
George Burgess IV93ea19b2016-07-24 07:03:49 +0000920 resetPhiOptznState();
921 Result = OptRes.PrimaryClobber.Clobber;
George Burgess IV5f308972016-07-19 01:29:15 +0000922 }
923
George Burgess IV5f308972016-07-19 01:29:15 +0000924#ifdef EXPENSIVE_CHECKS
Alina Sbirleae41f4b32019-01-10 21:47:15 +0000925 if (!Q.SkipSelfAccess)
926 checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, AA);
George Burgess IV5f308972016-07-19 01:29:15 +0000927#endif
George Burgess IV93ea19b2016-07-24 07:03:49 +0000928 return Result;
George Burgess IV5f308972016-07-19 01:29:15 +0000929 }
930};
931
932struct RenamePassData {
933 DomTreeNode *DTN;
934 DomTreeNode::const_iterator ChildIt;
935 MemoryAccess *IncomingVal;
936
937 RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
938 MemoryAccess *M)
939 : DTN(D), ChildIt(It), IncomingVal(M) {}
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000940
George Burgess IV5f308972016-07-19 01:29:15 +0000941 void swap(RenamePassData &RHS) {
942 std::swap(DTN, RHS.DTN);
943 std::swap(ChildIt, RHS.ChildIt);
944 std::swap(IncomingVal, RHS.IncomingVal);
945 }
946};
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000947
948} // end anonymous namespace
George Burgess IV5f308972016-07-19 01:29:15 +0000949
950namespace llvm {
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000951
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000952template <class AliasAnalysisType> class MemorySSA::ClobberWalkerBase {
953 ClobberWalker<AliasAnalysisType> Walker;
Alina Sbirleabc8aa242019-01-07 19:22:37 +0000954 MemorySSA *MSSA;
955
956public:
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000957 ClobberWalkerBase(MemorySSA *M, AliasAnalysisType *A, DominatorTree *D)
Alina Sbirleabc8aa242019-01-07 19:22:37 +0000958 : Walker(*M, *A, *D), MSSA(M) {}
959
960 MemoryAccess *getClobberingMemoryAccessBase(MemoryAccess *,
961 const MemoryLocation &);
962 // Second argument (bool), defines whether the clobber search should skip the
963 // original queried access. If true, there will be a follow-up query searching
964 // for a clobber access past "self". Note that the Optimized access is not
965 // updated if a new clobber is found by this SkipSelf search. If this
966 // additional query becomes heavily used we may decide to cache the result.
967 // Walker instantiations will decide how to set the SkipSelf bool.
968 MemoryAccess *getClobberingMemoryAccessBase(MemoryAccess *, bool);
Alina Sbirleabc8aa242019-01-07 19:22:37 +0000969};
970
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000971/// A MemorySSAWalker that does AA walks to disambiguate accesses. It no
George Burgess IV45f263d2018-05-26 02:28:55 +0000972/// longer does caching on its own, but the name has been retained for the
973/// moment.
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000974template <class AliasAnalysisType>
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000975class MemorySSA::CachingWalker final : public MemorySSAWalker {
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000976 ClobberWalkerBase<AliasAnalysisType> *Walker;
George Burgess IV5f308972016-07-19 01:29:15 +0000977
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000978public:
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000979 CachingWalker(MemorySSA *M, ClobberWalkerBase<AliasAnalysisType> *W)
Alina Sbirleabc8aa242019-01-07 19:22:37 +0000980 : MemorySSAWalker(M), Walker(W) {}
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000981 ~CachingWalker() override = default;
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000982
George Burgess IV400ae402016-07-20 19:51:34 +0000983 using MemorySSAWalker::getClobberingMemoryAccess;
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000984
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000985 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA) override {
986 return Walker->getClobberingMemoryAccessBase(MA, false);
987 }
Alina Sbirleabc8aa242019-01-07 19:22:37 +0000988 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000989 const MemoryLocation &Loc) override {
990 return Walker->getClobberingMemoryAccessBase(MA, Loc);
991 }
Alina Sbirleabc8aa242019-01-07 19:22:37 +0000992
993 void invalidateInfo(MemoryAccess *MA) override {
994 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
995 MUD->resetOptimized();
996 }
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000997};
George Burgess IVe1100f52016-02-02 22:46:49 +0000998
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000999template <class AliasAnalysisType>
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001000class MemorySSA::SkipSelfWalker final : public MemorySSAWalker {
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001001 ClobberWalkerBase<AliasAnalysisType> *Walker;
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001002
1003public:
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001004 SkipSelfWalker(MemorySSA *M, ClobberWalkerBase<AliasAnalysisType> *W)
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001005 : MemorySSAWalker(M), Walker(W) {}
1006 ~SkipSelfWalker() override = default;
1007
1008 using MemorySSAWalker::getClobberingMemoryAccess;
1009
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001010 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA) override {
1011 return Walker->getClobberingMemoryAccessBase(MA, true);
1012 }
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001013 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001014 const MemoryLocation &Loc) override {
1015 return Walker->getClobberingMemoryAccessBase(MA, Loc);
1016 }
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001017
1018 void invalidateInfo(MemoryAccess *MA) override {
1019 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1020 MUD->resetOptimized();
1021 }
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001022};
1023
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001024} // end namespace llvm
1025
Daniel Berlin78cbd282017-02-20 22:26:03 +00001026void MemorySSA::renameSuccessorPhis(BasicBlock *BB, MemoryAccess *IncomingVal,
1027 bool RenameAllUses) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001028 // Pass through values to our successors
1029 for (const BasicBlock *S : successors(BB)) {
1030 auto It = PerBlockAccesses.find(S);
1031 // Rename the phi nodes in our successor block
1032 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1033 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +00001034 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001035 auto *Phi = cast<MemoryPhi>(&Accesses->front());
Daniel Berlin78cbd282017-02-20 22:26:03 +00001036 if (RenameAllUses) {
1037 int PhiIndex = Phi->getBasicBlockIndex(BB);
1038 assert(PhiIndex != -1 && "Incomplete phi during partial rename");
1039 Phi->setIncomingValue(PhiIndex, IncomingVal);
1040 } else
1041 Phi->addIncoming(IncomingVal, BB);
George Burgess IVe1100f52016-02-02 22:46:49 +00001042 }
Daniel Berlin78cbd282017-02-20 22:26:03 +00001043}
George Burgess IVe1100f52016-02-02 22:46:49 +00001044
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001045/// Rename a single basic block into MemorySSA form.
Daniel Berlin78cbd282017-02-20 22:26:03 +00001046/// Uses the standard SSA renaming algorithm.
1047/// \returns The new incoming value.
1048MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB, MemoryAccess *IncomingVal,
1049 bool RenameAllUses) {
1050 auto It = PerBlockAccesses.find(BB);
1051 // Skip most processing if the list is empty.
1052 if (It != PerBlockAccesses.end()) {
1053 AccessList *Accesses = It->second.get();
1054 for (MemoryAccess &L : *Accesses) {
1055 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&L)) {
1056 if (MUD->getDefiningAccess() == nullptr || RenameAllUses)
1057 MUD->setDefiningAccess(IncomingVal);
1058 if (isa<MemoryDef>(&L))
1059 IncomingVal = &L;
1060 } else {
1061 IncomingVal = &L;
1062 }
1063 }
1064 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001065 return IncomingVal;
1066}
1067
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001068/// This is the standard SSA renaming algorithm.
George Burgess IVe1100f52016-02-02 22:46:49 +00001069///
1070/// We walk the dominator tree in preorder, renaming accesses, and then filling
1071/// in phi nodes in our successors.
1072void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
Daniel Berlin78cbd282017-02-20 22:26:03 +00001073 SmallPtrSetImpl<BasicBlock *> &Visited,
1074 bool SkipVisited, bool RenameAllUses) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001075 SmallVector<RenamePassData, 32> WorkStack;
Daniel Berlin78cbd282017-02-20 22:26:03 +00001076 // Skip everything if we already renamed this block and we are skipping.
1077 // Note: You can't sink this into the if, because we need it to occur
1078 // regardless of whether we skip blocks or not.
1079 bool AlreadyVisited = !Visited.insert(Root->getBlock()).second;
1080 if (SkipVisited && AlreadyVisited)
1081 return;
1082
1083 IncomingVal = renameBlock(Root->getBlock(), IncomingVal, RenameAllUses);
1084 renameSuccessorPhis(Root->getBlock(), IncomingVal, RenameAllUses);
George Burgess IVe1100f52016-02-02 22:46:49 +00001085 WorkStack.push_back({Root, Root->begin(), IncomingVal});
George Burgess IVe1100f52016-02-02 22:46:49 +00001086
1087 while (!WorkStack.empty()) {
1088 DomTreeNode *Node = WorkStack.back().DTN;
1089 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
1090 IncomingVal = WorkStack.back().IncomingVal;
1091
1092 if (ChildIt == Node->end()) {
1093 WorkStack.pop_back();
1094 } else {
1095 DomTreeNode *Child = *ChildIt;
1096 ++WorkStack.back().ChildIt;
1097 BasicBlock *BB = Child->getBlock();
Daniel Berlin78cbd282017-02-20 22:26:03 +00001098 // Note: You can't sink this into the if, because we need it to occur
1099 // regardless of whether we skip blocks or not.
1100 AlreadyVisited = !Visited.insert(BB).second;
1101 if (SkipVisited && AlreadyVisited) {
1102 // We already visited this during our renaming, which can happen when
1103 // being asked to rename multiple blocks. Figure out the incoming val,
1104 // which is the last def.
1105 // Incoming value can only change if there is a block def, and in that
1106 // case, it's the last block def in the list.
1107 if (auto *BlockDefs = getWritableBlockDefs(BB))
1108 IncomingVal = &*BlockDefs->rbegin();
1109 } else
1110 IncomingVal = renameBlock(BB, IncomingVal, RenameAllUses);
1111 renameSuccessorPhis(BB, IncomingVal, RenameAllUses);
George Burgess IVe1100f52016-02-02 22:46:49 +00001112 WorkStack.push_back({Child, Child->begin(), IncomingVal});
1113 }
1114 }
1115}
1116
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001117/// This handles unreachable block accesses by deleting phi nodes in
George Burgess IVe1100f52016-02-02 22:46:49 +00001118/// unreachable blocks, and marking all other unreachable MemoryAccess's as
1119/// being uses of the live on entry definition.
1120void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
1121 assert(!DT->isReachableFromEntry(BB) &&
1122 "Reachable block found while handling unreachable blocks");
1123
Daniel Berlinfc7e6512016-07-06 05:32:05 +00001124 // Make sure phi nodes in our reachable successors end up with a
1125 // LiveOnEntryDef for our incoming edge, even though our block is forward
1126 // unreachable. We could just disconnect these blocks from the CFG fully,
1127 // but we do not right now.
1128 for (const BasicBlock *S : successors(BB)) {
1129 if (!DT->isReachableFromEntry(S))
1130 continue;
1131 auto It = PerBlockAccesses.find(S);
1132 // Rename the phi nodes in our successor block
1133 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1134 continue;
1135 AccessList *Accesses = It->second.get();
1136 auto *Phi = cast<MemoryPhi>(&Accesses->front());
1137 Phi->addIncoming(LiveOnEntryDef.get(), BB);
1138 }
1139
George Burgess IVe1100f52016-02-02 22:46:49 +00001140 auto It = PerBlockAccesses.find(BB);
1141 if (It == PerBlockAccesses.end())
1142 return;
1143
1144 auto &Accesses = It->second;
1145 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1146 auto Next = std::next(AI);
1147 // If we have a phi, just remove it. We are going to replace all
1148 // users with live on entry.
1149 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1150 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1151 else
1152 Accesses->erase(AI);
1153 AI = Next;
1154 }
1155}
1156
Geoff Berryb96d3b22016-06-01 21:30:40 +00001157MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001158 : AA(nullptr), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001159 SkipWalker(nullptr), NextID(0) {
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001160 // Build MemorySSA using a batch alias analysis. This reuses the internal
1161 // state that AA collects during an alias()/getModRefInfo() call. This is
1162 // safe because there are no CFG changes while building MemorySSA and can
1163 // significantly reduce the time spent by the compiler in AA, because we will
1164 // make queries about all the instructions in the Function.
1165 BatchAAResults BatchAA(*AA);
1166 buildMemorySSA(BatchAA);
1167 // Intentionally leave AA to nullptr while building so we don't accidently
1168 // use non-batch AliasAnalysis.
1169 this->AA = AA;
1170 // Also create the walker here.
1171 getWalker();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001172}
1173
George Burgess IVe1100f52016-02-02 22:46:49 +00001174MemorySSA::~MemorySSA() {
1175 // Drop all our references
1176 for (const auto &Pair : PerBlockAccesses)
1177 for (MemoryAccess &MA : *Pair.second)
1178 MA.dropAllReferences();
1179}
1180
Daniel Berlin14300262016-06-21 18:39:20 +00001181MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001182 auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
1183
1184 if (Res.second)
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001185 Res.first->second = llvm::make_unique<AccessList>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001186 return Res.first->second.get();
1187}
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001188
Daniel Berlind602e042017-01-25 20:56:19 +00001189MemorySSA::DefsList *MemorySSA::getOrCreateDefsList(const BasicBlock *BB) {
1190 auto Res = PerBlockDefs.insert(std::make_pair(BB, nullptr));
1191
1192 if (Res.second)
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001193 Res.first->second = llvm::make_unique<DefsList>();
Daniel Berlind602e042017-01-25 20:56:19 +00001194 return Res.first->second.get();
1195}
George Burgess IVe1100f52016-02-02 22:46:49 +00001196
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001197namespace llvm {
1198
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001199/// This class is a batch walker of all MemoryUse's in the program, and points
1200/// their defining access at the thing that actually clobbers them. Because it
1201/// is a batch walker that touches everything, it does not operate like the
1202/// other walkers. This walker is basically performing a top-down SSA renaming
1203/// pass, where the version stack is used as the cache. This enables it to be
1204/// significantly more time and memory efficient than using the regular walker,
1205/// which is walking bottom-up.
1206class MemorySSA::OptimizeUses {
1207public:
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001208 OptimizeUses(MemorySSA *MSSA, MemorySSAWalker *Walker, BatchAAResults *BAA,
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001209 DominatorTree *DT)
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001210 : MSSA(MSSA), Walker(Walker), AA(BAA), DT(DT) {}
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001211
1212 void optimizeUses();
1213
1214private:
1215 /// This represents where a given memorylocation is in the stack.
1216 struct MemlocStackInfo {
1217 // This essentially is keeping track of versions of the stack. Whenever
1218 // the stack changes due to pushes or pops, these versions increase.
1219 unsigned long StackEpoch;
1220 unsigned long PopEpoch;
1221 // This is the lower bound of places on the stack to check. It is equal to
1222 // the place the last stack walk ended.
1223 // Note: Correctness depends on this being initialized to 0, which densemap
1224 // does
1225 unsigned long LowerBound;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001226 const BasicBlock *LowerBoundBlock;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001227 // This is where the last walk for this memory location ended.
1228 unsigned long LastKill;
1229 bool LastKillValid;
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001230 Optional<AliasResult> AR;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001231 };
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001232
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001233 void optimizeUsesInBlock(const BasicBlock *, unsigned long &, unsigned long &,
1234 SmallVectorImpl<MemoryAccess *> &,
1235 DenseMap<MemoryLocOrCall, MemlocStackInfo> &);
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001236
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001237 MemorySSA *MSSA;
1238 MemorySSAWalker *Walker;
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001239 BatchAAResults *AA;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001240 DominatorTree *DT;
1241};
1242
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001243} // end namespace llvm
1244
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001245/// Optimize the uses in a given block This is basically the SSA renaming
1246/// algorithm, with one caveat: We are able to use a single stack for all
1247/// MemoryUses. This is because the set of *possible* reaching MemoryDefs is
1248/// the same for every MemoryUse. The *actual* clobbering MemoryDef is just
1249/// going to be some position in that stack of possible ones.
1250///
1251/// We track the stack positions that each MemoryLocation needs
1252/// to check, and last ended at. This is because we only want to check the
1253/// things that changed since last time. The same MemoryLocation should
1254/// get clobbered by the same store (getModRefInfo does not use invariantness or
1255/// things like this, and if they start, we can modify MemoryLocOrCall to
1256/// include relevant data)
1257void MemorySSA::OptimizeUses::optimizeUsesInBlock(
1258 const BasicBlock *BB, unsigned long &StackEpoch, unsigned long &PopEpoch,
1259 SmallVectorImpl<MemoryAccess *> &VersionStack,
1260 DenseMap<MemoryLocOrCall, MemlocStackInfo> &LocStackInfo) {
1261
1262 /// If no accesses, nothing to do.
1263 MemorySSA::AccessList *Accesses = MSSA->getWritableBlockAccesses(BB);
1264 if (Accesses == nullptr)
1265 return;
1266
1267 // Pop everything that doesn't dominate the current block off the stack,
1268 // increment the PopEpoch to account for this.
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001269 while (true) {
1270 assert(
1271 !VersionStack.empty() &&
1272 "Version stack should have liveOnEntry sentinel dominating everything");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001273 BasicBlock *BackBlock = VersionStack.back()->getBlock();
1274 if (DT->dominates(BackBlock, BB))
1275 break;
1276 while (VersionStack.back()->getBlock() == BackBlock)
1277 VersionStack.pop_back();
1278 ++PopEpoch;
1279 }
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001280
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001281 for (MemoryAccess &MA : *Accesses) {
1282 auto *MU = dyn_cast<MemoryUse>(&MA);
1283 if (!MU) {
1284 VersionStack.push_back(&MA);
1285 ++StackEpoch;
1286 continue;
1287 }
1288
George Burgess IV024f3d22016-08-03 19:57:02 +00001289 if (isUseTriviallyOptimizableToLiveOnEntry(*AA, MU->getMemoryInst())) {
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001290 MU->setDefiningAccess(MSSA->getLiveOnEntryDef(), true, None);
George Burgess IV024f3d22016-08-03 19:57:02 +00001291 continue;
1292 }
1293
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001294 MemoryLocOrCall UseMLOC(MU);
1295 auto &LocInfo = LocStackInfo[UseMLOC];
Daniel Berlin26fcea92016-08-02 20:02:21 +00001296 // If the pop epoch changed, it means we've removed stuff from top of
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001297 // stack due to changing blocks. We may have to reset the lower bound or
1298 // last kill info.
1299 if (LocInfo.PopEpoch != PopEpoch) {
1300 LocInfo.PopEpoch = PopEpoch;
1301 LocInfo.StackEpoch = StackEpoch;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001302 // If the lower bound was in something that no longer dominates us, we
1303 // have to reset it.
1304 // We can't simply track stack size, because the stack may have had
1305 // pushes/pops in the meantime.
1306 // XXX: This is non-optimal, but only is slower cases with heavily
1307 // branching dominator trees. To get the optimal number of queries would
1308 // be to make lowerbound and lastkill a per-loc stack, and pop it until
1309 // the top of that stack dominates us. This does not seem worth it ATM.
1310 // A much cheaper optimization would be to always explore the deepest
1311 // branch of the dominator tree first. This will guarantee this resets on
1312 // the smallest set of blocks.
1313 if (LocInfo.LowerBoundBlock && LocInfo.LowerBoundBlock != BB &&
Daniel Berlin1e98c042016-09-26 17:22:54 +00001314 !DT->dominates(LocInfo.LowerBoundBlock, BB)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001315 // Reset the lower bound of things to check.
1316 // TODO: Some day we should be able to reset to last kill, rather than
1317 // 0.
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001318 LocInfo.LowerBound = 0;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001319 LocInfo.LowerBoundBlock = VersionStack[0]->getBlock();
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001320 LocInfo.LastKillValid = false;
1321 }
1322 } else if (LocInfo.StackEpoch != StackEpoch) {
1323 // If all that has changed is the StackEpoch, we only have to check the
1324 // new things on the stack, because we've checked everything before. In
1325 // this case, the lower bound of things to check remains the same.
1326 LocInfo.PopEpoch = PopEpoch;
1327 LocInfo.StackEpoch = StackEpoch;
1328 }
1329 if (!LocInfo.LastKillValid) {
1330 LocInfo.LastKill = VersionStack.size() - 1;
1331 LocInfo.LastKillValid = true;
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001332 LocInfo.AR = MayAlias;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001333 }
1334
1335 // At this point, we should have corrected last kill and LowerBound to be
1336 // in bounds.
1337 assert(LocInfo.LowerBound < VersionStack.size() &&
1338 "Lower bound out of range");
1339 assert(LocInfo.LastKill < VersionStack.size() &&
1340 "Last kill info out of range");
1341 // In any case, the new upper bound is the top of the stack.
1342 unsigned long UpperBound = VersionStack.size() - 1;
1343
1344 if (UpperBound - LocInfo.LowerBound > MaxCheckLimit) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001345 LLVM_DEBUG(dbgs() << "MemorySSA skipping optimization of " << *MU << " ("
1346 << *(MU->getMemoryInst()) << ")"
1347 << " because there are "
1348 << UpperBound - LocInfo.LowerBound
1349 << " stores to disambiguate\n");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001350 // Because we did not walk, LastKill is no longer valid, as this may
1351 // have been a kill.
1352 LocInfo.LastKillValid = false;
1353 continue;
1354 }
1355 bool FoundClobberResult = false;
1356 while (UpperBound > LocInfo.LowerBound) {
1357 if (isa<MemoryPhi>(VersionStack[UpperBound])) {
1358 // For phis, use the walker, see where we ended up, go there
1359 Instruction *UseInst = MU->getMemoryInst();
1360 MemoryAccess *Result = Walker->getClobberingMemoryAccess(UseInst);
1361 // We are guaranteed to find it or something is wrong
1362 while (VersionStack[UpperBound] != Result) {
1363 assert(UpperBound != 0);
1364 --UpperBound;
1365 }
1366 FoundClobberResult = true;
1367 break;
1368 }
1369
1370 MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]);
Daniel Berlindf101192016-08-03 00:01:46 +00001371 // If the lifetime of the pointer ends at this instruction, it's live on
1372 // entry.
1373 if (!UseMLOC.IsCall && lifetimeEndsAt(MD, UseMLOC.getLoc(), *AA)) {
1374 // Reset UpperBound to liveOnEntryDef's place in the stack
1375 UpperBound = 0;
1376 FoundClobberResult = true;
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001377 LocInfo.AR = MustAlias;
Daniel Berlindf101192016-08-03 00:01:46 +00001378 break;
1379 }
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001380 ClobberAlias CA = instructionClobbersQuery(MD, MU, UseMLOC, *AA);
1381 if (CA.IsClobber) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001382 FoundClobberResult = true;
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001383 LocInfo.AR = CA.AR;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001384 break;
1385 }
1386 --UpperBound;
1387 }
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001388
1389 // Note: Phis always have AliasResult AR set to MayAlias ATM.
1390
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001391 // At the end of this loop, UpperBound is either a clobber, or lower bound
1392 // PHI walking may cause it to be < LowerBound, and in fact, < LastKill.
1393 if (FoundClobberResult || UpperBound < LocInfo.LastKill) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001394 // We were last killed now by where we got to
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001395 if (MSSA->isLiveOnEntryDef(VersionStack[UpperBound]))
1396 LocInfo.AR = None;
1397 MU->setDefiningAccess(VersionStack[UpperBound], true, LocInfo.AR);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001398 LocInfo.LastKill = UpperBound;
1399 } else {
1400 // Otherwise, we checked all the new ones, and now we know we can get to
1401 // LastKill.
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001402 MU->setDefiningAccess(VersionStack[LocInfo.LastKill], true, LocInfo.AR);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001403 }
1404 LocInfo.LowerBound = VersionStack.size() - 1;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001405 LocInfo.LowerBoundBlock = BB;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001406 }
1407}
1408
1409/// Optimize uses to point to their actual clobbering definitions.
1410void MemorySSA::OptimizeUses::optimizeUses() {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001411 SmallVector<MemoryAccess *, 16> VersionStack;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001412 DenseMap<MemoryLocOrCall, MemlocStackInfo> LocStackInfo;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001413 VersionStack.push_back(MSSA->getLiveOnEntryDef());
1414
1415 unsigned long StackEpoch = 1;
1416 unsigned long PopEpoch = 1;
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001417 // We perform a non-recursive top-down dominator tree walk.
Daniel Berlin7ac3d742016-08-05 22:09:14 +00001418 for (const auto *DomNode : depth_first(DT->getRootNode()))
1419 optimizeUsesInBlock(DomNode->getBlock(), StackEpoch, PopEpoch, VersionStack,
1420 LocStackInfo);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001421}
1422
Daniel Berlin3d512a22016-08-22 19:14:30 +00001423void MemorySSA::placePHINodes(
Michael Zolotukhin67cfbaa2018-05-15 18:40:29 +00001424 const SmallPtrSetImpl<BasicBlock *> &DefiningBlocks) {
Daniel Berlin3d512a22016-08-22 19:14:30 +00001425 // Determine where our MemoryPhi's should go
1426 ForwardIDFCalculator IDFs(*DT);
1427 IDFs.setDefiningBlocks(DefiningBlocks);
Daniel Berlin3d512a22016-08-22 19:14:30 +00001428 SmallVector<BasicBlock *, 32> IDFBlocks;
1429 IDFs.calculate(IDFBlocks);
1430
1431 // Now place MemoryPhi nodes.
Daniel Berlind602e042017-01-25 20:56:19 +00001432 for (auto &BB : IDFBlocks)
1433 createMemoryPhi(BB);
Daniel Berlin3d512a22016-08-22 19:14:30 +00001434}
1435
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001436void MemorySSA::buildMemorySSA(BatchAAResults &BAA) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001437 // We create an access to represent "live on entry", for things like
1438 // arguments or users of globals, where the memory they use is defined before
1439 // the beginning of the function. We do not actually insert it into the IR.
1440 // We do not define a live on exit for the immediate uses, and thus our
1441 // semantics do *not* imply that something with no immediate uses can simply
1442 // be removed.
1443 BasicBlock &StartingPoint = F.getEntryBlock();
George Burgess IV612cf212018-02-27 06:43:19 +00001444 LiveOnEntryDef.reset(new MemoryDef(F.getContext(), nullptr, nullptr,
1445 &StartingPoint, NextID++));
George Burgess IVe1100f52016-02-02 22:46:49 +00001446
1447 // We maintain lists of memory accesses per-block, trading memory for time. We
1448 // could just look up the memory access for every possible instruction in the
1449 // stream.
1450 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
George Burgess IVe1100f52016-02-02 22:46:49 +00001451 // Go through each block, figure out where defs occur, and chain together all
1452 // the accesses.
1453 for (BasicBlock &B : F) {
Daniel Berlin7898ca62016-02-07 01:52:15 +00001454 bool InsertIntoDef = false;
Daniel Berlinada263d2016-06-20 20:21:33 +00001455 AccessList *Accesses = nullptr;
Daniel Berlind602e042017-01-25 20:56:19 +00001456 DefsList *Defs = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +00001457 for (Instruction &I : B) {
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001458 MemoryUseOrDef *MUD = createNewAccess(&I, &BAA);
George Burgess IVb42b7622016-03-11 19:34:03 +00001459 if (!MUD)
George Burgess IVe1100f52016-02-02 22:46:49 +00001460 continue;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001461
George Burgess IVe1100f52016-02-02 22:46:49 +00001462 if (!Accesses)
1463 Accesses = getOrCreateAccessList(&B);
George Burgess IVb42b7622016-03-11 19:34:03 +00001464 Accesses->push_back(MUD);
Daniel Berlind602e042017-01-25 20:56:19 +00001465 if (isa<MemoryDef>(MUD)) {
1466 InsertIntoDef = true;
1467 if (!Defs)
1468 Defs = getOrCreateDefsList(&B);
1469 Defs->push_back(*MUD);
1470 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001471 }
Daniel Berlin7898ca62016-02-07 01:52:15 +00001472 if (InsertIntoDef)
1473 DefiningBlocks.insert(&B);
Daniel Berlin1b51a292016-02-07 01:52:19 +00001474 }
Michael Zolotukhin67cfbaa2018-05-15 18:40:29 +00001475 placePHINodes(DefiningBlocks);
George Burgess IVe1100f52016-02-02 22:46:49 +00001476
1477 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
1478 // filled in with all blocks.
1479 SmallPtrSet<BasicBlock *, 16> Visited;
1480 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1481
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001482 ClobberWalkerBase<BatchAAResults> WalkerBase(this, &BAA, DT);
1483 CachingWalker<BatchAAResults> WalkerLocal(this, &WalkerBase);
1484 OptimizeUses(this, &WalkerLocal, &BAA, DT).optimizeUses();
George Burgess IV5f308972016-07-19 01:29:15 +00001485
George Burgess IVe1100f52016-02-02 22:46:49 +00001486 // Mark the uses in unreachable blocks as live on entry, so that they go
1487 // somewhere.
1488 for (auto &BB : F)
1489 if (!Visited.count(&BB))
1490 markUnreachableAsLiveOnEntry(&BB);
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001491}
George Burgess IVe1100f52016-02-02 22:46:49 +00001492
George Burgess IV5f308972016-07-19 01:29:15 +00001493MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
1494
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001495MemorySSA::CachingWalker<AliasAnalysis> *MemorySSA::getWalkerImpl() {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001496 if (Walker)
1497 return Walker.get();
1498
Alina Sbirleabc8aa242019-01-07 19:22:37 +00001499 if (!WalkerBase)
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001500 WalkerBase =
1501 llvm::make_unique<ClobberWalkerBase<AliasAnalysis>>(this, AA, DT);
Alina Sbirleabc8aa242019-01-07 19:22:37 +00001502
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001503 Walker =
1504 llvm::make_unique<CachingWalker<AliasAnalysis>>(this, WalkerBase.get());
Geoff Berryb96d3b22016-06-01 21:30:40 +00001505 return Walker.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001506}
1507
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001508MemorySSAWalker *MemorySSA::getSkipSelfWalker() {
1509 if (SkipWalker)
1510 return SkipWalker.get();
1511
1512 if (!WalkerBase)
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001513 WalkerBase =
1514 llvm::make_unique<ClobberWalkerBase<AliasAnalysis>>(this, AA, DT);
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001515
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001516 SkipWalker =
1517 llvm::make_unique<SkipSelfWalker<AliasAnalysis>>(this, WalkerBase.get());
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001518 return SkipWalker.get();
1519 }
1520
1521
Daniel Berlind602e042017-01-25 20:56:19 +00001522// This is a helper function used by the creation routines. It places NewAccess
1523// into the access and defs lists for a given basic block, at the given
1524// insertion point.
1525void MemorySSA::insertIntoListsForBlock(MemoryAccess *NewAccess,
1526 const BasicBlock *BB,
1527 InsertionPlace Point) {
1528 auto *Accesses = getOrCreateAccessList(BB);
1529 if (Point == Beginning) {
1530 // If it's a phi node, it goes first, otherwise, it goes after any phi
1531 // nodes.
1532 if (isa<MemoryPhi>(NewAccess)) {
1533 Accesses->push_front(NewAccess);
1534 auto *Defs = getOrCreateDefsList(BB);
1535 Defs->push_front(*NewAccess);
1536 } else {
1537 auto AI = find_if_not(
1538 *Accesses, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1539 Accesses->insert(AI, NewAccess);
1540 if (!isa<MemoryUse>(NewAccess)) {
1541 auto *Defs = getOrCreateDefsList(BB);
1542 auto DI = find_if_not(
1543 *Defs, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1544 Defs->insert(DI, *NewAccess);
1545 }
1546 }
1547 } else {
1548 Accesses->push_back(NewAccess);
1549 if (!isa<MemoryUse>(NewAccess)) {
1550 auto *Defs = getOrCreateDefsList(BB);
1551 Defs->push_back(*NewAccess);
1552 }
1553 }
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001554 BlockNumberingValid.erase(BB);
Daniel Berlind602e042017-01-25 20:56:19 +00001555}
1556
1557void MemorySSA::insertIntoListsBefore(MemoryAccess *What, const BasicBlock *BB,
1558 AccessList::iterator InsertPt) {
1559 auto *Accesses = getWritableBlockAccesses(BB);
1560 bool WasEnd = InsertPt == Accesses->end();
1561 Accesses->insert(AccessList::iterator(InsertPt), What);
1562 if (!isa<MemoryUse>(What)) {
1563 auto *Defs = getOrCreateDefsList(BB);
1564 // If we got asked to insert at the end, we have an easy job, just shove it
1565 // at the end. If we got asked to insert before an existing def, we also get
Zhaoshi Zhenga5531f22018-04-04 21:08:11 +00001566 // an iterator. If we got asked to insert before a use, we have to hunt for
Daniel Berlind602e042017-01-25 20:56:19 +00001567 // the next def.
1568 if (WasEnd) {
1569 Defs->push_back(*What);
1570 } else if (isa<MemoryDef>(InsertPt)) {
1571 Defs->insert(InsertPt->getDefsIterator(), *What);
1572 } else {
1573 while (InsertPt != Accesses->end() && !isa<MemoryDef>(InsertPt))
1574 ++InsertPt;
1575 // Either we found a def, or we are inserting at the end
1576 if (InsertPt == Accesses->end())
1577 Defs->push_back(*What);
1578 else
1579 Defs->insert(InsertPt->getDefsIterator(), *What);
1580 }
1581 }
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001582 BlockNumberingValid.erase(BB);
Daniel Berlind602e042017-01-25 20:56:19 +00001583}
1584
George Burgess IV5676a5d2018-08-22 22:34:38 +00001585void MemorySSA::prepareForMoveTo(MemoryAccess *What, BasicBlock *BB) {
1586 // Keep it in the lookup tables, remove from the lists
1587 removeFromLists(What, false);
1588
1589 // Note that moving should implicitly invalidate the optimized state of a
1590 // MemoryUse (and Phis can't be optimized). However, it doesn't do so for a
1591 // MemoryDef.
1592 if (auto *MD = dyn_cast<MemoryDef>(What))
1593 MD->resetOptimized();
1594 What->setBlock(BB);
1595}
1596
Zhaoshi Zhenga5531f22018-04-04 21:08:11 +00001597// Move What before Where in the IR. The end result is that What will belong to
Daniel Berlin60ead052017-01-28 01:23:13 +00001598// the right lists and have the right Block set, but will not otherwise be
1599// correct. It will not have the right defining access, and if it is a def,
1600// things below it will not properly be updated.
1601void MemorySSA::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
1602 AccessList::iterator Where) {
George Burgess IV5676a5d2018-08-22 22:34:38 +00001603 prepareForMoveTo(What, BB);
Daniel Berlin60ead052017-01-28 01:23:13 +00001604 insertIntoListsBefore(What, BB, Where);
1605}
1606
Alina Sbirlea0f533552018-07-11 22:11:46 +00001607void MemorySSA::moveTo(MemoryAccess *What, BasicBlock *BB,
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001608 InsertionPlace Point) {
Alina Sbirlea0f533552018-07-11 22:11:46 +00001609 if (isa<MemoryPhi>(What)) {
1610 assert(Point == Beginning &&
1611 "Can only move a Phi at the beginning of the block");
1612 // Update lookup table entry
1613 ValueToMemoryAccess.erase(What->getBlock());
1614 bool Inserted = ValueToMemoryAccess.insert({BB, What}).second;
1615 (void)Inserted;
1616 assert(Inserted && "Cannot move a Phi to a block that already has one");
1617 }
1618
George Burgess IV5676a5d2018-08-22 22:34:38 +00001619 prepareForMoveTo(What, BB);
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001620 insertIntoListsForBlock(What, BB, Point);
1621}
1622
Daniel Berlin14300262016-06-21 18:39:20 +00001623MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
1624 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
Daniel Berlin14300262016-06-21 18:39:20 +00001625 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001626 // Phi's always are placed at the front of the block.
Daniel Berlind602e042017-01-25 20:56:19 +00001627 insertIntoListsForBlock(Phi, BB, Beginning);
Daniel Berlin5130cc82016-07-31 21:08:20 +00001628 ValueToMemoryAccess[BB] = Phi;
Daniel Berlin14300262016-06-21 18:39:20 +00001629 return Phi;
1630}
1631
1632MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
Alina Sbirlea79800992018-09-10 20:13:01 +00001633 MemoryAccess *Definition,
1634 const MemoryUseOrDef *Template) {
Daniel Berlin14300262016-06-21 18:39:20 +00001635 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001636 MemoryUseOrDef *NewAccess = createNewAccess(I, AA, Template);
Daniel Berlin14300262016-06-21 18:39:20 +00001637 assert(
1638 NewAccess != nullptr &&
1639 "Tried to create a memory access for a non-memory touching instruction");
1640 NewAccess->setDefiningAccess(Definition);
1641 return NewAccess;
1642}
1643
Daniel Berlind952cea2017-04-07 01:28:36 +00001644// Return true if the instruction has ordering constraints.
1645// Note specifically that this only considers stores and loads
1646// because others are still considered ModRef by getModRefInfo.
1647static inline bool isOrdered(const Instruction *I) {
1648 if (auto *SI = dyn_cast<StoreInst>(I)) {
1649 if (!SI->isUnordered())
1650 return true;
1651 } else if (auto *LI = dyn_cast<LoadInst>(I)) {
1652 if (!LI->isUnordered())
1653 return true;
1654 }
1655 return false;
1656}
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001657
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001658/// Helper function to create new memory accesses
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001659template <typename AliasAnalysisType>
Alina Sbirlea79800992018-09-10 20:13:01 +00001660MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I,
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001661 AliasAnalysisType *AAP,
Alina Sbirlea79800992018-09-10 20:13:01 +00001662 const MemoryUseOrDef *Template) {
Peter Collingbourneb9aa1f42016-05-26 04:58:46 +00001663 // The assume intrinsic has a control dependency which we model by claiming
1664 // that it writes arbitrarily. Ignore that fake memory dependency here.
1665 // FIXME: Replace this special casing with a more accurate modelling of
1666 // assume's control dependency.
1667 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1668 if (II->getIntrinsicID() == Intrinsic::assume)
1669 return nullptr;
1670
Alina Sbirlea79800992018-09-10 20:13:01 +00001671 bool Def, Use;
1672 if (Template) {
1673 Def = dyn_cast_or_null<MemoryDef>(Template) != nullptr;
1674 Use = dyn_cast_or_null<MemoryUse>(Template) != nullptr;
1675#if !defined(NDEBUG)
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001676 ModRefInfo ModRef = AAP->getModRefInfo(I, None);
Alina Sbirlea79800992018-09-10 20:13:01 +00001677 bool DefCheck, UseCheck;
1678 DefCheck = isModSet(ModRef) || isOrdered(I);
1679 UseCheck = isRefSet(ModRef);
1680 assert(Def == DefCheck && (Def || Use == UseCheck) && "Invalid template");
1681#endif
1682 } else {
1683 // Find out what affect this instruction has on memory.
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001684 ModRefInfo ModRef = AAP->getModRefInfo(I, None);
Alina Sbirlea79800992018-09-10 20:13:01 +00001685 // The isOrdered check is used to ensure that volatiles end up as defs
1686 // (atomics end up as ModRef right now anyway). Until we separate the
1687 // ordering chain from the memory chain, this enables people to see at least
1688 // some relative ordering to volatiles. Note that getClobberingMemoryAccess
1689 // will still give an answer that bypasses other volatile loads. TODO:
1690 // Separate memory aliasing and ordering into two different chains so that
1691 // we can precisely represent both "what memory will this read/write/is
1692 // clobbered by" and "what instructions can I move this past".
1693 Def = isModSet(ModRef) || isOrdered(I);
1694 Use = isRefSet(ModRef);
1695 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001696
1697 // It's possible for an instruction to not modify memory at all. During
1698 // construction, we ignore them.
Peter Collingbourneffecb142016-05-26 01:19:17 +00001699 if (!Def && !Use)
George Burgess IVe1100f52016-02-02 22:46:49 +00001700 return nullptr;
1701
George Burgess IVb42b7622016-03-11 19:34:03 +00001702 MemoryUseOrDef *MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001703 if (Def)
George Burgess IVb42b7622016-03-11 19:34:03 +00001704 MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
George Burgess IVe1100f52016-02-02 22:46:49 +00001705 else
George Burgess IVb42b7622016-03-11 19:34:03 +00001706 MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
Daniel Berlin5130cc82016-07-31 21:08:20 +00001707 ValueToMemoryAccess[I] = MUD;
George Burgess IVb42b7622016-03-11 19:34:03 +00001708 return MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001709}
1710
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001711/// Returns true if \p Replacer dominates \p Replacee .
George Burgess IVe1100f52016-02-02 22:46:49 +00001712bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
1713 const MemoryAccess *Replacee) const {
1714 if (isa<MemoryUseOrDef>(Replacee))
1715 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
1716 const auto *MP = cast<MemoryPhi>(Replacee);
1717 // For a phi node, the use occurs in the predecessor block of the phi node.
1718 // Since we may occur multiple times in the phi node, we have to check each
1719 // operand to ensure Replacer dominates each operand where Replacee occurs.
1720 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +00001721 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +00001722 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
1723 return false;
1724 }
1725 return true;
1726}
1727
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001728/// Properly remove \p MA from all of MemorySSA's lookup tables.
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001729void MemorySSA::removeFromLookups(MemoryAccess *MA) {
1730 assert(MA->use_empty() &&
1731 "Trying to remove memory access that still has uses");
Daniel Berlin5c46b942016-07-19 22:49:43 +00001732 BlockNumbering.erase(MA);
George Burgess IV2cbf9732018-06-22 22:34:07 +00001733 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001734 MUD->setDefiningAccess(nullptr);
1735 // Invalidate our walker's cache if necessary
1736 if (!isa<MemoryUse>(MA))
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001737 getWalker()->invalidateInfo(MA);
George Burgess IV2cbf9732018-06-22 22:34:07 +00001738
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001739 Value *MemoryInst;
George Burgess IV2cbf9732018-06-22 22:34:07 +00001740 if (const auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001741 MemoryInst = MUD->getMemoryInst();
George Burgess IV2cbf9732018-06-22 22:34:07 +00001742 else
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001743 MemoryInst = MA->getBlock();
George Burgess IV2cbf9732018-06-22 22:34:07 +00001744
Daniel Berlin5130cc82016-07-31 21:08:20 +00001745 auto VMA = ValueToMemoryAccess.find(MemoryInst);
1746 if (VMA->second == MA)
1747 ValueToMemoryAccess.erase(VMA);
Daniel Berlin60ead052017-01-28 01:23:13 +00001748}
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001749
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001750/// Properly remove \p MA from all of MemorySSA's lists.
Daniel Berlin60ead052017-01-28 01:23:13 +00001751///
1752/// Because of the way the intrusive list and use lists work, it is important to
1753/// do removal in the right order.
1754/// ShouldDelete defaults to true, and will cause the memory access to also be
1755/// deleted, not just removed.
1756void MemorySSA::removeFromLists(MemoryAccess *MA, bool ShouldDelete) {
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001757 BasicBlock *BB = MA->getBlock();
Daniel Berlind602e042017-01-25 20:56:19 +00001758 // The access list owns the reference, so we erase it from the non-owning list
1759 // first.
1760 if (!isa<MemoryUse>(MA)) {
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001761 auto DefsIt = PerBlockDefs.find(BB);
Daniel Berlind602e042017-01-25 20:56:19 +00001762 std::unique_ptr<DefsList> &Defs = DefsIt->second;
1763 Defs->remove(*MA);
1764 if (Defs->empty())
1765 PerBlockDefs.erase(DefsIt);
1766 }
1767
Daniel Berlin60ead052017-01-28 01:23:13 +00001768 // The erase call here will delete it. If we don't want it deleted, we call
1769 // remove instead.
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001770 auto AccessIt = PerBlockAccesses.find(BB);
Daniel Berlinada263d2016-06-20 20:21:33 +00001771 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
Daniel Berlin60ead052017-01-28 01:23:13 +00001772 if (ShouldDelete)
1773 Accesses->erase(MA);
1774 else
1775 Accesses->remove(MA);
1776
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001777 if (Accesses->empty()) {
George Burgess IVe0e6e482016-03-02 02:35:04 +00001778 PerBlockAccesses.erase(AccessIt);
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001779 BlockNumberingValid.erase(BB);
1780 }
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001781}
1782
George Burgess IVe1100f52016-02-02 22:46:49 +00001783void MemorySSA::print(raw_ostream &OS) const {
1784 MemorySSAAnnotatedWriter Writer(this);
1785 F.print(OS, &Writer);
1786}
1787
Aaron Ballman615eb472017-10-15 14:32:27 +00001788#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Daniel Berlin78cbd282017-02-20 22:26:03 +00001789LLVM_DUMP_METHOD void MemorySSA::dump() const { print(dbgs()); }
Matthias Braun8c209aa2017-01-28 02:02:38 +00001790#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001791
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001792void MemorySSA::verifyMemorySSA() const {
1793 verifyDefUses(F);
1794 verifyDomination(F);
Daniel Berlin14300262016-06-21 18:39:20 +00001795 verifyOrdering(F);
George Burgess IV97ec6242018-06-25 05:30:36 +00001796 verifyDominationNumbers(F);
Alina Sbirlead77edc02019-02-11 19:51:21 +00001797 // Previously, the verification used to also verify that the clobberingAccess
1798 // cached by MemorySSA is the same as the clobberingAccess found at a later
1799 // query to AA. This does not hold true in general due to the current fragility
1800 // of BasicAA which has arbitrary caps on the things it analyzes before giving
1801 // up. As a result, transformations that are correct, will lead to BasicAA
1802 // returning different Alias answers before and after that transformation.
1803 // Invalidating MemorySSA is not an option, as the results in BasicAA can be so
1804 // random, in the worst case we'd need to rebuild MemorySSA from scratch after
1805 // every transformation, which defeats the purpose of using it. For such an
1806 // example, see test4 added in D51960.
Daniel Berlin14300262016-06-21 18:39:20 +00001807}
1808
George Burgess IV97ec6242018-06-25 05:30:36 +00001809/// Verify that all of the blocks we believe to have valid domination numbers
1810/// actually have valid domination numbers.
1811void MemorySSA::verifyDominationNumbers(const Function &F) const {
1812#ifndef NDEBUG
1813 if (BlockNumberingValid.empty())
1814 return;
1815
1816 SmallPtrSet<const BasicBlock *, 16> ValidBlocks = BlockNumberingValid;
1817 for (const BasicBlock &BB : F) {
1818 if (!ValidBlocks.count(&BB))
1819 continue;
1820
1821 ValidBlocks.erase(&BB);
1822
1823 const AccessList *Accesses = getBlockAccesses(&BB);
1824 // It's correct to say an empty block has valid numbering.
1825 if (!Accesses)
1826 continue;
1827
1828 // Block numbering starts at 1.
1829 unsigned long LastNumber = 0;
1830 for (const MemoryAccess &MA : *Accesses) {
1831 auto ThisNumberIter = BlockNumbering.find(&MA);
1832 assert(ThisNumberIter != BlockNumbering.end() &&
1833 "MemoryAccess has no domination number in a valid block!");
1834
1835 unsigned long ThisNumber = ThisNumberIter->second;
1836 assert(ThisNumber > LastNumber &&
1837 "Domination numbers should be strictly increasing!");
1838 LastNumber = ThisNumber;
1839 }
1840 }
1841
1842 assert(ValidBlocks.empty() &&
1843 "All valid BasicBlocks should exist in F -- dangling pointers?");
1844#endif
1845}
1846
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001847/// Verify that the order and existence of MemoryAccesses matches the
Daniel Berlin14300262016-06-21 18:39:20 +00001848/// order and existence of memory affecting instructions.
1849void MemorySSA::verifyOrdering(Function &F) const {
George Burgess IV6a9aa022018-08-28 00:32:32 +00001850#ifndef NDEBUG
Daniel Berlin14300262016-06-21 18:39:20 +00001851 // Walk all the blocks, comparing what the lookups think and what the access
1852 // lists think, as well as the order in the blocks vs the order in the access
1853 // lists.
1854 SmallVector<MemoryAccess *, 32> ActualAccesses;
Daniel Berlind602e042017-01-25 20:56:19 +00001855 SmallVector<MemoryAccess *, 32> ActualDefs;
Daniel Berlin14300262016-06-21 18:39:20 +00001856 for (BasicBlock &B : F) {
1857 const AccessList *AL = getBlockAccesses(&B);
Daniel Berlind602e042017-01-25 20:56:19 +00001858 const auto *DL = getBlockDefs(&B);
Daniel Berlin14300262016-06-21 18:39:20 +00001859 MemoryAccess *Phi = getMemoryAccess(&B);
Daniel Berlind602e042017-01-25 20:56:19 +00001860 if (Phi) {
Daniel Berlin14300262016-06-21 18:39:20 +00001861 ActualAccesses.push_back(Phi);
Daniel Berlind602e042017-01-25 20:56:19 +00001862 ActualDefs.push_back(Phi);
1863 }
1864
Daniel Berlin14300262016-06-21 18:39:20 +00001865 for (Instruction &I : B) {
1866 MemoryAccess *MA = getMemoryAccess(&I);
Daniel Berlind602e042017-01-25 20:56:19 +00001867 assert((!MA || (AL && (isa<MemoryUse>(MA) || DL))) &&
1868 "We have memory affecting instructions "
1869 "in this block but they are not in the "
1870 "access list or defs list");
1871 if (MA) {
Daniel Berlin14300262016-06-21 18:39:20 +00001872 ActualAccesses.push_back(MA);
Daniel Berlind602e042017-01-25 20:56:19 +00001873 if (isa<MemoryDef>(MA))
1874 ActualDefs.push_back(MA);
1875 }
Daniel Berlin14300262016-06-21 18:39:20 +00001876 }
1877 // Either we hit the assert, really have no accesses, or we have both
Daniel Berlind602e042017-01-25 20:56:19 +00001878 // accesses and an access list.
1879 // Same with defs.
1880 if (!AL && !DL)
Daniel Berlin14300262016-06-21 18:39:20 +00001881 continue;
1882 assert(AL->size() == ActualAccesses.size() &&
1883 "We don't have the same number of accesses in the block as on the "
1884 "access list");
Davide Italiano6c77de02017-01-30 03:16:43 +00001885 assert((DL || ActualDefs.size() == 0) &&
1886 "Either we should have a defs list, or we should have no defs");
Daniel Berlind602e042017-01-25 20:56:19 +00001887 assert((!DL || DL->size() == ActualDefs.size()) &&
1888 "We don't have the same number of defs in the block as on the "
1889 "def list");
Daniel Berlin14300262016-06-21 18:39:20 +00001890 auto ALI = AL->begin();
1891 auto AAI = ActualAccesses.begin();
1892 while (ALI != AL->end() && AAI != ActualAccesses.end()) {
1893 assert(&*ALI == *AAI && "Not the same accesses in the same order");
1894 ++ALI;
1895 ++AAI;
1896 }
1897 ActualAccesses.clear();
Daniel Berlind602e042017-01-25 20:56:19 +00001898 if (DL) {
1899 auto DLI = DL->begin();
1900 auto ADI = ActualDefs.begin();
1901 while (DLI != DL->end() && ADI != ActualDefs.end()) {
1902 assert(&*DLI == *ADI && "Not the same defs in the same order");
1903 ++DLI;
1904 ++ADI;
1905 }
1906 }
1907 ActualDefs.clear();
Daniel Berlin14300262016-06-21 18:39:20 +00001908 }
George Burgess IV6a9aa022018-08-28 00:32:32 +00001909#endif
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001910}
1911
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001912/// Verify the domination properties of MemorySSA by checking that each
George Burgess IVe1100f52016-02-02 22:46:49 +00001913/// definition dominates all of its uses.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001914void MemorySSA::verifyDomination(Function &F) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001915#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001916 for (BasicBlock &B : F) {
1917 // Phi nodes are attached to basic blocks
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001918 if (MemoryPhi *MP = getMemoryAccess(&B))
1919 for (const Use &U : MP->uses())
1920 assert(dominates(MP, U) && "Memory PHI does not dominate it's uses");
Daniel Berlin7af95872016-08-05 21:47:20 +00001921
George Burgess IVe1100f52016-02-02 22:46:49 +00001922 for (Instruction &I : B) {
1923 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
1924 if (!MD)
1925 continue;
1926
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001927 for (const Use &U : MD->uses())
1928 assert(dominates(MD, U) && "Memory Def does not dominate it's uses");
George Burgess IVe1100f52016-02-02 22:46:49 +00001929 }
1930 }
Daniel Berlin7af95872016-08-05 21:47:20 +00001931#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001932}
1933
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001934/// Verify the def-use lists in MemorySSA, by verifying that \p Use
George Burgess IVe1100f52016-02-02 22:46:49 +00001935/// appears in the use list of \p Def.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001936void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001937#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001938 // The live on entry use may cause us to get a NULL def here
Daniel Berlin7af95872016-08-05 21:47:20 +00001939 if (!Def)
1940 assert(isLiveOnEntryDef(Use) &&
1941 "Null def but use not point to live on entry def");
1942 else
Daniel Berlinda2f38e2016-08-11 21:26:50 +00001943 assert(is_contained(Def->users(), Use) &&
Daniel Berlin7af95872016-08-05 21:47:20 +00001944 "Did not find use in def's use list");
1945#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001946}
1947
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001948/// Verify the immediate use information, by walking all the memory
George Burgess IVe1100f52016-02-02 22:46:49 +00001949/// accesses and verifying that, for each use, it appears in the
1950/// appropriate def's use list
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001951void MemorySSA::verifyDefUses(Function &F) const {
George Burgess IV6a9aa022018-08-28 00:32:32 +00001952#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001953 for (BasicBlock &B : F) {
1954 // Phi nodes are attached to basic blocks
Daniel Berlin14300262016-06-21 18:39:20 +00001955 if (MemoryPhi *Phi = getMemoryAccess(&B)) {
David Majnemer580e7542016-06-25 00:04:06 +00001956 assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
1957 pred_begin(&B), pred_end(&B))) &&
Daniel Berlin14300262016-06-21 18:39:20 +00001958 "Incomplete MemoryPhi Node");
Alina Sbirlea201d02c2018-06-20 21:06:13 +00001959 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001960 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
Alina Sbirlea201d02c2018-06-20 21:06:13 +00001961 assert(find(predecessors(&B), Phi->getIncomingBlock(I)) !=
1962 pred_end(&B) &&
1963 "Incoming phi block not a block predecessor");
1964 }
Daniel Berlin14300262016-06-21 18:39:20 +00001965 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001966
1967 for (Instruction &I : B) {
George Burgess IV66837ab2016-11-01 21:17:46 +00001968 if (MemoryUseOrDef *MA = getMemoryAccess(&I)) {
1969 verifyUseInDefs(MA->getDefiningAccess(), MA);
George Burgess IVe1100f52016-02-02 22:46:49 +00001970 }
1971 }
1972 }
George Burgess IV6a9aa022018-08-28 00:32:32 +00001973#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001974}
1975
Daniel Berlin5c46b942016-07-19 22:49:43 +00001976/// Perform a local numbering on blocks so that instruction ordering can be
1977/// determined in constant time.
1978/// TODO: We currently just number in order. If we numbered by N, we could
1979/// allow at least N-1 sequences of insertBefore or insertAfter (and at least
1980/// log2(N) sequences of mixed before and after) without needing to invalidate
1981/// the numbering.
1982void MemorySSA::renumberBlock(const BasicBlock *B) const {
1983 // The pre-increment ensures the numbers really start at 1.
1984 unsigned long CurrentNumber = 0;
1985 const AccessList *AL = getBlockAccesses(B);
1986 assert(AL != nullptr && "Asking to renumber an empty block");
1987 for (const auto &I : *AL)
1988 BlockNumbering[&I] = ++CurrentNumber;
1989 BlockNumberingValid.insert(B);
1990}
1991
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001992/// Determine, for two memory accesses in the same block,
George Burgess IVe1100f52016-02-02 22:46:49 +00001993/// whether \p Dominator dominates \p Dominatee.
1994/// \returns True if \p Dominator dominates \p Dominatee.
1995bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
1996 const MemoryAccess *Dominatee) const {
Daniel Berlin5c46b942016-07-19 22:49:43 +00001997 const BasicBlock *DominatorBlock = Dominator->getBlock();
Daniel Berlin5c46b942016-07-19 22:49:43 +00001998
Daniel Berlin19860302016-07-19 23:08:08 +00001999 assert((DominatorBlock == Dominatee->getBlock()) &&
Daniel Berlin5c46b942016-07-19 22:49:43 +00002000 "Asking for local domination when accesses are in different blocks!");
Sebastian Pope1f60b12016-06-10 21:36:41 +00002001 // A node dominates itself.
2002 if (Dominatee == Dominator)
2003 return true;
2004
2005 // When Dominatee is defined on function entry, it is not dominated by another
2006 // memory access.
2007 if (isLiveOnEntryDef(Dominatee))
2008 return false;
2009
2010 // When Dominator is defined on function entry, it dominates the other memory
2011 // access.
2012 if (isLiveOnEntryDef(Dominator))
2013 return true;
2014
Daniel Berlin5c46b942016-07-19 22:49:43 +00002015 if (!BlockNumberingValid.count(DominatorBlock))
2016 renumberBlock(DominatorBlock);
George Burgess IVe1100f52016-02-02 22:46:49 +00002017
Daniel Berlin5c46b942016-07-19 22:49:43 +00002018 unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
2019 // All numbers start with 1
2020 assert(DominatorNum != 0 && "Block was not numbered properly");
2021 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
2022 assert(DominateeNum != 0 && "Block was not numbered properly");
2023 return DominatorNum < DominateeNum;
George Burgess IVe1100f52016-02-02 22:46:49 +00002024}
2025
George Burgess IV5f308972016-07-19 01:29:15 +00002026bool MemorySSA::dominates(const MemoryAccess *Dominator,
2027 const MemoryAccess *Dominatee) const {
2028 if (Dominator == Dominatee)
2029 return true;
2030
2031 if (isLiveOnEntryDef(Dominatee))
2032 return false;
2033
2034 if (Dominator->getBlock() != Dominatee->getBlock())
2035 return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
2036 return locallyDominates(Dominator, Dominatee);
2037}
2038
Daniel Berlin2919b1c2016-08-05 21:46:52 +00002039bool MemorySSA::dominates(const MemoryAccess *Dominator,
2040 const Use &Dominatee) const {
2041 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Dominatee.getUser())) {
2042 BasicBlock *UseBB = MP->getIncomingBlock(Dominatee);
2043 // The def must dominate the incoming block of the phi.
2044 if (UseBB != Dominator->getBlock())
2045 return DT->dominates(Dominator->getBlock(), UseBB);
2046 // If the UseBB and the DefBB are the same, compare locally.
2047 return locallyDominates(Dominator, cast<MemoryAccess>(Dominatee));
2048 }
2049 // If it's not a PHI node use, the normal dominates can already handle it.
2050 return dominates(Dominator, cast<MemoryAccess>(Dominatee.getUser()));
2051}
2052
George Burgess IVe1100f52016-02-02 22:46:49 +00002053const static char LiveOnEntryStr[] = "liveOnEntry";
2054
Reid Kleckner96ab8722017-05-18 17:24:10 +00002055void MemoryAccess::print(raw_ostream &OS) const {
2056 switch (getValueID()) {
2057 case MemoryPhiVal: return static_cast<const MemoryPhi *>(this)->print(OS);
2058 case MemoryDefVal: return static_cast<const MemoryDef *>(this)->print(OS);
2059 case MemoryUseVal: return static_cast<const MemoryUse *>(this)->print(OS);
2060 }
2061 llvm_unreachable("invalid value id");
2062}
2063
George Burgess IVe1100f52016-02-02 22:46:49 +00002064void MemoryDef::print(raw_ostream &OS) const {
2065 MemoryAccess *UO = getDefiningAccess();
2066
George Burgess IVaa283d82018-06-14 19:55:53 +00002067 auto printID = [&OS](MemoryAccess *A) {
2068 if (A && A->getID())
2069 OS << A->getID();
2070 else
2071 OS << LiveOnEntryStr;
2072 };
2073
George Burgess IVe1100f52016-02-02 22:46:49 +00002074 OS << getID() << " = MemoryDef(";
George Burgess IVaa283d82018-06-14 19:55:53 +00002075 printID(UO);
2076 OS << ")";
2077
2078 if (isOptimized()) {
2079 OS << "->";
2080 printID(getOptimized());
2081
2082 if (Optional<AliasResult> AR = getOptimizedAccessType())
2083 OS << " " << *AR;
2084 }
George Burgess IVe1100f52016-02-02 22:46:49 +00002085}
2086
2087void MemoryPhi::print(raw_ostream &OS) const {
2088 bool First = true;
2089 OS << getID() << " = MemoryPhi(";
2090 for (const auto &Op : operands()) {
2091 BasicBlock *BB = getIncomingBlock(Op);
2092 MemoryAccess *MA = cast<MemoryAccess>(Op);
2093 if (!First)
2094 OS << ',';
2095 else
2096 First = false;
2097
2098 OS << '{';
2099 if (BB->hasName())
2100 OS << BB->getName();
2101 else
2102 BB->printAsOperand(OS, false);
2103 OS << ',';
2104 if (unsigned ID = MA->getID())
2105 OS << ID;
2106 else
2107 OS << LiveOnEntryStr;
2108 OS << '}';
2109 }
2110 OS << ')';
2111}
2112
George Burgess IVe1100f52016-02-02 22:46:49 +00002113void MemoryUse::print(raw_ostream &OS) const {
2114 MemoryAccess *UO = getDefiningAccess();
2115 OS << "MemoryUse(";
2116 if (UO && UO->getID())
2117 OS << UO->getID();
2118 else
2119 OS << LiveOnEntryStr;
2120 OS << ')';
George Burgess IVaa283d82018-06-14 19:55:53 +00002121
2122 if (Optional<AliasResult> AR = getOptimizedAccessType())
2123 OS << " " << *AR;
George Burgess IVe1100f52016-02-02 22:46:49 +00002124}
2125
2126void MemoryAccess::dump() const {
Daniel Berlin78cbd282017-02-20 22:26:03 +00002127// Cannot completely remove virtual function even in release mode.
Aaron Ballman615eb472017-10-15 14:32:27 +00002128#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
George Burgess IVe1100f52016-02-02 22:46:49 +00002129 print(dbgs());
2130 dbgs() << "\n";
Matthias Braun8c209aa2017-01-28 02:02:38 +00002131#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00002132}
2133
Chad Rosier232e29e2016-07-06 21:20:47 +00002134char MemorySSAPrinterLegacyPass::ID = 0;
2135
2136MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) {
2137 initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
2138}
2139
2140void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
2141 AU.setPreservesAll();
2142 AU.addRequired<MemorySSAWrapperPass>();
Chad Rosier232e29e2016-07-06 21:20:47 +00002143}
2144
2145bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) {
2146 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
2147 MSSA.print(dbgs());
2148 if (VerifyMemorySSA)
2149 MSSA.verifyMemorySSA();
2150 return false;
2151}
2152
Chandler Carruthdab4eae2016-11-23 17:53:26 +00002153AnalysisKey MemorySSAAnalysis::Key;
George Burgess IVe1100f52016-02-02 22:46:49 +00002154
Daniel Berlin1e98c042016-09-26 17:22:54 +00002155MemorySSAAnalysis::Result MemorySSAAnalysis::run(Function &F,
2156 FunctionAnalysisManager &AM) {
Geoff Berryb96d3b22016-06-01 21:30:40 +00002157 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2158 auto &AA = AM.getResult<AAManager>(F);
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00002159 return MemorySSAAnalysis::Result(llvm::make_unique<MemorySSA>(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00002160}
2161
Geoff Berryb96d3b22016-06-01 21:30:40 +00002162PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
2163 FunctionAnalysisManager &AM) {
2164 OS << "MemorySSA for function: " << F.getName() << "\n";
Geoff Berry290a13e2016-08-08 18:27:22 +00002165 AM.getResult<MemorySSAAnalysis>(F).getMSSA().print(OS);
Geoff Berryb96d3b22016-06-01 21:30:40 +00002166
2167 return PreservedAnalyses::all();
George Burgess IVe1100f52016-02-02 22:46:49 +00002168}
2169
Geoff Berryb96d3b22016-06-01 21:30:40 +00002170PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
2171 FunctionAnalysisManager &AM) {
Geoff Berry290a13e2016-08-08 18:27:22 +00002172 AM.getResult<MemorySSAAnalysis>(F).getMSSA().verifyMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00002173
2174 return PreservedAnalyses::all();
2175}
2176
2177char MemorySSAWrapperPass::ID = 0;
2178
2179MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
2180 initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
2181}
2182
2183void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
2184
2185void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00002186 AU.setPreservesAll();
Geoff Berryb96d3b22016-06-01 21:30:40 +00002187 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
2188 AU.addRequiredTransitive<AAResultsWrapperPass>();
George Burgess IVe1100f52016-02-02 22:46:49 +00002189}
2190
Geoff Berryb96d3b22016-06-01 21:30:40 +00002191bool MemorySSAWrapperPass::runOnFunction(Function &F) {
2192 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2193 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2194 MSSA.reset(new MemorySSA(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00002195 return false;
2196}
2197
Geoff Berryb96d3b22016-06-01 21:30:40 +00002198void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); }
George Burgess IVe1100f52016-02-02 22:46:49 +00002199
Geoff Berryb96d3b22016-06-01 21:30:40 +00002200void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00002201 MSSA->print(OS);
2202}
2203
George Burgess IVe1100f52016-02-02 22:46:49 +00002204MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
2205
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002206/// Walk the use-def chains starting at \p StartingAccess and find
George Burgess IVe1100f52016-02-02 22:46:49 +00002207/// the MemoryAccess that actually clobbers Loc.
2208///
2209/// \returns our clobbering memory access
Alina Sbirleabfc779e2019-03-22 17:22:19 +00002210template <typename AliasAnalysisType>
2211MemoryAccess *
2212MemorySSA::ClobberWalkerBase<AliasAnalysisType>::getClobberingMemoryAccessBase(
George Burgess IV013fd732016-10-28 19:22:46 +00002213 MemoryAccess *StartingAccess, const MemoryLocation &Loc) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002214 if (isa<MemoryPhi>(StartingAccess))
2215 return StartingAccess;
2216
2217 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
2218 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
2219 return StartingUseOrDef;
2220
2221 Instruction *I = StartingUseOrDef->getMemoryInst();
2222
2223 // Conservatively, fences are always clobbers, so don't perform the walk if we
2224 // hit a fence.
Chandler Carruth363ac682019-01-07 05:42:51 +00002225 if (!isa<CallBase>(I) && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002226 return StartingUseOrDef;
2227
2228 UpwardsMemoryQuery Q;
2229 Q.OriginalAccess = StartingUseOrDef;
2230 Q.StartingLoc = Loc;
George Burgess IV5f308972016-07-19 01:29:15 +00002231 Q.Inst = I;
George Burgess IVe1100f52016-02-02 22:46:49 +00002232 Q.IsCall = false;
George Burgess IVe1100f52016-02-02 22:46:49 +00002233
George Burgess IVe1100f52016-02-02 22:46:49 +00002234 // Unlike the other function, do not walk to the def of a def, because we are
2235 // handed something we already believe is the clobbering access.
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002236 // We never set SkipSelf to true in Q in this method.
George Burgess IVe1100f52016-02-02 22:46:49 +00002237 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
2238 ? StartingUseOrDef->getDefiningAccess()
2239 : StartingUseOrDef;
2240
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002241 MemoryAccess *Clobber = Walker.findClobber(DefiningAccess, Q);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002242 LLVM_DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2243 LLVM_DEBUG(dbgs() << *StartingUseOrDef << "\n");
2244 LLVM_DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2245 LLVM_DEBUG(dbgs() << *Clobber << "\n");
George Burgess IVe1100f52016-02-02 22:46:49 +00002246 return Clobber;
2247}
2248
Alina Sbirleabfc779e2019-03-22 17:22:19 +00002249template <typename AliasAnalysisType>
George Burgess IVe1100f52016-02-02 22:46:49 +00002250MemoryAccess *
Alina Sbirleabfc779e2019-03-22 17:22:19 +00002251MemorySSA::ClobberWalkerBase<AliasAnalysisType>::getClobberingMemoryAccessBase(
2252 MemoryAccess *MA, bool SkipSelf) {
George Burgess IV400ae402016-07-20 19:51:34 +00002253 auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
2254 // If this is a MemoryPhi, we can't do anything.
2255 if (!StartingAccess)
2256 return MA;
George Burgess IVe1100f52016-02-02 22:46:49 +00002257
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002258 bool IsOptimized = false;
2259
Daniel Berlincd2deac2016-10-20 20:13:45 +00002260 // If this is an already optimized use or def, return the optimized result.
Alina Sbirlead90c9f42018-03-08 18:03:14 +00002261 // Note: Currently, we store the optimized def result in a separate field,
2262 // since we can't use the defining access.
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002263 if (StartingAccess->isOptimized()) {
2264 if (!SkipSelf || !isa<MemoryDef>(StartingAccess))
2265 return StartingAccess->getOptimized();
2266 IsOptimized = true;
2267 }
Daniel Berlincd2deac2016-10-20 20:13:45 +00002268
George Burgess IV400ae402016-07-20 19:51:34 +00002269 const Instruction *I = StartingAccess->getMemoryInst();
George Burgess IV44477c62018-03-11 04:16:12 +00002270 // We can't sanely do anything with a fence, since they conservatively clobber
2271 // all memory, and have no locations to get pointers from to try to
2272 // disambiguate.
Chandler Carruth363ac682019-01-07 05:42:51 +00002273 if (!isa<CallBase>(I) && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002274 return StartingAccess;
2275
Alina Sbirleab4d088d2018-11-13 21:12:49 +00002276 UpwardsMemoryQuery Q(I, StartingAccess);
2277
Alina Sbirleabfc779e2019-03-22 17:22:19 +00002278 if (isUseTriviallyOptimizableToLiveOnEntry(*Walker.getAA(), I)) {
George Burgess IV024f3d22016-08-03 19:57:02 +00002279 MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef();
George Burgess IV44477c62018-03-11 04:16:12 +00002280 StartingAccess->setOptimized(LiveOnEntry);
2281 StartingAccess->setOptimizedAccessType(None);
George Burgess IV024f3d22016-08-03 19:57:02 +00002282 return LiveOnEntry;
2283 }
2284
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002285 MemoryAccess *OptimizedAccess;
2286 if (!IsOptimized) {
2287 // Start with the thing we already think clobbers this location
2288 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
George Burgess IVe1100f52016-02-02 22:46:49 +00002289
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002290 // At this point, DefiningAccess may be the live on entry def.
2291 // If it is, we will not get a better result.
2292 if (MSSA->isLiveOnEntryDef(DefiningAccess)) {
2293 StartingAccess->setOptimized(DefiningAccess);
2294 StartingAccess->setOptimizedAccessType(None);
2295 return DefiningAccess;
2296 }
George Burgess IVe1100f52016-02-02 22:46:49 +00002297
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002298 OptimizedAccess = Walker.findClobber(DefiningAccess, Q);
2299 StartingAccess->setOptimized(OptimizedAccess);
2300 if (MSSA->isLiveOnEntryDef(OptimizedAccess))
2301 StartingAccess->setOptimizedAccessType(None);
2302 else if (Q.AR == MustAlias)
2303 StartingAccess->setOptimizedAccessType(MustAlias);
2304 } else
2305 OptimizedAccess = StartingAccess->getOptimized();
2306
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002307 LLVM_DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002308 LLVM_DEBUG(dbgs() << *StartingAccess << "\n");
2309 LLVM_DEBUG(dbgs() << "Optimized Memory SSA clobber for " << *I << " is ");
2310 LLVM_DEBUG(dbgs() << *OptimizedAccess << "\n");
Alina Sbirlead90c9f42018-03-08 18:03:14 +00002311
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002312 MemoryAccess *Result;
2313 if (SkipSelf && isa<MemoryPhi>(OptimizedAccess) &&
2314 isa<MemoryDef>(StartingAccess)) {
2315 assert(isa<MemoryDef>(Q.OriginalAccess));
2316 Q.SkipSelfAccess = true;
2317 Result = Walker.findClobber(OptimizedAccess, Q);
2318 } else
2319 Result = OptimizedAccess;
2320
2321 LLVM_DEBUG(dbgs() << "Result Memory SSA clobber [SkipSelf = " << SkipSelf);
2322 LLVM_DEBUG(dbgs() << "] for " << *I << " is " << *Result << "\n");
George Burgess IVe1100f52016-02-02 22:46:49 +00002323
2324 return Result;
2325}
2326
George Burgess IVe1100f52016-02-02 22:46:49 +00002327MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002328DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002329 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
2330 return Use->getDefiningAccess();
2331 return MA;
2332}
2333
2334MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
George Burgess IV013fd732016-10-28 19:22:46 +00002335 MemoryAccess *StartingAccess, const MemoryLocation &) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002336 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
2337 return Use->getDefiningAccess();
2338 return StartingAccess;
2339}
Reid Kleckner96ab8722017-05-18 17:24:10 +00002340
2341void MemoryPhi::deleteMe(DerivedUser *Self) {
2342 delete static_cast<MemoryPhi *>(Self);
2343}
2344
2345void MemoryDef::deleteMe(DerivedUser *Self) {
2346 delete static_cast<MemoryDef *>(Self);
2347}
2348
2349void MemoryUse::deleteMe(DerivedUser *Self) {
2350 delete static_cast<MemoryUse *>(Self);
2351}