blob: da2d0f81748593ac5bae5fedd0e1531ad66e7cb1 [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>
Alina Sbirlea63e97fa2019-07-31 17:41:04 +000052#include <cstdlib>
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000053#include <iterator>
54#include <memory>
55#include <utility>
56
57using namespace llvm;
George Burgess IVe1100f52016-02-02 22:46:49 +000058
59#define DEBUG_TYPE "memoryssa"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000060
Geoff Berryefb0dd12016-06-14 21:19:40 +000061INITIALIZE_PASS_BEGIN(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
Geoff Berryb96d3b22016-06-01 21:30:40 +000062 true)
George Burgess IVe1100f52016-02-02 22:46:49 +000063INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
64INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Geoff Berryefb0dd12016-06-14 21:19:40 +000065INITIALIZE_PASS_END(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
66 true)
George Burgess IVe1100f52016-02-02 22:46:49 +000067
Chad Rosier232e29e2016-07-06 21:20:47 +000068INITIALIZE_PASS_BEGIN(MemorySSAPrinterLegacyPass, "print-memoryssa",
69 "Memory SSA Printer", false, false)
70INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
71INITIALIZE_PASS_END(MemorySSAPrinterLegacyPass, "print-memoryssa",
72 "Memory SSA Printer", false, false)
73
Daniel Berlinc43aa5a2016-08-02 16:24:03 +000074static cl::opt<unsigned> MaxCheckLimit(
75 "memssa-check-limit", cl::Hidden, cl::init(100),
76 cl::desc("The maximum number of stores/phis MemorySSA"
77 "will consider trying to walk past (default = 100)"));
78
Alina Sbirleacc2e8cc2018-08-15 17:34:55 +000079// Always verify MemorySSA if expensive checking is enabled.
80#ifdef EXPENSIVE_CHECKS
81bool llvm::VerifyMemorySSA = true;
82#else
83bool llvm::VerifyMemorySSA = false;
84#endif
Alina Sbirlea4fd1f262019-04-23 20:59:44 +000085/// Enables memory ssa as a dependency for loop passes in legacy pass manager.
86cl::opt<bool> llvm::EnableMSSALoopDependency(
Alina Sbirlea6da79ce2019-09-04 19:16:04 +000087 "enable-mssa-loop-dependency", cl::Hidden, cl::init(true),
Alina Sbirlea4fd1f262019-04-23 20:59:44 +000088 cl::desc("Enable MemorySSA dependency for loop pass manager"));
89
Alina Sbirleacc2e8cc2018-08-15 17:34:55 +000090static cl::opt<bool, true>
91 VerifyMemorySSAX("verify-memoryssa", cl::location(VerifyMemorySSA),
92 cl::Hidden, cl::desc("Enable verification of MemorySSA."));
Chad Rosier232e29e2016-07-06 21:20:47 +000093
George Burgess IVe1100f52016-02-02 22:46:49 +000094namespace llvm {
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000095
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000096/// An assembly annotator class to print Memory SSA information in
George Burgess IVe1100f52016-02-02 22:46:49 +000097/// comments.
98class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter {
99 friend class MemorySSA;
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000100
George Burgess IVe1100f52016-02-02 22:46:49 +0000101 const MemorySSA *MSSA;
102
103public:
104 MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {}
105
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000106 void emitBasicBlockStartAnnot(const BasicBlock *BB,
107 formatted_raw_ostream &OS) override {
George Burgess IVe1100f52016-02-02 22:46:49 +0000108 if (MemoryAccess *MA = MSSA->getMemoryAccess(BB))
109 OS << "; " << *MA << "\n";
110 }
111
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000112 void emitInstructionAnnot(const Instruction *I,
113 formatted_raw_ostream &OS) override {
George Burgess IVe1100f52016-02-02 22:46:49 +0000114 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
115 OS << "; " << *MA << "\n";
116 }
117};
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000118
119} // end namespace llvm
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000120
George Burgess IV5f308972016-07-19 01:29:15 +0000121namespace {
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000122
Daniel Berlindff31de2016-08-02 21:57:52 +0000123/// Our current alias analysis API differentiates heavily between calls and
124/// non-calls, and functions called on one usually assert on the other.
125/// This class encapsulates the distinction to simplify other code that wants
126/// "Memory affecting instructions and related data" to use as a key.
127/// For example, this class is used as a densemap key in the use optimizer.
128class MemoryLocOrCall {
129public:
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000130 bool IsCall = false;
131
Daniel Berlindff31de2016-08-02 21:57:52 +0000132 MemoryLocOrCall(MemoryUseOrDef *MUD)
133 : MemoryLocOrCall(MUD->getMemoryInst()) {}
Sebastian Pop5068d7a2016-10-13 03:23:33 +0000134 MemoryLocOrCall(const MemoryUseOrDef *MUD)
135 : MemoryLocOrCall(MUD->getMemoryInst()) {}
Daniel Berlindff31de2016-08-02 21:57:52 +0000136
137 MemoryLocOrCall(Instruction *Inst) {
Chandler Carruth363ac682019-01-07 05:42:51 +0000138 if (auto *C = dyn_cast<CallBase>(Inst)) {
Daniel Berlindff31de2016-08-02 21:57:52 +0000139 IsCall = true;
Chandler Carruth363ac682019-01-07 05:42:51 +0000140 Call = C;
Daniel Berlindff31de2016-08-02 21:57:52 +0000141 } else {
142 IsCall = false;
143 // There is no such thing as a memorylocation for a fence inst, and it is
144 // unique in that regard.
145 if (!isa<FenceInst>(Inst))
146 Loc = MemoryLocation::get(Inst);
147 }
148 }
149
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000150 explicit MemoryLocOrCall(const MemoryLocation &Loc) : Loc(Loc) {}
Daniel Berlindff31de2016-08-02 21:57:52 +0000151
Chandler Carruth363ac682019-01-07 05:42:51 +0000152 const CallBase *getCall() const {
Daniel Berlindff31de2016-08-02 21:57:52 +0000153 assert(IsCall);
Chandler Carruth363ac682019-01-07 05:42:51 +0000154 return Call;
Daniel Berlindff31de2016-08-02 21:57:52 +0000155 }
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000156
Daniel Berlindff31de2016-08-02 21:57:52 +0000157 MemoryLocation getLoc() const {
158 assert(!IsCall);
159 return Loc;
160 }
161
162 bool operator==(const MemoryLocOrCall &Other) const {
163 if (IsCall != Other.IsCall)
164 return false;
165
George Burgess IV3588fd42018-03-29 00:54:39 +0000166 if (!IsCall)
167 return Loc == Other.Loc;
168
Chandler Carruth363ac682019-01-07 05:42:51 +0000169 if (Call->getCalledValue() != Other.Call->getCalledValue())
George Burgess IV3588fd42018-03-29 00:54:39 +0000170 return false;
171
Chandler Carruth363ac682019-01-07 05:42:51 +0000172 return Call->arg_size() == Other.Call->arg_size() &&
173 std::equal(Call->arg_begin(), Call->arg_end(),
174 Other.Call->arg_begin());
Daniel Berlindff31de2016-08-02 21:57:52 +0000175 }
176
177private:
Daniel Berlinf5361132016-10-22 04:15:41 +0000178 union {
Chandler Carruth363ac682019-01-07 05:42:51 +0000179 const CallBase *Call;
Daniel Berlind602e042017-01-25 20:56:19 +0000180 MemoryLocation Loc;
Daniel Berlinf5361132016-10-22 04:15:41 +0000181 };
Daniel Berlindff31de2016-08-02 21:57:52 +0000182};
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000183
184} // end anonymous namespace
Daniel Berlindff31de2016-08-02 21:57:52 +0000185
186namespace llvm {
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000187
Daniel Berlindff31de2016-08-02 21:57:52 +0000188template <> struct DenseMapInfo<MemoryLocOrCall> {
189 static inline MemoryLocOrCall getEmptyKey() {
190 return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getEmptyKey());
191 }
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000192
Daniel Berlindff31de2016-08-02 21:57:52 +0000193 static inline MemoryLocOrCall getTombstoneKey() {
194 return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getTombstoneKey());
195 }
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000196
Daniel Berlindff31de2016-08-02 21:57:52 +0000197 static unsigned getHashValue(const MemoryLocOrCall &MLOC) {
George Burgess IV3588fd42018-03-29 00:54:39 +0000198 if (!MLOC.IsCall)
199 return hash_combine(
200 MLOC.IsCall,
201 DenseMapInfo<MemoryLocation>::getHashValue(MLOC.getLoc()));
202
203 hash_code hash =
204 hash_combine(MLOC.IsCall, DenseMapInfo<const Value *>::getHashValue(
Chandler Carruth363ac682019-01-07 05:42:51 +0000205 MLOC.getCall()->getCalledValue()));
George Burgess IV3588fd42018-03-29 00:54:39 +0000206
Chandler Carruth363ac682019-01-07 05:42:51 +0000207 for (const Value *Arg : MLOC.getCall()->args())
George Burgess IV3588fd42018-03-29 00:54:39 +0000208 hash = hash_combine(hash, DenseMapInfo<const Value *>::getHashValue(Arg));
209 return hash;
Daniel Berlindff31de2016-08-02 21:57:52 +0000210 }
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000211
Daniel Berlindff31de2016-08-02 21:57:52 +0000212 static bool isEqual(const MemoryLocOrCall &LHS, const MemoryLocOrCall &RHS) {
213 return LHS == RHS;
214 }
215};
Daniel Berlindf101192016-08-03 00:01:46 +0000216
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000217} // end namespace llvm
218
George Burgess IV82e355c2016-08-03 19:39:54 +0000219/// This does one-way checks to see if Use could theoretically be hoisted above
220/// MayClobber. This will not check the other way around.
221///
222/// This assumes that, for the purposes of MemorySSA, Use comes directly after
223/// MayClobber, with no potentially clobbering operations in between them.
224/// (Where potentially clobbering ops are memory barriers, aliased stores, etc.)
Alina Sbirleaca741a82017-12-22 19:54:03 +0000225static bool areLoadsReorderable(const LoadInst *Use,
226 const LoadInst *MayClobber) {
George Burgess IV82e355c2016-08-03 19:39:54 +0000227 bool VolatileUse = Use->isVolatile();
228 bool VolatileClobber = MayClobber->isVolatile();
229 // Volatile operations may never be reordered with other volatile operations.
230 if (VolatileUse && VolatileClobber)
Alina Sbirleaca741a82017-12-22 19:54:03 +0000231 return false;
232 // Otherwise, volatile doesn't matter here. From the language reference:
233 // 'optimizers may change the order of volatile operations relative to
234 // non-volatile operations.'"
George Burgess IV82e355c2016-08-03 19:39:54 +0000235
236 // If a load is seq_cst, it cannot be moved above other loads. If its ordering
237 // is weaker, it can be moved above other loads. We just need to be sure that
238 // MayClobber isn't an acquire load, because loads can't be moved above
239 // acquire loads.
240 //
241 // Note that this explicitly *does* allow the free reordering of monotonic (or
242 // weaker) loads of the same address.
243 bool SeqCstUse = Use->getOrdering() == AtomicOrdering::SequentiallyConsistent;
244 bool MayClobberIsAcquire = isAtLeastOrStrongerThan(MayClobber->getOrdering(),
245 AtomicOrdering::Acquire);
Alina Sbirleaca741a82017-12-22 19:54:03 +0000246 return !(SeqCstUse || MayClobberIsAcquire);
George Burgess IV82e355c2016-08-03 19:39:54 +0000247}
248
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000249namespace {
250
251struct ClobberAlias {
252 bool IsClobber;
253 Optional<AliasResult> AR;
254};
255
256} // end anonymous namespace
257
258// Return a pair of {IsClobber (bool), AR (AliasResult)}. It relies on AR being
259// ignored if IsClobber = false.
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000260template <typename AliasAnalysisType>
261static ClobberAlias
262instructionClobbersQuery(const MemoryDef *MD, const MemoryLocation &UseLoc,
263 const Instruction *UseInst, AliasAnalysisType &AA) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000264 Instruction *DefInst = MD->getMemoryInst();
265 assert(DefInst && "Defining instruction not actually an instruction");
Chandler Carruth363ac682019-01-07 05:42:51 +0000266 const auto *UseCall = dyn_cast<CallBase>(UseInst);
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000267 Optional<AliasResult> AR;
George Burgess IV5f308972016-07-19 01:29:15 +0000268
Daniel Berlindf101192016-08-03 00:01:46 +0000269 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) {
270 // These intrinsics will show up as affecting memory, but they are just
George Burgess IVff08c802018-08-10 05:14:43 +0000271 // markers, mostly.
272 //
273 // FIXME: We probably don't actually want MemorySSA to model these at all
274 // (including creating MemoryAccesses for them): we just end up inventing
275 // clobbers where they don't really exist at all. Please see D43269 for
276 // context.
Daniel Berlindf101192016-08-03 00:01:46 +0000277 switch (II->getIntrinsicID()) {
278 case Intrinsic::lifetime_start:
Chandler Carruth363ac682019-01-07 05:42:51 +0000279 if (UseCall)
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000280 return {false, NoAlias};
281 AR = AA.alias(MemoryLocation(II->getArgOperand(1)), UseLoc);
George Burgess IVff08c802018-08-10 05:14:43 +0000282 return {AR != NoAlias, AR};
Daniel Berlindf101192016-08-03 00:01:46 +0000283 case Intrinsic::lifetime_end:
284 case Intrinsic::invariant_start:
285 case Intrinsic::invariant_end:
286 case Intrinsic::assume:
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000287 return {false, NoAlias};
Alina Sbirleaf7b40222019-09-10 22:35:27 +0000288 case Intrinsic::dbg_addr:
289 case Intrinsic::dbg_declare:
290 case Intrinsic::dbg_label:
291 case Intrinsic::dbg_value:
292 llvm_unreachable("debuginfo shouldn't have associated defs!");
Daniel Berlindf101192016-08-03 00:01:46 +0000293 default:
294 break;
295 }
296 }
297
Chandler Carruth363ac682019-01-07 05:42:51 +0000298 if (UseCall) {
299 ModRefInfo I = AA.getModRefInfo(DefInst, UseCall);
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000300 AR = isMustSet(I) ? MustAlias : MayAlias;
301 return {isModOrRefSet(I), AR};
Hans Wennborg70e22d12017-11-21 18:00:01 +0000302 }
George Burgess IV82e355c2016-08-03 19:39:54 +0000303
Alina Sbirleaca741a82017-12-22 19:54:03 +0000304 if (auto *DefLoad = dyn_cast<LoadInst>(DefInst))
305 if (auto *UseLoad = dyn_cast<LoadInst>(UseInst))
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000306 return {!areLoadsReorderable(UseLoad, DefLoad), MayAlias};
George Burgess IV82e355c2016-08-03 19:39:54 +0000307
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000308 ModRefInfo I = AA.getModRefInfo(DefInst, UseLoc);
309 AR = isMustSet(I) ? MustAlias : MayAlias;
310 return {isModSet(I), AR};
Daniel Berlindff31de2016-08-02 21:57:52 +0000311}
312
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000313template <typename AliasAnalysisType>
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000314static ClobberAlias instructionClobbersQuery(MemoryDef *MD,
315 const MemoryUseOrDef *MU,
316 const MemoryLocOrCall &UseMLOC,
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000317 AliasAnalysisType &AA) {
Sebastian Pop5068d7a2016-10-13 03:23:33 +0000318 // FIXME: This is a temporary hack to allow a single instructionClobbersQuery
319 // to exist while MemoryLocOrCall is pushed through places.
320 if (UseMLOC.IsCall)
321 return instructionClobbersQuery(MD, MemoryLocation(), MU->getMemoryInst(),
322 AA);
323 return instructionClobbersQuery(MD, UseMLOC.getLoc(), MU->getMemoryInst(),
324 AA);
325}
326
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000327// Return true when MD may alias MU, return false otherwise.
Daniel Berlindcb004f2017-03-02 23:06:46 +0000328bool MemorySSAUtil::defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU,
329 AliasAnalysis &AA) {
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000330 return instructionClobbersQuery(MD, MU, MemoryLocOrCall(MU), AA).IsClobber;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000331}
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000332
333namespace {
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000334
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000335struct UpwardsMemoryQuery {
336 // True if our original query started off as a call
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000337 bool IsCall = false;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000338 // The pointer location we started the query with. This will be empty if
339 // IsCall is true.
340 MemoryLocation StartingLoc;
341 // This is the instruction we were querying about.
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000342 const Instruction *Inst = nullptr;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000343 // The MemoryAccess we actually got called with, used to test local domination
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000344 const MemoryAccess *OriginalAccess = nullptr;
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000345 Optional<AliasResult> AR = MayAlias;
Alina Sbirleaf7230202019-01-07 18:40:27 +0000346 bool SkipSelfAccess = false;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000347
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000348 UpwardsMemoryQuery() = default;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000349
350 UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access)
Chandler Carruth363ac682019-01-07 05:42:51 +0000351 : IsCall(isa<CallBase>(Inst)), Inst(Inst), OriginalAccess(Access) {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000352 if (!IsCall)
353 StartingLoc = MemoryLocation::get(Inst);
354 }
355};
356
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000357} // end anonymous namespace
358
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000359static bool lifetimeEndsAt(MemoryDef *MD, const MemoryLocation &Loc,
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000360 BatchAAResults &AA) {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000361 Instruction *Inst = MD->getMemoryInst();
362 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
363 switch (II->getIntrinsicID()) {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000364 case Intrinsic::lifetime_end:
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000365 return AA.alias(MemoryLocation(II->getArgOperand(1)), Loc) == MustAlias;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000366 default:
367 return false;
368 }
369 }
370 return false;
371}
372
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000373template <typename AliasAnalysisType>
374static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysisType &AA,
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000375 const Instruction *I) {
376 // If the memory can't be changed, then loads of the memory can't be
377 // clobbered.
Philip Reames42282452019-09-04 18:27:31 +0000378 return isa<LoadInst>(I) && (I->hasMetadata(LLVMContext::MD_invariant_load) ||
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000379 AA.pointsToConstantMemory(MemoryLocation(
380 cast<LoadInst>(I)->getPointerOperand())));
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000381}
382
George Burgess IV5f308972016-07-19 01:29:15 +0000383/// Verifies that `Start` is clobbered by `ClobberAt`, and that nothing
384/// inbetween `Start` and `ClobberAt` can clobbers `Start`.
385///
386/// This is meant to be as simple and self-contained as possible. Because it
387/// uses no cache, etc., it can be relatively expensive.
388///
389/// \param Start The MemoryAccess that we want to walk from.
390/// \param ClobberAt A clobber for Start.
391/// \param StartLoc The MemoryLocation for Start.
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000392/// \param MSSA The MemorySSA instance that Start and ClobberAt belong to.
George Burgess IV5f308972016-07-19 01:29:15 +0000393/// \param Query The UpwardsMemoryQuery we used for our search.
394/// \param AA The AliasAnalysis we used for our search.
Alina Sbirlea65f385d2018-09-07 23:51:41 +0000395/// \param AllowImpreciseClobber Always false, unless we do relaxed verify.
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000396
397template <typename AliasAnalysisType>
Alina Sbirlead77edc02019-02-11 19:51:21 +0000398LLVM_ATTRIBUTE_UNUSED static void
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000399checkClobberSanity(const MemoryAccess *Start, MemoryAccess *ClobberAt,
George Burgess IV5f308972016-07-19 01:29:15 +0000400 const MemoryLocation &StartLoc, const MemorySSA &MSSA,
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000401 const UpwardsMemoryQuery &Query, AliasAnalysisType &AA,
Alina Sbirlea65f385d2018-09-07 23:51:41 +0000402 bool AllowImpreciseClobber = false) {
George Burgess IV5f308972016-07-19 01:29:15 +0000403 assert(MSSA.dominates(ClobberAt, Start) && "Clobber doesn't dominate start?");
404
405 if (MSSA.isLiveOnEntryDef(Start)) {
406 assert(MSSA.isLiveOnEntryDef(ClobberAt) &&
407 "liveOnEntry must clobber itself");
408 return;
409 }
410
George Burgess IV5f308972016-07-19 01:29:15 +0000411 bool FoundClobber = false;
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000412 DenseSet<ConstMemoryAccessPair> VisitedPhis;
413 SmallVector<ConstMemoryAccessPair, 8> Worklist;
George Burgess IV5f308972016-07-19 01:29:15 +0000414 Worklist.emplace_back(Start, StartLoc);
415 // Walk all paths from Start to ClobberAt, while looking for clobbers. If one
416 // is found, complain.
417 while (!Worklist.empty()) {
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000418 auto MAP = Worklist.pop_back_val();
George Burgess IV5f308972016-07-19 01:29:15 +0000419 // All we care about is that nothing from Start to ClobberAt clobbers Start.
420 // We learn nothing from revisiting nodes.
421 if (!VisitedPhis.insert(MAP).second)
422 continue;
423
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000424 for (const auto *MA : def_chain(MAP.first)) {
George Burgess IV5f308972016-07-19 01:29:15 +0000425 if (MA == ClobberAt) {
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000426 if (const auto *MD = dyn_cast<MemoryDef>(MA)) {
George Burgess IV5f308972016-07-19 01:29:15 +0000427 // instructionClobbersQuery isn't essentially free, so don't use `|=`,
428 // since it won't let us short-circuit.
429 //
430 // Also, note that this can't be hoisted out of the `Worklist` loop,
431 // since MD may only act as a clobber for 1 of N MemoryLocations.
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000432 FoundClobber = FoundClobber || MSSA.isLiveOnEntryDef(MD);
433 if (!FoundClobber) {
434 ClobberAlias CA =
435 instructionClobbersQuery(MD, MAP.second, Query.Inst, AA);
436 if (CA.IsClobber) {
437 FoundClobber = true;
438 // Not used: CA.AR;
439 }
440 }
George Burgess IV5f308972016-07-19 01:29:15 +0000441 }
442 break;
443 }
444
445 // We should never hit liveOnEntry, unless it's the clobber.
446 assert(!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?");
447
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000448 if (const auto *MD = dyn_cast<MemoryDef>(MA)) {
Alina Sbirlea5bce4d52018-08-29 22:38:51 +0000449 // If Start is a Def, skip self.
450 if (MD == Start)
451 continue;
452
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000453 assert(!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA)
454 .IsClobber &&
George Burgess IV5f308972016-07-19 01:29:15 +0000455 "Found clobber before reaching ClobberAt!");
456 continue;
457 }
458
Alina Sbirlea5bce4d52018-08-29 22:38:51 +0000459 if (const auto *MU = dyn_cast<MemoryUse>(MA)) {
Alina Sbirlea6edcc9e2018-08-29 23:20:29 +0000460 (void)MU;
Alina Sbirlea5bce4d52018-08-29 22:38:51 +0000461 assert (MU == Start &&
462 "Can only find use in def chain if Start is a use");
463 continue;
464 }
465
George Burgess IV5f308972016-07-19 01:29:15 +0000466 assert(isa<MemoryPhi>(MA));
Alina Sbirleaf5403d82018-08-29 18:26:04 +0000467 Worklist.append(
468 upward_defs_begin({const_cast<MemoryAccess *>(MA), MAP.second}),
469 upward_defs_end());
George Burgess IV5f308972016-07-19 01:29:15 +0000470 }
471 }
472
Alina Sbirlea65f385d2018-09-07 23:51:41 +0000473 // If the verify is done following an optimization, it's possible that
474 // ClobberAt was a conservative clobbering, that we can now infer is not a
475 // true clobbering access. Don't fail the verify if that's the case.
476 // We do have accesses that claim they're optimized, but could be optimized
477 // further. Updating all these can be expensive, so allow it for now (FIXME).
478 if (AllowImpreciseClobber)
479 return;
480
George Burgess IV5f308972016-07-19 01:29:15 +0000481 // If ClobberAt is a MemoryPhi, we can assume something above it acted as a
482 // clobber. Otherwise, `ClobberAt` should've acted as a clobber at some point.
483 assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&
484 "ClobberAt never acted as a clobber");
485}
486
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000487namespace {
488
George Burgess IV5f308972016-07-19 01:29:15 +0000489/// Our algorithm for walking (and trying to optimize) clobbers, all wrapped up
490/// in one class.
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000491template <class AliasAnalysisType> class ClobberWalker {
George Burgess IV5f308972016-07-19 01:29:15 +0000492 /// Save a few bytes by using unsigned instead of size_t.
493 using ListIndex = unsigned;
494
495 /// Represents a span of contiguous MemoryDefs, potentially ending in a
496 /// MemoryPhi.
497 struct DefPath {
498 MemoryLocation Loc;
499 // Note that, because we always walk in reverse, Last will always dominate
500 // First. Also note that First and Last are inclusive.
501 MemoryAccess *First;
502 MemoryAccess *Last;
George Burgess IV5f308972016-07-19 01:29:15 +0000503 Optional<ListIndex> Previous;
504
505 DefPath(const MemoryLocation &Loc, MemoryAccess *First, MemoryAccess *Last,
506 Optional<ListIndex> Previous)
507 : Loc(Loc), First(First), Last(Last), Previous(Previous) {}
508
509 DefPath(const MemoryLocation &Loc, MemoryAccess *Init,
510 Optional<ListIndex> Previous)
511 : DefPath(Loc, Init, Init, Previous) {}
512 };
513
514 const MemorySSA &MSSA;
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000515 AliasAnalysisType &AA;
George Burgess IV5f308972016-07-19 01:29:15 +0000516 DominatorTree &DT;
George Burgess IV5f308972016-07-19 01:29:15 +0000517 UpwardsMemoryQuery *Query;
Alina Sbirleaf085cc52019-03-29 21:56:09 +0000518 unsigned *UpwardWalkLimit;
George Burgess IV5f308972016-07-19 01:29:15 +0000519
520 // Phi optimization bookkeeping
521 SmallVector<DefPath, 32> Paths;
522 DenseSet<ConstMemoryAccessPair> VisitedPhis;
George Burgess IV5f308972016-07-19 01:29:15 +0000523
George Burgess IV5f308972016-07-19 01:29:15 +0000524 /// Find the nearest def or phi that `From` can legally be optimized to.
Daniel Berlind0420312017-04-01 09:01:12 +0000525 const MemoryAccess *getWalkTarget(const MemoryPhi *From) const {
George Burgess IV5f308972016-07-19 01:29:15 +0000526 assert(From->getNumOperands() && "Phi with no operands?");
527
528 BasicBlock *BB = From->getBlock();
George Burgess IV5f308972016-07-19 01:29:15 +0000529 MemoryAccess *Result = MSSA.getLiveOnEntryDef();
530 DomTreeNode *Node = DT.getNode(BB);
531 while ((Node = Node->getIDom())) {
Daniel Berlin7500c562017-04-01 08:59:45 +0000532 auto *Defs = MSSA.getBlockDefs(Node->getBlock());
533 if (Defs)
Daniel Berlind0420312017-04-01 09:01:12 +0000534 return &*Defs->rbegin();
George Burgess IV5f308972016-07-19 01:29:15 +0000535 }
George Burgess IV5f308972016-07-19 01:29:15 +0000536 return Result;
537 }
538
539 /// Result of calling walkToPhiOrClobber.
540 struct UpwardsWalkResult {
541 /// The "Result" of the walk. Either a clobber, the last thing we walked, or
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000542 /// both. Include alias info when clobber found.
George Burgess IV5f308972016-07-19 01:29:15 +0000543 MemoryAccess *Result;
544 bool IsKnownClobber;
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000545 Optional<AliasResult> AR;
George Burgess IV5f308972016-07-19 01:29:15 +0000546 };
547
548 /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last.
549 /// This will update Desc.Last as it walks. It will (optionally) also stop at
550 /// StopAt.
551 ///
552 /// This does not test for whether StopAt is a clobber
Daniel Berlind0420312017-04-01 09:01:12 +0000553 UpwardsWalkResult
Alina Sbirleaf7230202019-01-07 18:40:27 +0000554 walkToPhiOrClobber(DefPath &Desc, const MemoryAccess *StopAt = nullptr,
555 const MemoryAccess *SkipStopAt = nullptr) const {
George Burgess IV5f308972016-07-19 01:29:15 +0000556 assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");
Alina Sbirleac8d6e042019-03-29 22:55:59 +0000557 assert(UpwardWalkLimit && "Need a valid walk limit");
Alina Sbirlea57769382019-04-12 18:48:46 +0000558 bool LimitAlreadyReached = false;
559 // (*UpwardWalkLimit) may be 0 here, due to the loop in tryOptimizePhi. Set
560 // it to 1. This will not do any alias() calls. It either returns in the
561 // first iteration in the loop below, or is set back to 0 if all def chains
562 // are free of MemoryDefs.
563 if (!*UpwardWalkLimit) {
564 *UpwardWalkLimit = 1;
565 LimitAlreadyReached = true;
566 }
George Burgess IV5f308972016-07-19 01:29:15 +0000567
568 for (MemoryAccess *Current : def_chain(Desc.Last)) {
569 Desc.Last = Current;
Alina Sbirleaf7230202019-01-07 18:40:27 +0000570 if (Current == StopAt || Current == SkipStopAt)
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000571 return {Current, false, MayAlias};
George Burgess IV5f308972016-07-19 01:29:15 +0000572
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000573 if (auto *MD = dyn_cast<MemoryDef>(Current)) {
574 if (MSSA.isLiveOnEntryDef(MD))
575 return {MD, true, MustAlias};
Alina Sbirleaf085cc52019-03-29 21:56:09 +0000576
577 if (!--*UpwardWalkLimit)
578 return {Current, true, MayAlias};
579
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000580 ClobberAlias CA =
581 instructionClobbersQuery(MD, Desc.Loc, Query->Inst, AA);
582 if (CA.IsClobber)
583 return {MD, true, CA.AR};
584 }
George Burgess IV5f308972016-07-19 01:29:15 +0000585 }
586
Alina Sbirlea57769382019-04-12 18:48:46 +0000587 if (LimitAlreadyReached)
588 *UpwardWalkLimit = 0;
589
George Burgess IV5f308972016-07-19 01:29:15 +0000590 assert(isa<MemoryPhi>(Desc.Last) &&
591 "Ended at a non-clobber that's not a phi?");
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000592 return {Desc.Last, false, MayAlias};
George Burgess IV5f308972016-07-19 01:29:15 +0000593 }
594
595 void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches,
596 ListIndex PriorNode) {
597 auto UpwardDefs = make_range(upward_defs_begin({Phi, Paths[PriorNode].Loc}),
598 upward_defs_end());
599 for (const MemoryAccessPair &P : UpwardDefs) {
600 PausedSearches.push_back(Paths.size());
601 Paths.emplace_back(P.second, P.first, PriorNode);
602 }
603 }
604
605 /// Represents a search that terminated after finding a clobber. This clobber
606 /// may or may not be present in the path of defs from LastNode..SearchStart,
607 /// since it may have been retrieved from cache.
608 struct TerminatedPath {
609 MemoryAccess *Clobber;
610 ListIndex LastNode;
611 };
612
613 /// Get an access that keeps us from optimizing to the given phi.
614 ///
615 /// PausedSearches is an array of indices into the Paths array. Its incoming
616 /// value is the indices of searches that stopped at the last phi optimization
617 /// target. It's left in an unspecified state.
618 ///
619 /// If this returns None, NewPaused is a vector of searches that terminated
620 /// at StopWhere. Otherwise, NewPaused is left in an unspecified state.
George Burgess IV14633b52016-08-03 01:22:19 +0000621 Optional<TerminatedPath>
Daniel Berlind0420312017-04-01 09:01:12 +0000622 getBlockingAccess(const MemoryAccess *StopWhere,
George Burgess IV5f308972016-07-19 01:29:15 +0000623 SmallVectorImpl<ListIndex> &PausedSearches,
624 SmallVectorImpl<ListIndex> &NewPaused,
625 SmallVectorImpl<TerminatedPath> &Terminated) {
626 assert(!PausedSearches.empty() && "No searches to continue?");
627
628 // BFS vs DFS really doesn't make a difference here, so just do a DFS with
629 // PausedSearches as our stack.
630 while (!PausedSearches.empty()) {
631 ListIndex PathIndex = PausedSearches.pop_back_val();
632 DefPath &Node = Paths[PathIndex];
633
634 // If we've already visited this path with this MemoryLocation, we don't
635 // need to do so again.
636 //
637 // NOTE: That we just drop these paths on the ground makes caching
638 // behavior sporadic. e.g. given a diamond:
639 // A
640 // B C
641 // D
642 //
643 // ...If we walk D, B, A, C, we'll only cache the result of phi
644 // optimization for A, B, and D; C will be skipped because it dies here.
645 // This arguably isn't the worst thing ever, since:
646 // - We generally query things in a top-down order, so if we got below D
647 // without needing cache entries for {C, MemLoc}, then chances are
648 // that those cache entries would end up ultimately unused.
649 // - We still cache things for A, so C only needs to walk up a bit.
650 // If this behavior becomes problematic, we can fix without a ton of extra
651 // work.
652 if (!VisitedPhis.insert({Node.Last, Node.Loc}).second)
653 continue;
654
Alina Sbirleaf7230202019-01-07 18:40:27 +0000655 const MemoryAccess *SkipStopWhere = nullptr;
656 if (Query->SkipSelfAccess && Node.Loc == Query->StartingLoc) {
657 assert(isa<MemoryDef>(Query->OriginalAccess));
658 SkipStopWhere = Query->OriginalAccess;
659 }
660
Alina Sbirleaf085cc52019-03-29 21:56:09 +0000661 UpwardsWalkResult Res = walkToPhiOrClobber(Node,
662 /*StopAt=*/StopWhere,
Alina Sbirleaf7230202019-01-07 18:40:27 +0000663 /*SkipStopAt=*/SkipStopWhere);
George Burgess IV5f308972016-07-19 01:29:15 +0000664 if (Res.IsKnownClobber) {
Alina Sbirleaf7230202019-01-07 18:40:27 +0000665 assert(Res.Result != StopWhere && Res.Result != SkipStopWhere);
Alina Sbirleaf085cc52019-03-29 21:56:09 +0000666
George Burgess IV5f308972016-07-19 01:29:15 +0000667 // If this wasn't a cache hit, we hit a clobber when walking. That's a
668 // failure.
George Burgess IV14633b52016-08-03 01:22:19 +0000669 TerminatedPath Term{Res.Result, PathIndex};
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000670 if (!MSSA.dominates(Res.Result, StopWhere))
George Burgess IV14633b52016-08-03 01:22:19 +0000671 return Term;
George Burgess IV5f308972016-07-19 01:29:15 +0000672
673 // Otherwise, it's a valid thing to potentially optimize to.
George Burgess IV14633b52016-08-03 01:22:19 +0000674 Terminated.push_back(Term);
George Burgess IV5f308972016-07-19 01:29:15 +0000675 continue;
676 }
677
Alina Sbirleaf7230202019-01-07 18:40:27 +0000678 if (Res.Result == StopWhere || Res.Result == SkipStopWhere) {
George Burgess IV5f308972016-07-19 01:29:15 +0000679 // We've hit our target. Save this path off for if we want to continue
Alina Sbirleaf7230202019-01-07 18:40:27 +0000680 // walking. If we are in the mode of skipping the OriginalAccess, and
681 // we've reached back to the OriginalAccess, do not save path, we've
682 // just looped back to self.
683 if (Res.Result != SkipStopWhere)
684 NewPaused.push_back(PathIndex);
George Burgess IV5f308972016-07-19 01:29:15 +0000685 continue;
686 }
687
688 assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");
689 addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
690 }
691
692 return None;
693 }
694
695 template <typename T, typename Walker>
696 struct generic_def_path_iterator
697 : public iterator_facade_base<generic_def_path_iterator<T, Walker>,
698 std::forward_iterator_tag, T *> {
Hans Wennborg5519cb22019-03-25 09:27:42 +0000699 generic_def_path_iterator() {}
George Burgess IV5f308972016-07-19 01:29:15 +0000700 generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}
701
702 T &operator*() const { return curNode(); }
703
704 generic_def_path_iterator &operator++() {
705 N = curNode().Previous;
706 return *this;
707 }
708
709 bool operator==(const generic_def_path_iterator &O) const {
710 if (N.hasValue() != O.N.hasValue())
711 return false;
712 return !N.hasValue() || *N == *O.N;
713 }
714
715 private:
716 T &curNode() const { return W->Paths[*N]; }
717
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000718 Walker *W = nullptr;
719 Optional<ListIndex> N = None;
George Burgess IV5f308972016-07-19 01:29:15 +0000720 };
721
722 using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
723 using const_def_path_iterator =
724 generic_def_path_iterator<const DefPath, const ClobberWalker>;
725
726 iterator_range<def_path_iterator> def_path(ListIndex From) {
727 return make_range(def_path_iterator(this, From), def_path_iterator());
728 }
729
730 iterator_range<const_def_path_iterator> const_def_path(ListIndex From) const {
731 return make_range(const_def_path_iterator(this, From),
732 const_def_path_iterator());
733 }
734
735 struct OptznResult {
736 /// The path that contains our result.
737 TerminatedPath PrimaryClobber;
738 /// The paths that we can legally cache back from, but that aren't
739 /// necessarily the result of the Phi optimization.
740 SmallVector<TerminatedPath, 4> OtherClobbers;
741 };
742
743 ListIndex defPathIndex(const DefPath &N) const {
744 // The assert looks nicer if we don't need to do &N
745 const DefPath *NP = &N;
746 assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
747 "Out of bounds DefPath!");
748 return NP - &Paths.front();
749 }
750
751 /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths
752 /// that act as legal clobbers. Note that this won't return *all* clobbers.
753 ///
754 /// Phi optimization algorithm tl;dr:
755 /// - Find the earliest def/phi, A, we can optimize to
756 /// - Find if all paths from the starting memory access ultimately reach A
757 /// - If not, optimization isn't possible.
758 /// - Otherwise, walk from A to another clobber or phi, A'.
759 /// - If A' is a def, we're done.
760 /// - If A' is a phi, try to optimize it.
761 ///
762 /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path
763 /// terminates when a MemoryAccess that clobbers said MemoryLocation is found.
764 OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start,
765 const MemoryLocation &Loc) {
766 assert(Paths.empty() && VisitedPhis.empty() &&
767 "Reset the optimization state.");
768
769 Paths.emplace_back(Loc, Start, Phi, None);
770 // Stores how many "valid" optimization nodes we had prior to calling
771 // addSearches/getBlockingAccess. Necessary for caching if we had a blocker.
772 auto PriorPathsSize = Paths.size();
773
774 SmallVector<ListIndex, 16> PausedSearches;
775 SmallVector<ListIndex, 8> NewPaused;
776 SmallVector<TerminatedPath, 4> TerminatedPaths;
777
778 addSearches(Phi, PausedSearches, 0);
779
780 // Moves the TerminatedPath with the "most dominated" Clobber to the end of
781 // Paths.
782 auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
783 assert(!Paths.empty() && "Need a path to move");
George Burgess IV5f308972016-07-19 01:29:15 +0000784 auto Dom = Paths.begin();
785 for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I)
786 if (!MSSA.dominates(I->Clobber, Dom->Clobber))
787 Dom = I;
788 auto Last = Paths.end() - 1;
789 if (Last != Dom)
790 std::iter_swap(Last, Dom);
791 };
792
793 MemoryPhi *Current = Phi;
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000794 while (true) {
George Burgess IV5f308972016-07-19 01:29:15 +0000795 assert(!MSSA.isLiveOnEntryDef(Current) &&
796 "liveOnEntry wasn't treated as a clobber?");
797
Daniel Berlind0420312017-04-01 09:01:12 +0000798 const auto *Target = getWalkTarget(Current);
George Burgess IV5f308972016-07-19 01:29:15 +0000799 // If a TerminatedPath doesn't dominate Target, then it wasn't a legal
800 // optimization for the prior phi.
801 assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {
802 return MSSA.dominates(P.Clobber, Target);
803 }));
804
805 // FIXME: This is broken, because the Blocker may be reported to be
806 // liveOnEntry, and we'll happily wait for that to disappear (read: never)
George Burgess IV7f414b92016-08-22 23:40:01 +0000807 // For the moment, this is fine, since we do nothing with blocker info.
George Burgess IV14633b52016-08-03 01:22:19 +0000808 if (Optional<TerminatedPath> Blocker = getBlockingAccess(
George Burgess IV5f308972016-07-19 01:29:15 +0000809 Target, PausedSearches, NewPaused, TerminatedPaths)) {
George Burgess IV5f308972016-07-19 01:29:15 +0000810
811 // Find the node we started at. We can't search based on N->Last, since
812 // we may have gone around a loop with a different MemoryLocation.
George Burgess IV14633b52016-08-03 01:22:19 +0000813 auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) {
George Burgess IV5f308972016-07-19 01:29:15 +0000814 return defPathIndex(N) < PriorPathsSize;
815 });
816 assert(Iter != def_path_iterator());
817
818 DefPath &CurNode = *Iter;
819 assert(CurNode.Last == Current);
George Burgess IV5f308972016-07-19 01:29:15 +0000820
821 // Two things:
822 // A. We can't reliably cache all of NewPaused back. Consider a case
823 // where we have two paths in NewPaused; one of which can't optimize
824 // above this phi, whereas the other can. If we cache the second path
825 // back, we'll end up with suboptimal cache entries. We can handle
826 // cases like this a bit better when we either try to find all
827 // clobbers that block phi optimization, or when our cache starts
828 // supporting unfinished searches.
829 // B. We can't reliably cache TerminatedPaths back here without doing
830 // extra checks; consider a case like:
831 // T
832 // / \
833 // D C
834 // \ /
835 // S
836 // Where T is our target, C is a node with a clobber on it, D is a
837 // diamond (with a clobber *only* on the left or right node, N), and
838 // S is our start. Say we walk to D, through the node opposite N
839 // (read: ignoring the clobber), and see a cache entry in the top
840 // node of D. That cache entry gets put into TerminatedPaths. We then
841 // walk up to C (N is later in our worklist), find the clobber, and
842 // quit. If we append TerminatedPaths to OtherClobbers, we'll cache
843 // the bottom part of D to the cached clobber, ignoring the clobber
844 // in N. Again, this problem goes away if we start tracking all
845 // blockers for a given phi optimization.
846 TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
847 return {Result, {}};
848 }
849
850 // If there's nothing left to search, then all paths led to valid clobbers
851 // that we got from our cache; pick the nearest to the start, and allow
852 // the rest to be cached back.
853 if (NewPaused.empty()) {
854 MoveDominatedPathToEnd(TerminatedPaths);
855 TerminatedPath Result = TerminatedPaths.pop_back_val();
856 return {Result, std::move(TerminatedPaths)};
857 }
858
859 MemoryAccess *DefChainEnd = nullptr;
860 SmallVector<TerminatedPath, 4> Clobbers;
861 for (ListIndex Paused : NewPaused) {
862 UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
863 if (WR.IsKnownClobber)
864 Clobbers.push_back({WR.Result, Paused});
865 else
866 // Micro-opt: If we hit the end of the chain, save it.
867 DefChainEnd = WR.Result;
868 }
869
870 if (!TerminatedPaths.empty()) {
871 // If we couldn't find the dominating phi/liveOnEntry in the above loop,
872 // do it now.
873 if (!DefChainEnd)
Daniel Berlind0420312017-04-01 09:01:12 +0000874 for (auto *MA : def_chain(const_cast<MemoryAccess *>(Target)))
George Burgess IV5f308972016-07-19 01:29:15 +0000875 DefChainEnd = MA;
Simon Pilgrim65e11502019-10-02 13:09:04 +0000876 assert(DefChainEnd && "Failed to find dominating phi/liveOnEntry");
George Burgess IV5f308972016-07-19 01:29:15 +0000877
878 // If any of the terminated paths don't dominate the phi we'll try to
879 // optimize, we need to figure out what they are and quit.
880 const BasicBlock *ChainBB = DefChainEnd->getBlock();
881 for (const TerminatedPath &TP : TerminatedPaths) {
882 // Because we know that DefChainEnd is as "high" as we can go, we
883 // don't need local dominance checks; BB dominance is sufficient.
884 if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
885 Clobbers.push_back(TP);
886 }
887 }
888
889 // If we have clobbers in the def chain, find the one closest to Current
890 // and quit.
891 if (!Clobbers.empty()) {
892 MoveDominatedPathToEnd(Clobbers);
893 TerminatedPath Result = Clobbers.pop_back_val();
894 return {Result, std::move(Clobbers)};
895 }
896
897 assert(all_of(NewPaused,
898 [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
899
900 // Because liveOnEntry is a clobber, this must be a phi.
901 auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
902
903 PriorPathsSize = Paths.size();
904 PausedSearches.clear();
905 for (ListIndex I : NewPaused)
906 addSearches(DefChainPhi, PausedSearches, I);
907 NewPaused.clear();
908
909 Current = DefChainPhi;
910 }
911 }
912
George Burgess IV5f308972016-07-19 01:29:15 +0000913 void verifyOptResult(const OptznResult &R) const {
914 assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
915 return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
916 }));
917 }
918
919 void resetPhiOptznState() {
920 Paths.clear();
921 VisitedPhis.clear();
922 }
923
924public:
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000925 ClobberWalker(const MemorySSA &MSSA, AliasAnalysisType &AA, DominatorTree &DT)
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000926 : MSSA(MSSA), AA(AA), DT(DT) {}
George Burgess IV5f308972016-07-19 01:29:15 +0000927
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000928 AliasAnalysisType *getAA() { return &AA; }
George Burgess IV5f308972016-07-19 01:29:15 +0000929 /// Finds the nearest clobber for the given query, optimizing phis if
930 /// possible.
Alina Sbirleaf085cc52019-03-29 21:56:09 +0000931 MemoryAccess *findClobber(MemoryAccess *Start, UpwardsMemoryQuery &Q,
932 unsigned &UpWalkLimit) {
George Burgess IV5f308972016-07-19 01:29:15 +0000933 Query = &Q;
Alina Sbirleaf085cc52019-03-29 21:56:09 +0000934 UpwardWalkLimit = &UpWalkLimit;
935 // Starting limit must be > 0.
936 if (!UpWalkLimit)
937 UpWalkLimit++;
George Burgess IV5f308972016-07-19 01:29:15 +0000938
939 MemoryAccess *Current = Start;
940 // This walker pretends uses don't exist. If we're handed one, silently grab
941 // its def. (This has the nice side-effect of ensuring we never cache uses)
942 if (auto *MU = dyn_cast<MemoryUse>(Start))
943 Current = MU->getDefiningAccess();
944
945 DefPath FirstDesc(Q.StartingLoc, Current, Current, None);
946 // Fast path for the overly-common case (no crazy phi optimization
947 // necessary)
948 UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
George Burgess IV93ea19b2016-07-24 07:03:49 +0000949 MemoryAccess *Result;
George Burgess IV5f308972016-07-19 01:29:15 +0000950 if (WalkResult.IsKnownClobber) {
George Burgess IV93ea19b2016-07-24 07:03:49 +0000951 Result = WalkResult.Result;
Alina Sbirlead90c9f42018-03-08 18:03:14 +0000952 Q.AR = WalkResult.AR;
George Burgess IV93ea19b2016-07-24 07:03:49 +0000953 } else {
954 OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
955 Current, Q.StartingLoc);
956 verifyOptResult(OptRes);
George Burgess IV93ea19b2016-07-24 07:03:49 +0000957 resetPhiOptznState();
958 Result = OptRes.PrimaryClobber.Clobber;
George Burgess IV5f308972016-07-19 01:29:15 +0000959 }
960
George Burgess IV5f308972016-07-19 01:29:15 +0000961#ifdef EXPENSIVE_CHECKS
Alina Sbirleaf085cc52019-03-29 21:56:09 +0000962 if (!Q.SkipSelfAccess && *UpwardWalkLimit > 0)
Alina Sbirleae41f4b32019-01-10 21:47:15 +0000963 checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, AA);
George Burgess IV5f308972016-07-19 01:29:15 +0000964#endif
George Burgess IV93ea19b2016-07-24 07:03:49 +0000965 return Result;
George Burgess IV5f308972016-07-19 01:29:15 +0000966 }
967};
968
969struct RenamePassData {
970 DomTreeNode *DTN;
971 DomTreeNode::const_iterator ChildIt;
972 MemoryAccess *IncomingVal;
973
974 RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
975 MemoryAccess *M)
976 : DTN(D), ChildIt(It), IncomingVal(M) {}
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000977
George Burgess IV5f308972016-07-19 01:29:15 +0000978 void swap(RenamePassData &RHS) {
979 std::swap(DTN, RHS.DTN);
980 std::swap(ChildIt, RHS.ChildIt);
981 std::swap(IncomingVal, RHS.IncomingVal);
982 }
983};
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000984
985} // end anonymous namespace
George Burgess IV5f308972016-07-19 01:29:15 +0000986
987namespace llvm {
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000988
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000989template <class AliasAnalysisType> class MemorySSA::ClobberWalkerBase {
990 ClobberWalker<AliasAnalysisType> Walker;
Alina Sbirleabc8aa242019-01-07 19:22:37 +0000991 MemorySSA *MSSA;
992
993public:
Alina Sbirleabfc779e2019-03-22 17:22:19 +0000994 ClobberWalkerBase(MemorySSA *M, AliasAnalysisType *A, DominatorTree *D)
Alina Sbirleabc8aa242019-01-07 19:22:37 +0000995 : Walker(*M, *A, *D), MSSA(M) {}
996
997 MemoryAccess *getClobberingMemoryAccessBase(MemoryAccess *,
Alina Sbirleaf085cc52019-03-29 21:56:09 +0000998 const MemoryLocation &,
999 unsigned &);
1000 // Third argument (bool), defines whether the clobber search should skip the
Alina Sbirleabc8aa242019-01-07 19:22:37 +00001001 // original queried access. If true, there will be a follow-up query searching
1002 // for a clobber access past "self". Note that the Optimized access is not
1003 // updated if a new clobber is found by this SkipSelf search. If this
1004 // additional query becomes heavily used we may decide to cache the result.
1005 // Walker instantiations will decide how to set the SkipSelf bool.
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001006 MemoryAccess *getClobberingMemoryAccessBase(MemoryAccess *, unsigned &, bool);
Alina Sbirleabc8aa242019-01-07 19:22:37 +00001007};
1008
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001009/// A MemorySSAWalker that does AA walks to disambiguate accesses. It no
George Burgess IV45f263d2018-05-26 02:28:55 +00001010/// longer does caching on its own, but the name has been retained for the
1011/// moment.
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001012template <class AliasAnalysisType>
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001013class MemorySSA::CachingWalker final : public MemorySSAWalker {
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001014 ClobberWalkerBase<AliasAnalysisType> *Walker;
George Burgess IV5f308972016-07-19 01:29:15 +00001015
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001016public:
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001017 CachingWalker(MemorySSA *M, ClobberWalkerBase<AliasAnalysisType> *W)
Alina Sbirleabc8aa242019-01-07 19:22:37 +00001018 : MemorySSAWalker(M), Walker(W) {}
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001019 ~CachingWalker() override = default;
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001020
George Burgess IV400ae402016-07-20 19:51:34 +00001021 using MemorySSAWalker::getClobberingMemoryAccess;
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001022
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001023 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA, unsigned &UWL) {
1024 return Walker->getClobberingMemoryAccessBase(MA, UWL, false);
1025 }
1026 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
1027 const MemoryLocation &Loc,
1028 unsigned &UWL) {
1029 return Walker->getClobberingMemoryAccessBase(MA, Loc, UWL);
1030 }
1031
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001032 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA) override {
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001033 unsigned UpwardWalkLimit = MaxCheckLimit;
1034 return getClobberingMemoryAccess(MA, UpwardWalkLimit);
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001035 }
Alina Sbirleabc8aa242019-01-07 19:22:37 +00001036 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001037 const MemoryLocation &Loc) override {
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001038 unsigned UpwardWalkLimit = MaxCheckLimit;
1039 return getClobberingMemoryAccess(MA, Loc, UpwardWalkLimit);
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001040 }
Alina Sbirleabc8aa242019-01-07 19:22:37 +00001041
1042 void invalidateInfo(MemoryAccess *MA) override {
1043 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1044 MUD->resetOptimized();
1045 }
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001046};
George Burgess IVe1100f52016-02-02 22:46:49 +00001047
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001048template <class AliasAnalysisType>
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001049class MemorySSA::SkipSelfWalker final : public MemorySSAWalker {
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001050 ClobberWalkerBase<AliasAnalysisType> *Walker;
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001051
1052public:
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001053 SkipSelfWalker(MemorySSA *M, ClobberWalkerBase<AliasAnalysisType> *W)
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001054 : MemorySSAWalker(M), Walker(W) {}
1055 ~SkipSelfWalker() override = default;
1056
1057 using MemorySSAWalker::getClobberingMemoryAccess;
1058
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001059 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA, unsigned &UWL) {
1060 return Walker->getClobberingMemoryAccessBase(MA, UWL, true);
1061 }
1062 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
1063 const MemoryLocation &Loc,
1064 unsigned &UWL) {
1065 return Walker->getClobberingMemoryAccessBase(MA, Loc, UWL);
1066 }
1067
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001068 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA) override {
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001069 unsigned UpwardWalkLimit = MaxCheckLimit;
1070 return getClobberingMemoryAccess(MA, UpwardWalkLimit);
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001071 }
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001072 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *MA,
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001073 const MemoryLocation &Loc) override {
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001074 unsigned UpwardWalkLimit = MaxCheckLimit;
1075 return getClobberingMemoryAccess(MA, Loc, UpwardWalkLimit);
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001076 }
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001077
1078 void invalidateInfo(MemoryAccess *MA) override {
1079 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1080 MUD->resetOptimized();
1081 }
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001082};
1083
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001084} // end namespace llvm
1085
Daniel Berlin78cbd282017-02-20 22:26:03 +00001086void MemorySSA::renameSuccessorPhis(BasicBlock *BB, MemoryAccess *IncomingVal,
1087 bool RenameAllUses) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001088 // Pass through values to our successors
1089 for (const BasicBlock *S : successors(BB)) {
1090 auto It = PerBlockAccesses.find(S);
1091 // Rename the phi nodes in our successor block
1092 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1093 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +00001094 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001095 auto *Phi = cast<MemoryPhi>(&Accesses->front());
Daniel Berlin78cbd282017-02-20 22:26:03 +00001096 if (RenameAllUses) {
Alina Sbirlea3d037692019-08-30 23:02:53 +00001097 bool ReplacementDone = false;
1098 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
1099 if (Phi->getIncomingBlock(I) == BB) {
1100 Phi->setIncomingValue(I, IncomingVal);
1101 ReplacementDone = true;
1102 }
1103 (void) ReplacementDone;
1104 assert(ReplacementDone && "Incomplete phi during partial rename");
Daniel Berlin78cbd282017-02-20 22:26:03 +00001105 } else
1106 Phi->addIncoming(IncomingVal, BB);
George Burgess IVe1100f52016-02-02 22:46:49 +00001107 }
Daniel Berlin78cbd282017-02-20 22:26:03 +00001108}
George Burgess IVe1100f52016-02-02 22:46:49 +00001109
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001110/// Rename a single basic block into MemorySSA form.
Daniel Berlin78cbd282017-02-20 22:26:03 +00001111/// Uses the standard SSA renaming algorithm.
1112/// \returns The new incoming value.
1113MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB, MemoryAccess *IncomingVal,
1114 bool RenameAllUses) {
1115 auto It = PerBlockAccesses.find(BB);
1116 // Skip most processing if the list is empty.
1117 if (It != PerBlockAccesses.end()) {
1118 AccessList *Accesses = It->second.get();
1119 for (MemoryAccess &L : *Accesses) {
1120 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&L)) {
1121 if (MUD->getDefiningAccess() == nullptr || RenameAllUses)
1122 MUD->setDefiningAccess(IncomingVal);
1123 if (isa<MemoryDef>(&L))
1124 IncomingVal = &L;
1125 } else {
1126 IncomingVal = &L;
1127 }
1128 }
1129 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001130 return IncomingVal;
1131}
1132
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001133/// This is the standard SSA renaming algorithm.
George Burgess IVe1100f52016-02-02 22:46:49 +00001134///
1135/// We walk the dominator tree in preorder, renaming accesses, and then filling
1136/// in phi nodes in our successors.
1137void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
Daniel Berlin78cbd282017-02-20 22:26:03 +00001138 SmallPtrSetImpl<BasicBlock *> &Visited,
1139 bool SkipVisited, bool RenameAllUses) {
Alina Sbirlea0363c3b2019-05-02 23:41:58 +00001140 assert(Root && "Trying to rename accesses in an unreachable block");
1141
George Burgess IVe1100f52016-02-02 22:46:49 +00001142 SmallVector<RenamePassData, 32> WorkStack;
Daniel Berlin78cbd282017-02-20 22:26:03 +00001143 // Skip everything if we already renamed this block and we are skipping.
1144 // Note: You can't sink this into the if, because we need it to occur
1145 // regardless of whether we skip blocks or not.
1146 bool AlreadyVisited = !Visited.insert(Root->getBlock()).second;
1147 if (SkipVisited && AlreadyVisited)
1148 return;
1149
1150 IncomingVal = renameBlock(Root->getBlock(), IncomingVal, RenameAllUses);
1151 renameSuccessorPhis(Root->getBlock(), IncomingVal, RenameAllUses);
George Burgess IVe1100f52016-02-02 22:46:49 +00001152 WorkStack.push_back({Root, Root->begin(), IncomingVal});
George Burgess IVe1100f52016-02-02 22:46:49 +00001153
1154 while (!WorkStack.empty()) {
1155 DomTreeNode *Node = WorkStack.back().DTN;
1156 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
1157 IncomingVal = WorkStack.back().IncomingVal;
1158
1159 if (ChildIt == Node->end()) {
1160 WorkStack.pop_back();
1161 } else {
1162 DomTreeNode *Child = *ChildIt;
1163 ++WorkStack.back().ChildIt;
1164 BasicBlock *BB = Child->getBlock();
Daniel Berlin78cbd282017-02-20 22:26:03 +00001165 // Note: You can't sink this into the if, because we need it to occur
1166 // regardless of whether we skip blocks or not.
1167 AlreadyVisited = !Visited.insert(BB).second;
1168 if (SkipVisited && AlreadyVisited) {
1169 // We already visited this during our renaming, which can happen when
1170 // being asked to rename multiple blocks. Figure out the incoming val,
1171 // which is the last def.
1172 // Incoming value can only change if there is a block def, and in that
1173 // case, it's the last block def in the list.
1174 if (auto *BlockDefs = getWritableBlockDefs(BB))
1175 IncomingVal = &*BlockDefs->rbegin();
1176 } else
1177 IncomingVal = renameBlock(BB, IncomingVal, RenameAllUses);
1178 renameSuccessorPhis(BB, IncomingVal, RenameAllUses);
George Burgess IVe1100f52016-02-02 22:46:49 +00001179 WorkStack.push_back({Child, Child->begin(), IncomingVal});
1180 }
1181 }
1182}
1183
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001184/// This handles unreachable block accesses by deleting phi nodes in
George Burgess IVe1100f52016-02-02 22:46:49 +00001185/// unreachable blocks, and marking all other unreachable MemoryAccess's as
1186/// being uses of the live on entry definition.
1187void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
1188 assert(!DT->isReachableFromEntry(BB) &&
1189 "Reachable block found while handling unreachable blocks");
1190
Daniel Berlinfc7e6512016-07-06 05:32:05 +00001191 // Make sure phi nodes in our reachable successors end up with a
1192 // LiveOnEntryDef for our incoming edge, even though our block is forward
1193 // unreachable. We could just disconnect these blocks from the CFG fully,
1194 // but we do not right now.
1195 for (const BasicBlock *S : successors(BB)) {
1196 if (!DT->isReachableFromEntry(S))
1197 continue;
1198 auto It = PerBlockAccesses.find(S);
1199 // Rename the phi nodes in our successor block
1200 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1201 continue;
1202 AccessList *Accesses = It->second.get();
1203 auto *Phi = cast<MemoryPhi>(&Accesses->front());
1204 Phi->addIncoming(LiveOnEntryDef.get(), BB);
1205 }
1206
George Burgess IVe1100f52016-02-02 22:46:49 +00001207 auto It = PerBlockAccesses.find(BB);
1208 if (It == PerBlockAccesses.end())
1209 return;
1210
1211 auto &Accesses = It->second;
1212 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1213 auto Next = std::next(AI);
1214 // If we have a phi, just remove it. We are going to replace all
1215 // users with live on entry.
1216 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1217 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1218 else
1219 Accesses->erase(AI);
1220 AI = Next;
1221 }
1222}
1223
Geoff Berryb96d3b22016-06-01 21:30:40 +00001224MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001225 : AA(nullptr), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001226 SkipWalker(nullptr), NextID(0) {
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001227 // Build MemorySSA using a batch alias analysis. This reuses the internal
1228 // state that AA collects during an alias()/getModRefInfo() call. This is
1229 // safe because there are no CFG changes while building MemorySSA and can
1230 // significantly reduce the time spent by the compiler in AA, because we will
1231 // make queries about all the instructions in the Function.
Dávid Bolvanský717965a2019-11-03 20:27:40 +01001232 assert(AA && "No alias analysis?");
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001233 BatchAAResults BatchAA(*AA);
1234 buildMemorySSA(BatchAA);
1235 // Intentionally leave AA to nullptr while building so we don't accidently
1236 // use non-batch AliasAnalysis.
1237 this->AA = AA;
1238 // Also create the walker here.
1239 getWalker();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001240}
1241
George Burgess IVe1100f52016-02-02 22:46:49 +00001242MemorySSA::~MemorySSA() {
1243 // Drop all our references
1244 for (const auto &Pair : PerBlockAccesses)
1245 for (MemoryAccess &MA : *Pair.second)
1246 MA.dropAllReferences();
1247}
1248
Daniel Berlin14300262016-06-21 18:39:20 +00001249MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001250 auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
1251
1252 if (Res.second)
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001253 Res.first->second = std::make_unique<AccessList>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001254 return Res.first->second.get();
1255}
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001256
Daniel Berlind602e042017-01-25 20:56:19 +00001257MemorySSA::DefsList *MemorySSA::getOrCreateDefsList(const BasicBlock *BB) {
1258 auto Res = PerBlockDefs.insert(std::make_pair(BB, nullptr));
1259
1260 if (Res.second)
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001261 Res.first->second = std::make_unique<DefsList>();
Daniel Berlind602e042017-01-25 20:56:19 +00001262 return Res.first->second.get();
1263}
George Burgess IVe1100f52016-02-02 22:46:49 +00001264
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001265namespace llvm {
1266
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001267/// This class is a batch walker of all MemoryUse's in the program, and points
1268/// their defining access at the thing that actually clobbers them. Because it
1269/// is a batch walker that touches everything, it does not operate like the
1270/// other walkers. This walker is basically performing a top-down SSA renaming
1271/// pass, where the version stack is used as the cache. This enables it to be
1272/// significantly more time and memory efficient than using the regular walker,
1273/// which is walking bottom-up.
1274class MemorySSA::OptimizeUses {
1275public:
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001276 OptimizeUses(MemorySSA *MSSA, CachingWalker<BatchAAResults> *Walker,
1277 BatchAAResults *BAA, DominatorTree *DT)
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001278 : MSSA(MSSA), Walker(Walker), AA(BAA), DT(DT) {}
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001279
1280 void optimizeUses();
1281
1282private:
1283 /// This represents where a given memorylocation is in the stack.
1284 struct MemlocStackInfo {
1285 // This essentially is keeping track of versions of the stack. Whenever
1286 // the stack changes due to pushes or pops, these versions increase.
1287 unsigned long StackEpoch;
1288 unsigned long PopEpoch;
1289 // This is the lower bound of places on the stack to check. It is equal to
1290 // the place the last stack walk ended.
1291 // Note: Correctness depends on this being initialized to 0, which densemap
1292 // does
1293 unsigned long LowerBound;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001294 const BasicBlock *LowerBoundBlock;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001295 // This is where the last walk for this memory location ended.
1296 unsigned long LastKill;
1297 bool LastKillValid;
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001298 Optional<AliasResult> AR;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001299 };
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001300
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001301 void optimizeUsesInBlock(const BasicBlock *, unsigned long &, unsigned long &,
1302 SmallVectorImpl<MemoryAccess *> &,
1303 DenseMap<MemoryLocOrCall, MemlocStackInfo> &);
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001304
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001305 MemorySSA *MSSA;
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001306 CachingWalker<BatchAAResults> *Walker;
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001307 BatchAAResults *AA;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001308 DominatorTree *DT;
1309};
1310
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001311} // end namespace llvm
1312
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001313/// Optimize the uses in a given block This is basically the SSA renaming
1314/// algorithm, with one caveat: We are able to use a single stack for all
1315/// MemoryUses. This is because the set of *possible* reaching MemoryDefs is
1316/// the same for every MemoryUse. The *actual* clobbering MemoryDef is just
1317/// going to be some position in that stack of possible ones.
1318///
1319/// We track the stack positions that each MemoryLocation needs
1320/// to check, and last ended at. This is because we only want to check the
1321/// things that changed since last time. The same MemoryLocation should
1322/// get clobbered by the same store (getModRefInfo does not use invariantness or
1323/// things like this, and if they start, we can modify MemoryLocOrCall to
1324/// include relevant data)
1325void MemorySSA::OptimizeUses::optimizeUsesInBlock(
1326 const BasicBlock *BB, unsigned long &StackEpoch, unsigned long &PopEpoch,
1327 SmallVectorImpl<MemoryAccess *> &VersionStack,
1328 DenseMap<MemoryLocOrCall, MemlocStackInfo> &LocStackInfo) {
1329
1330 /// If no accesses, nothing to do.
1331 MemorySSA::AccessList *Accesses = MSSA->getWritableBlockAccesses(BB);
1332 if (Accesses == nullptr)
1333 return;
1334
1335 // Pop everything that doesn't dominate the current block off the stack,
1336 // increment the PopEpoch to account for this.
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001337 while (true) {
1338 assert(
1339 !VersionStack.empty() &&
1340 "Version stack should have liveOnEntry sentinel dominating everything");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001341 BasicBlock *BackBlock = VersionStack.back()->getBlock();
1342 if (DT->dominates(BackBlock, BB))
1343 break;
1344 while (VersionStack.back()->getBlock() == BackBlock)
1345 VersionStack.pop_back();
1346 ++PopEpoch;
1347 }
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001348
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001349 for (MemoryAccess &MA : *Accesses) {
1350 auto *MU = dyn_cast<MemoryUse>(&MA);
1351 if (!MU) {
1352 VersionStack.push_back(&MA);
1353 ++StackEpoch;
1354 continue;
1355 }
1356
George Burgess IV024f3d22016-08-03 19:57:02 +00001357 if (isUseTriviallyOptimizableToLiveOnEntry(*AA, MU->getMemoryInst())) {
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001358 MU->setDefiningAccess(MSSA->getLiveOnEntryDef(), true, None);
George Burgess IV024f3d22016-08-03 19:57:02 +00001359 continue;
1360 }
1361
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001362 MemoryLocOrCall UseMLOC(MU);
1363 auto &LocInfo = LocStackInfo[UseMLOC];
Daniel Berlin26fcea92016-08-02 20:02:21 +00001364 // If the pop epoch changed, it means we've removed stuff from top of
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001365 // stack due to changing blocks. We may have to reset the lower bound or
1366 // last kill info.
1367 if (LocInfo.PopEpoch != PopEpoch) {
1368 LocInfo.PopEpoch = PopEpoch;
1369 LocInfo.StackEpoch = StackEpoch;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001370 // If the lower bound was in something that no longer dominates us, we
1371 // have to reset it.
1372 // We can't simply track stack size, because the stack may have had
1373 // pushes/pops in the meantime.
1374 // XXX: This is non-optimal, but only is slower cases with heavily
1375 // branching dominator trees. To get the optimal number of queries would
1376 // be to make lowerbound and lastkill a per-loc stack, and pop it until
1377 // the top of that stack dominates us. This does not seem worth it ATM.
1378 // A much cheaper optimization would be to always explore the deepest
1379 // branch of the dominator tree first. This will guarantee this resets on
1380 // the smallest set of blocks.
1381 if (LocInfo.LowerBoundBlock && LocInfo.LowerBoundBlock != BB &&
Daniel Berlin1e98c042016-09-26 17:22:54 +00001382 !DT->dominates(LocInfo.LowerBoundBlock, BB)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001383 // Reset the lower bound of things to check.
1384 // TODO: Some day we should be able to reset to last kill, rather than
1385 // 0.
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001386 LocInfo.LowerBound = 0;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001387 LocInfo.LowerBoundBlock = VersionStack[0]->getBlock();
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001388 LocInfo.LastKillValid = false;
1389 }
1390 } else if (LocInfo.StackEpoch != StackEpoch) {
1391 // If all that has changed is the StackEpoch, we only have to check the
1392 // new things on the stack, because we've checked everything before. In
1393 // this case, the lower bound of things to check remains the same.
1394 LocInfo.PopEpoch = PopEpoch;
1395 LocInfo.StackEpoch = StackEpoch;
1396 }
1397 if (!LocInfo.LastKillValid) {
1398 LocInfo.LastKill = VersionStack.size() - 1;
1399 LocInfo.LastKillValid = true;
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001400 LocInfo.AR = MayAlias;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001401 }
1402
1403 // At this point, we should have corrected last kill and LowerBound to be
1404 // in bounds.
1405 assert(LocInfo.LowerBound < VersionStack.size() &&
1406 "Lower bound out of range");
1407 assert(LocInfo.LastKill < VersionStack.size() &&
1408 "Last kill info out of range");
1409 // In any case, the new upper bound is the top of the stack.
1410 unsigned long UpperBound = VersionStack.size() - 1;
1411
1412 if (UpperBound - LocInfo.LowerBound > MaxCheckLimit) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001413 LLVM_DEBUG(dbgs() << "MemorySSA skipping optimization of " << *MU << " ("
1414 << *(MU->getMemoryInst()) << ")"
1415 << " because there are "
1416 << UpperBound - LocInfo.LowerBound
1417 << " stores to disambiguate\n");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001418 // Because we did not walk, LastKill is no longer valid, as this may
1419 // have been a kill.
1420 LocInfo.LastKillValid = false;
1421 continue;
1422 }
1423 bool FoundClobberResult = false;
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001424 unsigned UpwardWalkLimit = MaxCheckLimit;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001425 while (UpperBound > LocInfo.LowerBound) {
1426 if (isa<MemoryPhi>(VersionStack[UpperBound])) {
1427 // For phis, use the walker, see where we ended up, go there
Alina Sbirleaf085cc52019-03-29 21:56:09 +00001428 MemoryAccess *Result =
1429 Walker->getClobberingMemoryAccess(MU, UpwardWalkLimit);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001430 // We are guaranteed to find it or something is wrong
1431 while (VersionStack[UpperBound] != Result) {
1432 assert(UpperBound != 0);
1433 --UpperBound;
1434 }
1435 FoundClobberResult = true;
1436 break;
1437 }
1438
1439 MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]);
Daniel Berlindf101192016-08-03 00:01:46 +00001440 // If the lifetime of the pointer ends at this instruction, it's live on
1441 // entry.
1442 if (!UseMLOC.IsCall && lifetimeEndsAt(MD, UseMLOC.getLoc(), *AA)) {
1443 // Reset UpperBound to liveOnEntryDef's place in the stack
1444 UpperBound = 0;
1445 FoundClobberResult = true;
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001446 LocInfo.AR = MustAlias;
Daniel Berlindf101192016-08-03 00:01:46 +00001447 break;
1448 }
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001449 ClobberAlias CA = instructionClobbersQuery(MD, MU, UseMLOC, *AA);
1450 if (CA.IsClobber) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001451 FoundClobberResult = true;
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001452 LocInfo.AR = CA.AR;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001453 break;
1454 }
1455 --UpperBound;
1456 }
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001457
1458 // Note: Phis always have AliasResult AR set to MayAlias ATM.
1459
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001460 // At the end of this loop, UpperBound is either a clobber, or lower bound
1461 // PHI walking may cause it to be < LowerBound, and in fact, < LastKill.
1462 if (FoundClobberResult || UpperBound < LocInfo.LastKill) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001463 // We were last killed now by where we got to
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001464 if (MSSA->isLiveOnEntryDef(VersionStack[UpperBound]))
1465 LocInfo.AR = None;
1466 MU->setDefiningAccess(VersionStack[UpperBound], true, LocInfo.AR);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001467 LocInfo.LastKill = UpperBound;
1468 } else {
1469 // Otherwise, we checked all the new ones, and now we know we can get to
1470 // LastKill.
Alina Sbirlead90c9f42018-03-08 18:03:14 +00001471 MU->setDefiningAccess(VersionStack[LocInfo.LastKill], true, LocInfo.AR);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001472 }
1473 LocInfo.LowerBound = VersionStack.size() - 1;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001474 LocInfo.LowerBoundBlock = BB;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001475 }
1476}
1477
1478/// Optimize uses to point to their actual clobbering definitions.
1479void MemorySSA::OptimizeUses::optimizeUses() {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001480 SmallVector<MemoryAccess *, 16> VersionStack;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001481 DenseMap<MemoryLocOrCall, MemlocStackInfo> LocStackInfo;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001482 VersionStack.push_back(MSSA->getLiveOnEntryDef());
1483
1484 unsigned long StackEpoch = 1;
1485 unsigned long PopEpoch = 1;
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001486 // We perform a non-recursive top-down dominator tree walk.
Daniel Berlin7ac3d742016-08-05 22:09:14 +00001487 for (const auto *DomNode : depth_first(DT->getRootNode()))
1488 optimizeUsesInBlock(DomNode->getBlock(), StackEpoch, PopEpoch, VersionStack,
1489 LocStackInfo);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001490}
1491
Daniel Berlin3d512a22016-08-22 19:14:30 +00001492void MemorySSA::placePHINodes(
Michael Zolotukhin67cfbaa2018-05-15 18:40:29 +00001493 const SmallPtrSetImpl<BasicBlock *> &DefiningBlocks) {
Daniel Berlin3d512a22016-08-22 19:14:30 +00001494 // Determine where our MemoryPhi's should go
1495 ForwardIDFCalculator IDFs(*DT);
1496 IDFs.setDefiningBlocks(DefiningBlocks);
Daniel Berlin3d512a22016-08-22 19:14:30 +00001497 SmallVector<BasicBlock *, 32> IDFBlocks;
1498 IDFs.calculate(IDFBlocks);
1499
1500 // Now place MemoryPhi nodes.
Daniel Berlind602e042017-01-25 20:56:19 +00001501 for (auto &BB : IDFBlocks)
1502 createMemoryPhi(BB);
Daniel Berlin3d512a22016-08-22 19:14:30 +00001503}
1504
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001505void MemorySSA::buildMemorySSA(BatchAAResults &BAA) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001506 // We create an access to represent "live on entry", for things like
1507 // arguments or users of globals, where the memory they use is defined before
1508 // the beginning of the function. We do not actually insert it into the IR.
1509 // We do not define a live on exit for the immediate uses, and thus our
1510 // semantics do *not* imply that something with no immediate uses can simply
1511 // be removed.
1512 BasicBlock &StartingPoint = F.getEntryBlock();
George Burgess IV612cf212018-02-27 06:43:19 +00001513 LiveOnEntryDef.reset(new MemoryDef(F.getContext(), nullptr, nullptr,
1514 &StartingPoint, NextID++));
George Burgess IVe1100f52016-02-02 22:46:49 +00001515
1516 // We maintain lists of memory accesses per-block, trading memory for time. We
1517 // could just look up the memory access for every possible instruction in the
1518 // stream.
1519 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
George Burgess IVe1100f52016-02-02 22:46:49 +00001520 // Go through each block, figure out where defs occur, and chain together all
1521 // the accesses.
1522 for (BasicBlock &B : F) {
Daniel Berlin7898ca62016-02-07 01:52:15 +00001523 bool InsertIntoDef = false;
Daniel Berlinada263d2016-06-20 20:21:33 +00001524 AccessList *Accesses = nullptr;
Daniel Berlind602e042017-01-25 20:56:19 +00001525 DefsList *Defs = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +00001526 for (Instruction &I : B) {
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001527 MemoryUseOrDef *MUD = createNewAccess(&I, &BAA);
George Burgess IVb42b7622016-03-11 19:34:03 +00001528 if (!MUD)
George Burgess IVe1100f52016-02-02 22:46:49 +00001529 continue;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001530
George Burgess IVe1100f52016-02-02 22:46:49 +00001531 if (!Accesses)
1532 Accesses = getOrCreateAccessList(&B);
George Burgess IVb42b7622016-03-11 19:34:03 +00001533 Accesses->push_back(MUD);
Daniel Berlind602e042017-01-25 20:56:19 +00001534 if (isa<MemoryDef>(MUD)) {
1535 InsertIntoDef = true;
1536 if (!Defs)
1537 Defs = getOrCreateDefsList(&B);
1538 Defs->push_back(*MUD);
1539 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001540 }
Daniel Berlin7898ca62016-02-07 01:52:15 +00001541 if (InsertIntoDef)
1542 DefiningBlocks.insert(&B);
Daniel Berlin1b51a292016-02-07 01:52:19 +00001543 }
Michael Zolotukhin67cfbaa2018-05-15 18:40:29 +00001544 placePHINodes(DefiningBlocks);
George Burgess IVe1100f52016-02-02 22:46:49 +00001545
1546 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
1547 // filled in with all blocks.
1548 SmallPtrSet<BasicBlock *, 16> Visited;
1549 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1550
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001551 ClobberWalkerBase<BatchAAResults> WalkerBase(this, &BAA, DT);
1552 CachingWalker<BatchAAResults> WalkerLocal(this, &WalkerBase);
1553 OptimizeUses(this, &WalkerLocal, &BAA, DT).optimizeUses();
George Burgess IV5f308972016-07-19 01:29:15 +00001554
George Burgess IVe1100f52016-02-02 22:46:49 +00001555 // Mark the uses in unreachable blocks as live on entry, so that they go
1556 // somewhere.
1557 for (auto &BB : F)
1558 if (!Visited.count(&BB))
1559 markUnreachableAsLiveOnEntry(&BB);
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001560}
George Burgess IVe1100f52016-02-02 22:46:49 +00001561
George Burgess IV5f308972016-07-19 01:29:15 +00001562MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
1563
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001564MemorySSA::CachingWalker<AliasAnalysis> *MemorySSA::getWalkerImpl() {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001565 if (Walker)
1566 return Walker.get();
1567
Alina Sbirleabc8aa242019-01-07 19:22:37 +00001568 if (!WalkerBase)
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001569 WalkerBase =
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001570 std::make_unique<ClobberWalkerBase<AliasAnalysis>>(this, AA, DT);
Alina Sbirleabc8aa242019-01-07 19:22:37 +00001571
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001572 Walker =
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001573 std::make_unique<CachingWalker<AliasAnalysis>>(this, WalkerBase.get());
Geoff Berryb96d3b22016-06-01 21:30:40 +00001574 return Walker.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001575}
1576
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001577MemorySSAWalker *MemorySSA::getSkipSelfWalker() {
1578 if (SkipWalker)
1579 return SkipWalker.get();
1580
1581 if (!WalkerBase)
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001582 WalkerBase =
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001583 std::make_unique<ClobberWalkerBase<AliasAnalysis>>(this, AA, DT);
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001584
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001585 SkipWalker =
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001586 std::make_unique<SkipSelfWalker<AliasAnalysis>>(this, WalkerBase.get());
Alina Sbirlea12bbb4f2019-01-07 19:38:47 +00001587 return SkipWalker.get();
1588 }
1589
1590
Daniel Berlind602e042017-01-25 20:56:19 +00001591// This is a helper function used by the creation routines. It places NewAccess
1592// into the access and defs lists for a given basic block, at the given
1593// insertion point.
1594void MemorySSA::insertIntoListsForBlock(MemoryAccess *NewAccess,
1595 const BasicBlock *BB,
1596 InsertionPlace Point) {
1597 auto *Accesses = getOrCreateAccessList(BB);
1598 if (Point == Beginning) {
1599 // If it's a phi node, it goes first, otherwise, it goes after any phi
1600 // nodes.
1601 if (isa<MemoryPhi>(NewAccess)) {
1602 Accesses->push_front(NewAccess);
1603 auto *Defs = getOrCreateDefsList(BB);
1604 Defs->push_front(*NewAccess);
1605 } else {
1606 auto AI = find_if_not(
1607 *Accesses, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1608 Accesses->insert(AI, NewAccess);
1609 if (!isa<MemoryUse>(NewAccess)) {
1610 auto *Defs = getOrCreateDefsList(BB);
1611 auto DI = find_if_not(
1612 *Defs, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1613 Defs->insert(DI, *NewAccess);
1614 }
1615 }
1616 } else {
1617 Accesses->push_back(NewAccess);
1618 if (!isa<MemoryUse>(NewAccess)) {
1619 auto *Defs = getOrCreateDefsList(BB);
1620 Defs->push_back(*NewAccess);
1621 }
1622 }
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001623 BlockNumberingValid.erase(BB);
Daniel Berlind602e042017-01-25 20:56:19 +00001624}
1625
1626void MemorySSA::insertIntoListsBefore(MemoryAccess *What, const BasicBlock *BB,
1627 AccessList::iterator InsertPt) {
1628 auto *Accesses = getWritableBlockAccesses(BB);
1629 bool WasEnd = InsertPt == Accesses->end();
1630 Accesses->insert(AccessList::iterator(InsertPt), What);
1631 if (!isa<MemoryUse>(What)) {
1632 auto *Defs = getOrCreateDefsList(BB);
1633 // If we got asked to insert at the end, we have an easy job, just shove it
1634 // at the end. If we got asked to insert before an existing def, we also get
Zhaoshi Zhenga5531f22018-04-04 21:08:11 +00001635 // an iterator. If we got asked to insert before a use, we have to hunt for
Daniel Berlind602e042017-01-25 20:56:19 +00001636 // the next def.
1637 if (WasEnd) {
1638 Defs->push_back(*What);
1639 } else if (isa<MemoryDef>(InsertPt)) {
1640 Defs->insert(InsertPt->getDefsIterator(), *What);
1641 } else {
1642 while (InsertPt != Accesses->end() && !isa<MemoryDef>(InsertPt))
1643 ++InsertPt;
1644 // Either we found a def, or we are inserting at the end
1645 if (InsertPt == Accesses->end())
1646 Defs->push_back(*What);
1647 else
1648 Defs->insert(InsertPt->getDefsIterator(), *What);
1649 }
1650 }
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001651 BlockNumberingValid.erase(BB);
Daniel Berlind602e042017-01-25 20:56:19 +00001652}
1653
George Burgess IV5676a5d2018-08-22 22:34:38 +00001654void MemorySSA::prepareForMoveTo(MemoryAccess *What, BasicBlock *BB) {
1655 // Keep it in the lookup tables, remove from the lists
1656 removeFromLists(What, false);
1657
1658 // Note that moving should implicitly invalidate the optimized state of a
1659 // MemoryUse (and Phis can't be optimized). However, it doesn't do so for a
1660 // MemoryDef.
1661 if (auto *MD = dyn_cast<MemoryDef>(What))
1662 MD->resetOptimized();
1663 What->setBlock(BB);
1664}
1665
Zhaoshi Zhenga5531f22018-04-04 21:08:11 +00001666// Move What before Where in the IR. The end result is that What will belong to
Daniel Berlin60ead052017-01-28 01:23:13 +00001667// the right lists and have the right Block set, but will not otherwise be
1668// correct. It will not have the right defining access, and if it is a def,
1669// things below it will not properly be updated.
1670void MemorySSA::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
1671 AccessList::iterator Where) {
George Burgess IV5676a5d2018-08-22 22:34:38 +00001672 prepareForMoveTo(What, BB);
Daniel Berlin60ead052017-01-28 01:23:13 +00001673 insertIntoListsBefore(What, BB, Where);
1674}
1675
Alina Sbirlea0f533552018-07-11 22:11:46 +00001676void MemorySSA::moveTo(MemoryAccess *What, BasicBlock *BB,
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001677 InsertionPlace Point) {
Alina Sbirlea0f533552018-07-11 22:11:46 +00001678 if (isa<MemoryPhi>(What)) {
1679 assert(Point == Beginning &&
1680 "Can only move a Phi at the beginning of the block");
1681 // Update lookup table entry
1682 ValueToMemoryAccess.erase(What->getBlock());
1683 bool Inserted = ValueToMemoryAccess.insert({BB, What}).second;
1684 (void)Inserted;
1685 assert(Inserted && "Cannot move a Phi to a block that already has one");
1686 }
1687
George Burgess IV5676a5d2018-08-22 22:34:38 +00001688 prepareForMoveTo(What, BB);
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001689 insertIntoListsForBlock(What, BB, Point);
1690}
1691
Daniel Berlin14300262016-06-21 18:39:20 +00001692MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
1693 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
Daniel Berlin14300262016-06-21 18:39:20 +00001694 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001695 // Phi's always are placed at the front of the block.
Daniel Berlind602e042017-01-25 20:56:19 +00001696 insertIntoListsForBlock(Phi, BB, Beginning);
Daniel Berlin5130cc82016-07-31 21:08:20 +00001697 ValueToMemoryAccess[BB] = Phi;
Daniel Berlin14300262016-06-21 18:39:20 +00001698 return Phi;
1699}
1700
1701MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
Alina Sbirlea79800992018-09-10 20:13:01 +00001702 MemoryAccess *Definition,
Alina Sbirlea4bc625c2019-07-30 20:10:33 +00001703 const MemoryUseOrDef *Template,
1704 bool CreationMustSucceed) {
Daniel Berlin14300262016-06-21 18:39:20 +00001705 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001706 MemoryUseOrDef *NewAccess = createNewAccess(I, AA, Template);
Alina Sbirlea4bc625c2019-07-30 20:10:33 +00001707 if (CreationMustSucceed)
1708 assert(NewAccess != nullptr && "Tried to create a memory access for a "
1709 "non-memory touching instruction");
1710 if (NewAccess)
1711 NewAccess->setDefiningAccess(Definition);
Daniel Berlin14300262016-06-21 18:39:20 +00001712 return NewAccess;
1713}
1714
Daniel Berlind952cea2017-04-07 01:28:36 +00001715// Return true if the instruction has ordering constraints.
1716// Note specifically that this only considers stores and loads
1717// because others are still considered ModRef by getModRefInfo.
1718static inline bool isOrdered(const Instruction *I) {
1719 if (auto *SI = dyn_cast<StoreInst>(I)) {
1720 if (!SI->isUnordered())
1721 return true;
1722 } else if (auto *LI = dyn_cast<LoadInst>(I)) {
1723 if (!LI->isUnordered())
1724 return true;
1725 }
1726 return false;
1727}
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +00001728
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001729/// Helper function to create new memory accesses
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001730template <typename AliasAnalysisType>
Alina Sbirlea79800992018-09-10 20:13:01 +00001731MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I,
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001732 AliasAnalysisType *AAP,
Alina Sbirlea79800992018-09-10 20:13:01 +00001733 const MemoryUseOrDef *Template) {
Peter Collingbourneb9aa1f42016-05-26 04:58:46 +00001734 // The assume intrinsic has a control dependency which we model by claiming
Alina Sbirleaf7b40222019-09-10 22:35:27 +00001735 // that it writes arbitrarily. Debuginfo intrinsics may be considered
1736 // clobbers when we have a nonstandard AA pipeline. Ignore these fake memory
1737 // dependencies here.
Peter Collingbourneb9aa1f42016-05-26 04:58:46 +00001738 // FIXME: Replace this special casing with a more accurate modelling of
1739 // assume's control dependency.
1740 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
Alina Sbirlea6b2d1342019-09-17 16:31:37 +00001741 if (II->getIntrinsicID() == Intrinsic::assume)
Peter Collingbourneb9aa1f42016-05-26 04:58:46 +00001742 return nullptr;
1743
Alina Sbirlea6b2d1342019-09-17 16:31:37 +00001744 // Using a nonstandard AA pipelines might leave us with unexpected modref
1745 // results for I, so add a check to not model instructions that may not read
1746 // from or write to memory. This is necessary for correctness.
1747 if (!I->mayReadFromMemory() && !I->mayWriteToMemory())
1748 return nullptr;
1749
Alina Sbirlea79800992018-09-10 20:13:01 +00001750 bool Def, Use;
1751 if (Template) {
1752 Def = dyn_cast_or_null<MemoryDef>(Template) != nullptr;
1753 Use = dyn_cast_or_null<MemoryUse>(Template) != nullptr;
1754#if !defined(NDEBUG)
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001755 ModRefInfo ModRef = AAP->getModRefInfo(I, None);
Alina Sbirlea79800992018-09-10 20:13:01 +00001756 bool DefCheck, UseCheck;
1757 DefCheck = isModSet(ModRef) || isOrdered(I);
1758 UseCheck = isRefSet(ModRef);
1759 assert(Def == DefCheck && (Def || Use == UseCheck) && "Invalid template");
1760#endif
1761 } else {
1762 // Find out what affect this instruction has on memory.
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001763 ModRefInfo ModRef = AAP->getModRefInfo(I, None);
Alina Sbirlea79800992018-09-10 20:13:01 +00001764 // The isOrdered check is used to ensure that volatiles end up as defs
1765 // (atomics end up as ModRef right now anyway). Until we separate the
1766 // ordering chain from the memory chain, this enables people to see at least
1767 // some relative ordering to volatiles. Note that getClobberingMemoryAccess
1768 // will still give an answer that bypasses other volatile loads. TODO:
1769 // Separate memory aliasing and ordering into two different chains so that
1770 // we can precisely represent both "what memory will this read/write/is
1771 // clobbered by" and "what instructions can I move this past".
1772 Def = isModSet(ModRef) || isOrdered(I);
1773 Use = isRefSet(ModRef);
1774 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001775
1776 // It's possible for an instruction to not modify memory at all. During
1777 // construction, we ignore them.
Peter Collingbourneffecb142016-05-26 01:19:17 +00001778 if (!Def && !Use)
George Burgess IVe1100f52016-02-02 22:46:49 +00001779 return nullptr;
1780
George Burgess IVb42b7622016-03-11 19:34:03 +00001781 MemoryUseOrDef *MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001782 if (Def)
George Burgess IVb42b7622016-03-11 19:34:03 +00001783 MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
George Burgess IVe1100f52016-02-02 22:46:49 +00001784 else
George Burgess IVb42b7622016-03-11 19:34:03 +00001785 MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
Daniel Berlin5130cc82016-07-31 21:08:20 +00001786 ValueToMemoryAccess[I] = MUD;
George Burgess IVb42b7622016-03-11 19:34:03 +00001787 return MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001788}
1789
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001790/// Returns true if \p Replacer dominates \p Replacee .
George Burgess IVe1100f52016-02-02 22:46:49 +00001791bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
1792 const MemoryAccess *Replacee) const {
1793 if (isa<MemoryUseOrDef>(Replacee))
1794 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
1795 const auto *MP = cast<MemoryPhi>(Replacee);
1796 // For a phi node, the use occurs in the predecessor block of the phi node.
1797 // Since we may occur multiple times in the phi node, we have to check each
1798 // operand to ensure Replacer dominates each operand where Replacee occurs.
1799 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +00001800 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +00001801 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
1802 return false;
1803 }
1804 return true;
1805}
1806
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001807/// Properly remove \p MA from all of MemorySSA's lookup tables.
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001808void MemorySSA::removeFromLookups(MemoryAccess *MA) {
1809 assert(MA->use_empty() &&
1810 "Trying to remove memory access that still has uses");
Daniel Berlin5c46b942016-07-19 22:49:43 +00001811 BlockNumbering.erase(MA);
George Burgess IV2cbf9732018-06-22 22:34:07 +00001812 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001813 MUD->setDefiningAccess(nullptr);
1814 // Invalidate our walker's cache if necessary
1815 if (!isa<MemoryUse>(MA))
Alina Sbirleabfc779e2019-03-22 17:22:19 +00001816 getWalker()->invalidateInfo(MA);
George Burgess IV2cbf9732018-06-22 22:34:07 +00001817
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001818 Value *MemoryInst;
George Burgess IV2cbf9732018-06-22 22:34:07 +00001819 if (const auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001820 MemoryInst = MUD->getMemoryInst();
George Burgess IV2cbf9732018-06-22 22:34:07 +00001821 else
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001822 MemoryInst = MA->getBlock();
George Burgess IV2cbf9732018-06-22 22:34:07 +00001823
Daniel Berlin5130cc82016-07-31 21:08:20 +00001824 auto VMA = ValueToMemoryAccess.find(MemoryInst);
1825 if (VMA->second == MA)
1826 ValueToMemoryAccess.erase(VMA);
Daniel Berlin60ead052017-01-28 01:23:13 +00001827}
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001828
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001829/// Properly remove \p MA from all of MemorySSA's lists.
Daniel Berlin60ead052017-01-28 01:23:13 +00001830///
1831/// Because of the way the intrusive list and use lists work, it is important to
1832/// do removal in the right order.
1833/// ShouldDelete defaults to true, and will cause the memory access to also be
1834/// deleted, not just removed.
1835void MemorySSA::removeFromLists(MemoryAccess *MA, bool ShouldDelete) {
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001836 BasicBlock *BB = MA->getBlock();
Daniel Berlind602e042017-01-25 20:56:19 +00001837 // The access list owns the reference, so we erase it from the non-owning list
1838 // first.
1839 if (!isa<MemoryUse>(MA)) {
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001840 auto DefsIt = PerBlockDefs.find(BB);
Daniel Berlind602e042017-01-25 20:56:19 +00001841 std::unique_ptr<DefsList> &Defs = DefsIt->second;
1842 Defs->remove(*MA);
1843 if (Defs->empty())
1844 PerBlockDefs.erase(DefsIt);
1845 }
1846
Daniel Berlin60ead052017-01-28 01:23:13 +00001847 // The erase call here will delete it. If we don't want it deleted, we call
1848 // remove instead.
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001849 auto AccessIt = PerBlockAccesses.find(BB);
Daniel Berlinada263d2016-06-20 20:21:33 +00001850 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
Daniel Berlin60ead052017-01-28 01:23:13 +00001851 if (ShouldDelete)
1852 Accesses->erase(MA);
1853 else
1854 Accesses->remove(MA);
1855
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001856 if (Accesses->empty()) {
George Burgess IVe0e6e482016-03-02 02:35:04 +00001857 PerBlockAccesses.erase(AccessIt);
Alina Sbirleada1e80f2018-06-29 20:46:16 +00001858 BlockNumberingValid.erase(BB);
1859 }
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001860}
1861
George Burgess IVe1100f52016-02-02 22:46:49 +00001862void MemorySSA::print(raw_ostream &OS) const {
1863 MemorySSAAnnotatedWriter Writer(this);
1864 F.print(OS, &Writer);
1865}
1866
Aaron Ballman615eb472017-10-15 14:32:27 +00001867#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Daniel Berlin78cbd282017-02-20 22:26:03 +00001868LLVM_DUMP_METHOD void MemorySSA::dump() const { print(dbgs()); }
Matthias Braun8c209aa2017-01-28 02:02:38 +00001869#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001870
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001871void MemorySSA::verifyMemorySSA() const {
1872 verifyDefUses(F);
1873 verifyDomination(F);
Daniel Berlin14300262016-06-21 18:39:20 +00001874 verifyOrdering(F);
George Burgess IV97ec6242018-06-25 05:30:36 +00001875 verifyDominationNumbers(F);
Alina Sbirlea63e97fa2019-07-31 17:41:04 +00001876 verifyPrevDefInPhis(F);
Alina Sbirlead77edc02019-02-11 19:51:21 +00001877 // Previously, the verification used to also verify that the clobberingAccess
1878 // cached by MemorySSA is the same as the clobberingAccess found at a later
1879 // query to AA. This does not hold true in general due to the current fragility
1880 // of BasicAA which has arbitrary caps on the things it analyzes before giving
1881 // up. As a result, transformations that are correct, will lead to BasicAA
1882 // returning different Alias answers before and after that transformation.
1883 // Invalidating MemorySSA is not an option, as the results in BasicAA can be so
1884 // random, in the worst case we'd need to rebuild MemorySSA from scratch after
1885 // every transformation, which defeats the purpose of using it. For such an
1886 // example, see test4 added in D51960.
Daniel Berlin14300262016-06-21 18:39:20 +00001887}
1888
Alina Sbirlea63e97fa2019-07-31 17:41:04 +00001889void MemorySSA::verifyPrevDefInPhis(Function &F) const {
Alina Sbirlea594f0e02019-09-04 00:44:54 +00001890#if !defined(NDEBUG) && defined(EXPENSIVE_CHECKS)
Alina Sbirlea63e97fa2019-07-31 17:41:04 +00001891 for (const BasicBlock &BB : F) {
1892 if (MemoryPhi *Phi = getMemoryAccess(&BB)) {
1893 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
1894 auto *Pred = Phi->getIncomingBlock(I);
1895 auto *IncAcc = Phi->getIncomingValue(I);
1896 // If Pred has no unreachable predecessors, get last def looking at
1897 // IDoms. If, while walkings IDoms, any of these has an unreachable
Alina Sbirlea1a3fdaf2019-08-19 18:57:40 +00001898 // predecessor, then the incoming def can be any access.
Alina Sbirlea63e97fa2019-07-31 17:41:04 +00001899 if (auto *DTNode = DT->getNode(Pred)) {
1900 while (DTNode) {
1901 if (auto *DefList = getBlockDefs(DTNode->getBlock())) {
1902 auto *LastAcc = &*(--DefList->end());
1903 assert(LastAcc == IncAcc &&
1904 "Incorrect incoming access into phi.");
1905 break;
1906 }
1907 DTNode = DTNode->getIDom();
1908 }
Alina Sbirlea1a3fdaf2019-08-19 18:57:40 +00001909 } else {
Alina Sbirlea63e97fa2019-07-31 17:41:04 +00001910 // If Pred has unreachable predecessors, but has at least a Def, the
1911 // incoming access can be the last Def in Pred, or it could have been
Alina Sbirlea1a3fdaf2019-08-19 18:57:40 +00001912 // optimized to LoE. After an update, though, the LoE may have been
1913 // replaced by another access, so IncAcc may be any access.
Alina Sbirlea63e97fa2019-07-31 17:41:04 +00001914 // If Pred has unreachable predecessors and no Defs, incoming access
Alina Sbirlea1a3fdaf2019-08-19 18:57:40 +00001915 // should be LoE; However, after an update, it may be any access.
Alina Sbirlea63e97fa2019-07-31 17:41:04 +00001916 }
1917 }
1918 }
1919 }
1920#endif
1921}
1922
George Burgess IV97ec6242018-06-25 05:30:36 +00001923/// Verify that all of the blocks we believe to have valid domination numbers
1924/// actually have valid domination numbers.
1925void MemorySSA::verifyDominationNumbers(const Function &F) const {
1926#ifndef NDEBUG
1927 if (BlockNumberingValid.empty())
1928 return;
1929
1930 SmallPtrSet<const BasicBlock *, 16> ValidBlocks = BlockNumberingValid;
1931 for (const BasicBlock &BB : F) {
1932 if (!ValidBlocks.count(&BB))
1933 continue;
1934
1935 ValidBlocks.erase(&BB);
1936
1937 const AccessList *Accesses = getBlockAccesses(&BB);
1938 // It's correct to say an empty block has valid numbering.
1939 if (!Accesses)
1940 continue;
1941
1942 // Block numbering starts at 1.
1943 unsigned long LastNumber = 0;
1944 for (const MemoryAccess &MA : *Accesses) {
1945 auto ThisNumberIter = BlockNumbering.find(&MA);
1946 assert(ThisNumberIter != BlockNumbering.end() &&
1947 "MemoryAccess has no domination number in a valid block!");
1948
1949 unsigned long ThisNumber = ThisNumberIter->second;
1950 assert(ThisNumber > LastNumber &&
1951 "Domination numbers should be strictly increasing!");
1952 LastNumber = ThisNumber;
1953 }
1954 }
1955
1956 assert(ValidBlocks.empty() &&
1957 "All valid BasicBlocks should exist in F -- dangling pointers?");
1958#endif
1959}
1960
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001961/// Verify that the order and existence of MemoryAccesses matches the
Daniel Berlin14300262016-06-21 18:39:20 +00001962/// order and existence of memory affecting instructions.
1963void MemorySSA::verifyOrdering(Function &F) const {
George Burgess IV6a9aa022018-08-28 00:32:32 +00001964#ifndef NDEBUG
Daniel Berlin14300262016-06-21 18:39:20 +00001965 // Walk all the blocks, comparing what the lookups think and what the access
1966 // lists think, as well as the order in the blocks vs the order in the access
1967 // lists.
1968 SmallVector<MemoryAccess *, 32> ActualAccesses;
Daniel Berlind602e042017-01-25 20:56:19 +00001969 SmallVector<MemoryAccess *, 32> ActualDefs;
Daniel Berlin14300262016-06-21 18:39:20 +00001970 for (BasicBlock &B : F) {
1971 const AccessList *AL = getBlockAccesses(&B);
Daniel Berlind602e042017-01-25 20:56:19 +00001972 const auto *DL = getBlockDefs(&B);
Daniel Berlin14300262016-06-21 18:39:20 +00001973 MemoryAccess *Phi = getMemoryAccess(&B);
Daniel Berlind602e042017-01-25 20:56:19 +00001974 if (Phi) {
Daniel Berlin14300262016-06-21 18:39:20 +00001975 ActualAccesses.push_back(Phi);
Daniel Berlind602e042017-01-25 20:56:19 +00001976 ActualDefs.push_back(Phi);
1977 }
1978
Daniel Berlin14300262016-06-21 18:39:20 +00001979 for (Instruction &I : B) {
1980 MemoryAccess *MA = getMemoryAccess(&I);
Daniel Berlind602e042017-01-25 20:56:19 +00001981 assert((!MA || (AL && (isa<MemoryUse>(MA) || DL))) &&
1982 "We have memory affecting instructions "
1983 "in this block but they are not in the "
1984 "access list or defs list");
1985 if (MA) {
Daniel Berlin14300262016-06-21 18:39:20 +00001986 ActualAccesses.push_back(MA);
Daniel Berlind602e042017-01-25 20:56:19 +00001987 if (isa<MemoryDef>(MA))
1988 ActualDefs.push_back(MA);
1989 }
Daniel Berlin14300262016-06-21 18:39:20 +00001990 }
1991 // Either we hit the assert, really have no accesses, or we have both
Daniel Berlind602e042017-01-25 20:56:19 +00001992 // accesses and an access list.
1993 // Same with defs.
1994 if (!AL && !DL)
Daniel Berlin14300262016-06-21 18:39:20 +00001995 continue;
1996 assert(AL->size() == ActualAccesses.size() &&
1997 "We don't have the same number of accesses in the block as on the "
1998 "access list");
Davide Italiano6c77de02017-01-30 03:16:43 +00001999 assert((DL || ActualDefs.size() == 0) &&
2000 "Either we should have a defs list, or we should have no defs");
Daniel Berlind602e042017-01-25 20:56:19 +00002001 assert((!DL || DL->size() == ActualDefs.size()) &&
2002 "We don't have the same number of defs in the block as on the "
2003 "def list");
Daniel Berlin14300262016-06-21 18:39:20 +00002004 auto ALI = AL->begin();
2005 auto AAI = ActualAccesses.begin();
2006 while (ALI != AL->end() && AAI != ActualAccesses.end()) {
2007 assert(&*ALI == *AAI && "Not the same accesses in the same order");
2008 ++ALI;
2009 ++AAI;
2010 }
2011 ActualAccesses.clear();
Daniel Berlind602e042017-01-25 20:56:19 +00002012 if (DL) {
2013 auto DLI = DL->begin();
2014 auto ADI = ActualDefs.begin();
2015 while (DLI != DL->end() && ADI != ActualDefs.end()) {
2016 assert(&*DLI == *ADI && "Not the same defs in the same order");
2017 ++DLI;
2018 ++ADI;
2019 }
2020 }
2021 ActualDefs.clear();
Daniel Berlin14300262016-06-21 18:39:20 +00002022 }
George Burgess IV6a9aa022018-08-28 00:32:32 +00002023#endif
Daniel Berlin932b4cb2016-02-10 17:39:43 +00002024}
2025
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002026/// Verify the domination properties of MemorySSA by checking that each
George Burgess IVe1100f52016-02-02 22:46:49 +00002027/// definition dominates all of its uses.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00002028void MemorySSA::verifyDomination(Function &F) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00002029#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00002030 for (BasicBlock &B : F) {
2031 // Phi nodes are attached to basic blocks
Daniel Berlin2919b1c2016-08-05 21:46:52 +00002032 if (MemoryPhi *MP = getMemoryAccess(&B))
2033 for (const Use &U : MP->uses())
2034 assert(dominates(MP, U) && "Memory PHI does not dominate it's uses");
Daniel Berlin7af95872016-08-05 21:47:20 +00002035
George Burgess IVe1100f52016-02-02 22:46:49 +00002036 for (Instruction &I : B) {
2037 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
2038 if (!MD)
2039 continue;
2040
Daniel Berlin2919b1c2016-08-05 21:46:52 +00002041 for (const Use &U : MD->uses())
2042 assert(dominates(MD, U) && "Memory Def does not dominate it's uses");
George Burgess IVe1100f52016-02-02 22:46:49 +00002043 }
2044 }
Daniel Berlin7af95872016-08-05 21:47:20 +00002045#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00002046}
2047
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002048/// Verify the def-use lists in MemorySSA, by verifying that \p Use
George Burgess IVe1100f52016-02-02 22:46:49 +00002049/// appears in the use list of \p Def.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00002050void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00002051#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00002052 // The live on entry use may cause us to get a NULL def here
Daniel Berlin7af95872016-08-05 21:47:20 +00002053 if (!Def)
2054 assert(isLiveOnEntryDef(Use) &&
2055 "Null def but use not point to live on entry def");
2056 else
Daniel Berlinda2f38e2016-08-11 21:26:50 +00002057 assert(is_contained(Def->users(), Use) &&
Daniel Berlin7af95872016-08-05 21:47:20 +00002058 "Did not find use in def's use list");
2059#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00002060}
2061
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002062/// Verify the immediate use information, by walking all the memory
George Burgess IVe1100f52016-02-02 22:46:49 +00002063/// accesses and verifying that, for each use, it appears in the
2064/// appropriate def's use list
Daniel Berlin932b4cb2016-02-10 17:39:43 +00002065void MemorySSA::verifyDefUses(Function &F) const {
Alina Sbirlea594f0e02019-09-04 00:44:54 +00002066#if !defined(NDEBUG) && defined(EXPENSIVE_CHECKS)
George Burgess IVe1100f52016-02-02 22:46:49 +00002067 for (BasicBlock &B : F) {
2068 // Phi nodes are attached to basic blocks
Daniel Berlin14300262016-06-21 18:39:20 +00002069 if (MemoryPhi *Phi = getMemoryAccess(&B)) {
David Majnemer580e7542016-06-25 00:04:06 +00002070 assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
2071 pred_begin(&B), pred_end(&B))) &&
Daniel Berlin14300262016-06-21 18:39:20 +00002072 "Incomplete MemoryPhi Node");
Alina Sbirlea201d02c2018-06-20 21:06:13 +00002073 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002074 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
Alina Sbirlea201d02c2018-06-20 21:06:13 +00002075 assert(find(predecessors(&B), Phi->getIncomingBlock(I)) !=
2076 pred_end(&B) &&
2077 "Incoming phi block not a block predecessor");
2078 }
Daniel Berlin14300262016-06-21 18:39:20 +00002079 }
George Burgess IVe1100f52016-02-02 22:46:49 +00002080
2081 for (Instruction &I : B) {
George Burgess IV66837ab2016-11-01 21:17:46 +00002082 if (MemoryUseOrDef *MA = getMemoryAccess(&I)) {
2083 verifyUseInDefs(MA->getDefiningAccess(), MA);
George Burgess IVe1100f52016-02-02 22:46:49 +00002084 }
2085 }
2086 }
George Burgess IV6a9aa022018-08-28 00:32:32 +00002087#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00002088}
2089
Daniel Berlin5c46b942016-07-19 22:49:43 +00002090/// Perform a local numbering on blocks so that instruction ordering can be
2091/// determined in constant time.
2092/// TODO: We currently just number in order. If we numbered by N, we could
2093/// allow at least N-1 sequences of insertBefore or insertAfter (and at least
2094/// log2(N) sequences of mixed before and after) without needing to invalidate
2095/// the numbering.
2096void MemorySSA::renumberBlock(const BasicBlock *B) const {
2097 // The pre-increment ensures the numbers really start at 1.
2098 unsigned long CurrentNumber = 0;
2099 const AccessList *AL = getBlockAccesses(B);
2100 assert(AL != nullptr && "Asking to renumber an empty block");
2101 for (const auto &I : *AL)
2102 BlockNumbering[&I] = ++CurrentNumber;
2103 BlockNumberingValid.insert(B);
2104}
2105
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002106/// Determine, for two memory accesses in the same block,
George Burgess IVe1100f52016-02-02 22:46:49 +00002107/// whether \p Dominator dominates \p Dominatee.
2108/// \returns True if \p Dominator dominates \p Dominatee.
2109bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
2110 const MemoryAccess *Dominatee) const {
Daniel Berlin5c46b942016-07-19 22:49:43 +00002111 const BasicBlock *DominatorBlock = Dominator->getBlock();
Daniel Berlin5c46b942016-07-19 22:49:43 +00002112
Daniel Berlin19860302016-07-19 23:08:08 +00002113 assert((DominatorBlock == Dominatee->getBlock()) &&
Daniel Berlin5c46b942016-07-19 22:49:43 +00002114 "Asking for local domination when accesses are in different blocks!");
Sebastian Pope1f60b12016-06-10 21:36:41 +00002115 // A node dominates itself.
2116 if (Dominatee == Dominator)
2117 return true;
2118
2119 // When Dominatee is defined on function entry, it is not dominated by another
2120 // memory access.
2121 if (isLiveOnEntryDef(Dominatee))
2122 return false;
2123
2124 // When Dominator is defined on function entry, it dominates the other memory
2125 // access.
2126 if (isLiveOnEntryDef(Dominator))
2127 return true;
2128
Daniel Berlin5c46b942016-07-19 22:49:43 +00002129 if (!BlockNumberingValid.count(DominatorBlock))
2130 renumberBlock(DominatorBlock);
George Burgess IVe1100f52016-02-02 22:46:49 +00002131
Daniel Berlin5c46b942016-07-19 22:49:43 +00002132 unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
2133 // All numbers start with 1
2134 assert(DominatorNum != 0 && "Block was not numbered properly");
2135 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
2136 assert(DominateeNum != 0 && "Block was not numbered properly");
2137 return DominatorNum < DominateeNum;
George Burgess IVe1100f52016-02-02 22:46:49 +00002138}
2139
George Burgess IV5f308972016-07-19 01:29:15 +00002140bool MemorySSA::dominates(const MemoryAccess *Dominator,
2141 const MemoryAccess *Dominatee) const {
2142 if (Dominator == Dominatee)
2143 return true;
2144
2145 if (isLiveOnEntryDef(Dominatee))
2146 return false;
2147
2148 if (Dominator->getBlock() != Dominatee->getBlock())
2149 return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
2150 return locallyDominates(Dominator, Dominatee);
2151}
2152
Daniel Berlin2919b1c2016-08-05 21:46:52 +00002153bool MemorySSA::dominates(const MemoryAccess *Dominator,
2154 const Use &Dominatee) const {
2155 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Dominatee.getUser())) {
2156 BasicBlock *UseBB = MP->getIncomingBlock(Dominatee);
2157 // The def must dominate the incoming block of the phi.
2158 if (UseBB != Dominator->getBlock())
2159 return DT->dominates(Dominator->getBlock(), UseBB);
2160 // If the UseBB and the DefBB are the same, compare locally.
2161 return locallyDominates(Dominator, cast<MemoryAccess>(Dominatee));
2162 }
2163 // If it's not a PHI node use, the normal dominates can already handle it.
2164 return dominates(Dominator, cast<MemoryAccess>(Dominatee.getUser()));
2165}
2166
George Burgess IVe1100f52016-02-02 22:46:49 +00002167const static char LiveOnEntryStr[] = "liveOnEntry";
2168
Reid Kleckner96ab8722017-05-18 17:24:10 +00002169void MemoryAccess::print(raw_ostream &OS) const {
2170 switch (getValueID()) {
2171 case MemoryPhiVal: return static_cast<const MemoryPhi *>(this)->print(OS);
2172 case MemoryDefVal: return static_cast<const MemoryDef *>(this)->print(OS);
2173 case MemoryUseVal: return static_cast<const MemoryUse *>(this)->print(OS);
2174 }
2175 llvm_unreachable("invalid value id");
2176}
2177
George Burgess IVe1100f52016-02-02 22:46:49 +00002178void MemoryDef::print(raw_ostream &OS) const {
2179 MemoryAccess *UO = getDefiningAccess();
2180
George Burgess IVaa283d82018-06-14 19:55:53 +00002181 auto printID = [&OS](MemoryAccess *A) {
2182 if (A && A->getID())
2183 OS << A->getID();
2184 else
2185 OS << LiveOnEntryStr;
2186 };
2187
George Burgess IVe1100f52016-02-02 22:46:49 +00002188 OS << getID() << " = MemoryDef(";
George Burgess IVaa283d82018-06-14 19:55:53 +00002189 printID(UO);
2190 OS << ")";
2191
2192 if (isOptimized()) {
2193 OS << "->";
2194 printID(getOptimized());
2195
2196 if (Optional<AliasResult> AR = getOptimizedAccessType())
2197 OS << " " << *AR;
2198 }
George Burgess IVe1100f52016-02-02 22:46:49 +00002199}
2200
2201void MemoryPhi::print(raw_ostream &OS) const {
2202 bool First = true;
2203 OS << getID() << " = MemoryPhi(";
2204 for (const auto &Op : operands()) {
2205 BasicBlock *BB = getIncomingBlock(Op);
2206 MemoryAccess *MA = cast<MemoryAccess>(Op);
2207 if (!First)
2208 OS << ',';
2209 else
2210 First = false;
2211
2212 OS << '{';
2213 if (BB->hasName())
2214 OS << BB->getName();
2215 else
2216 BB->printAsOperand(OS, false);
2217 OS << ',';
2218 if (unsigned ID = MA->getID())
2219 OS << ID;
2220 else
2221 OS << LiveOnEntryStr;
2222 OS << '}';
2223 }
2224 OS << ')';
2225}
2226
George Burgess IVe1100f52016-02-02 22:46:49 +00002227void MemoryUse::print(raw_ostream &OS) const {
2228 MemoryAccess *UO = getDefiningAccess();
2229 OS << "MemoryUse(";
2230 if (UO && UO->getID())
2231 OS << UO->getID();
2232 else
2233 OS << LiveOnEntryStr;
2234 OS << ')';
George Burgess IVaa283d82018-06-14 19:55:53 +00002235
2236 if (Optional<AliasResult> AR = getOptimizedAccessType())
2237 OS << " " << *AR;
George Burgess IVe1100f52016-02-02 22:46:49 +00002238}
2239
2240void MemoryAccess::dump() const {
Daniel Berlin78cbd282017-02-20 22:26:03 +00002241// Cannot completely remove virtual function even in release mode.
Aaron Ballman615eb472017-10-15 14:32:27 +00002242#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
George Burgess IVe1100f52016-02-02 22:46:49 +00002243 print(dbgs());
2244 dbgs() << "\n";
Matthias Braun8c209aa2017-01-28 02:02:38 +00002245#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00002246}
2247
Chad Rosier232e29e2016-07-06 21:20:47 +00002248char MemorySSAPrinterLegacyPass::ID = 0;
2249
2250MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) {
2251 initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
2252}
2253
2254void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
2255 AU.setPreservesAll();
2256 AU.addRequired<MemorySSAWrapperPass>();
Chad Rosier232e29e2016-07-06 21:20:47 +00002257}
2258
2259bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) {
2260 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
2261 MSSA.print(dbgs());
2262 if (VerifyMemorySSA)
2263 MSSA.verifyMemorySSA();
2264 return false;
2265}
2266
Chandler Carruthdab4eae2016-11-23 17:53:26 +00002267AnalysisKey MemorySSAAnalysis::Key;
George Burgess IVe1100f52016-02-02 22:46:49 +00002268
Daniel Berlin1e98c042016-09-26 17:22:54 +00002269MemorySSAAnalysis::Result MemorySSAAnalysis::run(Function &F,
2270 FunctionAnalysisManager &AM) {
Geoff Berryb96d3b22016-06-01 21:30:40 +00002271 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2272 auto &AA = AM.getResult<AAManager>(F);
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00002273 return MemorySSAAnalysis::Result(std::make_unique<MemorySSA>(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00002274}
2275
Alina Sbirleab4683202019-04-30 22:43:55 +00002276bool MemorySSAAnalysis::Result::invalidate(
2277 Function &F, const PreservedAnalyses &PA,
2278 FunctionAnalysisManager::Invalidator &Inv) {
2279 auto PAC = PA.getChecker<MemorySSAAnalysis>();
2280 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
2281 Inv.invalidate<AAManager>(F, PA) ||
2282 Inv.invalidate<DominatorTreeAnalysis>(F, PA);
2283}
2284
Geoff Berryb96d3b22016-06-01 21:30:40 +00002285PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
2286 FunctionAnalysisManager &AM) {
2287 OS << "MemorySSA for function: " << F.getName() << "\n";
Geoff Berry290a13e2016-08-08 18:27:22 +00002288 AM.getResult<MemorySSAAnalysis>(F).getMSSA().print(OS);
Geoff Berryb96d3b22016-06-01 21:30:40 +00002289
2290 return PreservedAnalyses::all();
George Burgess IVe1100f52016-02-02 22:46:49 +00002291}
2292
Geoff Berryb96d3b22016-06-01 21:30:40 +00002293PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
2294 FunctionAnalysisManager &AM) {
Geoff Berry290a13e2016-08-08 18:27:22 +00002295 AM.getResult<MemorySSAAnalysis>(F).getMSSA().verifyMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00002296
2297 return PreservedAnalyses::all();
2298}
2299
2300char MemorySSAWrapperPass::ID = 0;
2301
2302MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
2303 initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
2304}
2305
2306void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
2307
2308void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00002309 AU.setPreservesAll();
Geoff Berryb96d3b22016-06-01 21:30:40 +00002310 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
2311 AU.addRequiredTransitive<AAResultsWrapperPass>();
George Burgess IVe1100f52016-02-02 22:46:49 +00002312}
2313
Geoff Berryb96d3b22016-06-01 21:30:40 +00002314bool MemorySSAWrapperPass::runOnFunction(Function &F) {
2315 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2316 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2317 MSSA.reset(new MemorySSA(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00002318 return false;
2319}
2320
Geoff Berryb96d3b22016-06-01 21:30:40 +00002321void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); }
George Burgess IVe1100f52016-02-02 22:46:49 +00002322
Geoff Berryb96d3b22016-06-01 21:30:40 +00002323void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00002324 MSSA->print(OS);
2325}
2326
George Burgess IVe1100f52016-02-02 22:46:49 +00002327MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
2328
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002329/// Walk the use-def chains starting at \p StartingAccess and find
George Burgess IVe1100f52016-02-02 22:46:49 +00002330/// the MemoryAccess that actually clobbers Loc.
2331///
2332/// \returns our clobbering memory access
Alina Sbirleabfc779e2019-03-22 17:22:19 +00002333template <typename AliasAnalysisType>
2334MemoryAccess *
2335MemorySSA::ClobberWalkerBase<AliasAnalysisType>::getClobberingMemoryAccessBase(
Alina Sbirleaf085cc52019-03-29 21:56:09 +00002336 MemoryAccess *StartingAccess, const MemoryLocation &Loc,
2337 unsigned &UpwardWalkLimit) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002338 if (isa<MemoryPhi>(StartingAccess))
2339 return StartingAccess;
2340
2341 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
2342 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
2343 return StartingUseOrDef;
2344
2345 Instruction *I = StartingUseOrDef->getMemoryInst();
2346
2347 // Conservatively, fences are always clobbers, so don't perform the walk if we
2348 // hit a fence.
Chandler Carruth363ac682019-01-07 05:42:51 +00002349 if (!isa<CallBase>(I) && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002350 return StartingUseOrDef;
2351
2352 UpwardsMemoryQuery Q;
2353 Q.OriginalAccess = StartingUseOrDef;
2354 Q.StartingLoc = Loc;
George Burgess IV5f308972016-07-19 01:29:15 +00002355 Q.Inst = I;
George Burgess IVe1100f52016-02-02 22:46:49 +00002356 Q.IsCall = false;
George Burgess IVe1100f52016-02-02 22:46:49 +00002357
George Burgess IVe1100f52016-02-02 22:46:49 +00002358 // Unlike the other function, do not walk to the def of a def, because we are
2359 // handed something we already believe is the clobbering access.
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002360 // We never set SkipSelf to true in Q in this method.
George Burgess IVe1100f52016-02-02 22:46:49 +00002361 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
2362 ? StartingUseOrDef->getDefiningAccess()
2363 : StartingUseOrDef;
2364
Alina Sbirleaf085cc52019-03-29 21:56:09 +00002365 MemoryAccess *Clobber =
2366 Walker.findClobber(DefiningAccess, Q, UpwardWalkLimit);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002367 LLVM_DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2368 LLVM_DEBUG(dbgs() << *StartingUseOrDef << "\n");
2369 LLVM_DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2370 LLVM_DEBUG(dbgs() << *Clobber << "\n");
George Burgess IVe1100f52016-02-02 22:46:49 +00002371 return Clobber;
2372}
2373
Alina Sbirleabfc779e2019-03-22 17:22:19 +00002374template <typename AliasAnalysisType>
George Burgess IVe1100f52016-02-02 22:46:49 +00002375MemoryAccess *
Alina Sbirleabfc779e2019-03-22 17:22:19 +00002376MemorySSA::ClobberWalkerBase<AliasAnalysisType>::getClobberingMemoryAccessBase(
Alina Sbirleaf085cc52019-03-29 21:56:09 +00002377 MemoryAccess *MA, unsigned &UpwardWalkLimit, bool SkipSelf) {
George Burgess IV400ae402016-07-20 19:51:34 +00002378 auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
2379 // If this is a MemoryPhi, we can't do anything.
2380 if (!StartingAccess)
2381 return MA;
George Burgess IVe1100f52016-02-02 22:46:49 +00002382
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002383 bool IsOptimized = false;
2384
Daniel Berlincd2deac2016-10-20 20:13:45 +00002385 // If this is an already optimized use or def, return the optimized result.
Alina Sbirlead90c9f42018-03-08 18:03:14 +00002386 // Note: Currently, we store the optimized def result in a separate field,
2387 // since we can't use the defining access.
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002388 if (StartingAccess->isOptimized()) {
2389 if (!SkipSelf || !isa<MemoryDef>(StartingAccess))
2390 return StartingAccess->getOptimized();
2391 IsOptimized = true;
2392 }
Daniel Berlincd2deac2016-10-20 20:13:45 +00002393
George Burgess IV400ae402016-07-20 19:51:34 +00002394 const Instruction *I = StartingAccess->getMemoryInst();
George Burgess IV44477c62018-03-11 04:16:12 +00002395 // We can't sanely do anything with a fence, since they conservatively clobber
2396 // all memory, and have no locations to get pointers from to try to
2397 // disambiguate.
Chandler Carruth363ac682019-01-07 05:42:51 +00002398 if (!isa<CallBase>(I) && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002399 return StartingAccess;
2400
Alina Sbirleab4d088d2018-11-13 21:12:49 +00002401 UpwardsMemoryQuery Q(I, StartingAccess);
2402
Alina Sbirleabfc779e2019-03-22 17:22:19 +00002403 if (isUseTriviallyOptimizableToLiveOnEntry(*Walker.getAA(), I)) {
George Burgess IV024f3d22016-08-03 19:57:02 +00002404 MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef();
George Burgess IV44477c62018-03-11 04:16:12 +00002405 StartingAccess->setOptimized(LiveOnEntry);
2406 StartingAccess->setOptimizedAccessType(None);
George Burgess IV024f3d22016-08-03 19:57:02 +00002407 return LiveOnEntry;
2408 }
2409
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002410 MemoryAccess *OptimizedAccess;
2411 if (!IsOptimized) {
2412 // Start with the thing we already think clobbers this location
2413 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
George Burgess IVe1100f52016-02-02 22:46:49 +00002414
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002415 // At this point, DefiningAccess may be the live on entry def.
2416 // If it is, we will not get a better result.
2417 if (MSSA->isLiveOnEntryDef(DefiningAccess)) {
2418 StartingAccess->setOptimized(DefiningAccess);
2419 StartingAccess->setOptimizedAccessType(None);
2420 return DefiningAccess;
2421 }
George Burgess IVe1100f52016-02-02 22:46:49 +00002422
Alina Sbirleaf085cc52019-03-29 21:56:09 +00002423 OptimizedAccess = Walker.findClobber(DefiningAccess, Q, UpwardWalkLimit);
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002424 StartingAccess->setOptimized(OptimizedAccess);
2425 if (MSSA->isLiveOnEntryDef(OptimizedAccess))
2426 StartingAccess->setOptimizedAccessType(None);
2427 else if (Q.AR == MustAlias)
2428 StartingAccess->setOptimizedAccessType(MustAlias);
2429 } else
2430 OptimizedAccess = StartingAccess->getOptimized();
2431
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002432 LLVM_DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002433 LLVM_DEBUG(dbgs() << *StartingAccess << "\n");
2434 LLVM_DEBUG(dbgs() << "Optimized Memory SSA clobber for " << *I << " is ");
2435 LLVM_DEBUG(dbgs() << *OptimizedAccess << "\n");
Alina Sbirlead90c9f42018-03-08 18:03:14 +00002436
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002437 MemoryAccess *Result;
2438 if (SkipSelf && isa<MemoryPhi>(OptimizedAccess) &&
Alina Sbirleaf085cc52019-03-29 21:56:09 +00002439 isa<MemoryDef>(StartingAccess) && UpwardWalkLimit) {
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002440 assert(isa<MemoryDef>(Q.OriginalAccess));
2441 Q.SkipSelfAccess = true;
Alina Sbirleaf085cc52019-03-29 21:56:09 +00002442 Result = Walker.findClobber(OptimizedAccess, Q, UpwardWalkLimit);
Alina Sbirleabc8aa242019-01-07 19:22:37 +00002443 } else
2444 Result = OptimizedAccess;
2445
2446 LLVM_DEBUG(dbgs() << "Result Memory SSA clobber [SkipSelf = " << SkipSelf);
2447 LLVM_DEBUG(dbgs() << "] for " << *I << " is " << *Result << "\n");
George Burgess IVe1100f52016-02-02 22:46:49 +00002448
2449 return Result;
2450}
2451
George Burgess IVe1100f52016-02-02 22:46:49 +00002452MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002453DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002454 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
2455 return Use->getDefiningAccess();
2456 return MA;
2457}
2458
2459MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
George Burgess IV013fd732016-10-28 19:22:46 +00002460 MemoryAccess *StartingAccess, const MemoryLocation &) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002461 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
2462 return Use->getDefiningAccess();
2463 return StartingAccess;
2464}
Reid Kleckner96ab8722017-05-18 17:24:10 +00002465
2466void MemoryPhi::deleteMe(DerivedUser *Self) {
2467 delete static_cast<MemoryPhi *>(Self);
2468}
2469
2470void MemoryDef::deleteMe(DerivedUser *Self) {
2471 delete static_cast<MemoryDef *>(Self);
2472}
2473
2474void MemoryUse::deleteMe(DerivedUser *Self) {
2475 delete static_cast<MemoryUse *>(Self);
2476}