blob: dddfb3c50495c86046789722a21f81c2535284fe [file] [log] [blame]
Simon Pilgrim7ce99262017-06-13 09:58:27 +00001//===-- MemorySSA.cpp - Memory SSA Builder---------------------------===//
George Burgess IVe1100f52016-02-02 22:46:49 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------===//
9//
10// This file implements the MemorySSA class.
11//
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"
15#include "llvm/ADT/DenseSet.h"
16#include "llvm/ADT/DepthFirstIterator.h"
17#include "llvm/ADT/GraphTraits.h"
18#include "llvm/ADT/PostOrderIterator.h"
19#include "llvm/ADT/STLExtras.h"
George Burgess IV5f308972016-07-19 01:29:15 +000020#include "llvm/ADT/SmallBitVector.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000021#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/SmallSet.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/Analysis/AliasAnalysis.h"
25#include "llvm/Analysis/CFG.h"
26#include "llvm/Analysis/GlobalsModRef.h"
27#include "llvm/Analysis/IteratedDominanceFrontier.h"
28#include "llvm/Analysis/MemoryLocation.h"
29#include "llvm/Analysis/PHITransAddr.h"
30#include "llvm/IR/AssemblyAnnotationWriter.h"
31#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/Dominators.h"
33#include "llvm/IR/GlobalVariable.h"
34#include "llvm/IR/IRBuilder.h"
35#include "llvm/IR/IntrinsicInst.h"
36#include "llvm/IR/LLVMContext.h"
37#include "llvm/IR/Metadata.h"
38#include "llvm/IR/Module.h"
39#include "llvm/IR/PatternMatch.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000040#include "llvm/Support/Debug.h"
41#include "llvm/Support/FormattedStream.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000042#include <algorithm>
43
44#define DEBUG_TYPE "memoryssa"
45using namespace llvm;
Geoff Berryefb0dd12016-06-14 21:19:40 +000046INITIALIZE_PASS_BEGIN(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
Geoff Berryb96d3b22016-06-01 21:30:40 +000047 true)
George Burgess IVe1100f52016-02-02 22:46:49 +000048INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
49INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Geoff Berryefb0dd12016-06-14 21:19:40 +000050INITIALIZE_PASS_END(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
51 true)
George Burgess IVe1100f52016-02-02 22:46:49 +000052
Chad Rosier232e29e2016-07-06 21:20:47 +000053INITIALIZE_PASS_BEGIN(MemorySSAPrinterLegacyPass, "print-memoryssa",
54 "Memory SSA Printer", false, false)
55INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
56INITIALIZE_PASS_END(MemorySSAPrinterLegacyPass, "print-memoryssa",
57 "Memory SSA Printer", false, false)
58
Daniel Berlinc43aa5a2016-08-02 16:24:03 +000059static cl::opt<unsigned> MaxCheckLimit(
60 "memssa-check-limit", cl::Hidden, cl::init(100),
61 cl::desc("The maximum number of stores/phis MemorySSA"
62 "will consider trying to walk past (default = 100)"));
63
Chad Rosier232e29e2016-07-06 21:20:47 +000064static cl::opt<bool>
65 VerifyMemorySSA("verify-memoryssa", cl::init(false), cl::Hidden,
66 cl::desc("Verify MemorySSA in legacy printer pass."));
67
George Burgess IVe1100f52016-02-02 22:46:49 +000068namespace llvm {
George Burgess IVe1100f52016-02-02 22:46:49 +000069/// \brief An assembly annotator class to print Memory SSA information in
70/// comments.
71class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter {
72 friend class MemorySSA;
73 const MemorySSA *MSSA;
74
75public:
76 MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {}
77
78 virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
79 formatted_raw_ostream &OS) {
80 if (MemoryAccess *MA = MSSA->getMemoryAccess(BB))
81 OS << "; " << *MA << "\n";
82 }
83
84 virtual void emitInstructionAnnot(const Instruction *I,
85 formatted_raw_ostream &OS) {
86 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
87 OS << "; " << *MA << "\n";
88 }
89};
George Burgess IV5f308972016-07-19 01:29:15 +000090}
George Burgess IVfd1f2f82016-06-24 21:02:12 +000091
George Burgess IV5f308972016-07-19 01:29:15 +000092namespace {
Daniel Berlindff31de2016-08-02 21:57:52 +000093/// Our current alias analysis API differentiates heavily between calls and
94/// non-calls, and functions called on one usually assert on the other.
95/// This class encapsulates the distinction to simplify other code that wants
96/// "Memory affecting instructions and related data" to use as a key.
97/// For example, this class is used as a densemap key in the use optimizer.
98class MemoryLocOrCall {
99public:
100 MemoryLocOrCall() : IsCall(false) {}
101 MemoryLocOrCall(MemoryUseOrDef *MUD)
102 : MemoryLocOrCall(MUD->getMemoryInst()) {}
Sebastian Pop5068d7a2016-10-13 03:23:33 +0000103 MemoryLocOrCall(const MemoryUseOrDef *MUD)
104 : MemoryLocOrCall(MUD->getMemoryInst()) {}
Daniel Berlindff31de2016-08-02 21:57:52 +0000105
106 MemoryLocOrCall(Instruction *Inst) {
107 if (ImmutableCallSite(Inst)) {
108 IsCall = true;
109 CS = ImmutableCallSite(Inst);
110 } else {
111 IsCall = false;
112 // There is no such thing as a memorylocation for a fence inst, and it is
113 // unique in that regard.
114 if (!isa<FenceInst>(Inst))
115 Loc = MemoryLocation::get(Inst);
116 }
117 }
118
119 explicit MemoryLocOrCall(const MemoryLocation &Loc)
120 : IsCall(false), Loc(Loc) {}
121
122 bool IsCall;
123 ImmutableCallSite getCS() const {
124 assert(IsCall);
125 return CS;
126 }
127 MemoryLocation getLoc() const {
128 assert(!IsCall);
129 return Loc;
130 }
131
132 bool operator==(const MemoryLocOrCall &Other) const {
133 if (IsCall != Other.IsCall)
134 return false;
135
136 if (IsCall)
137 return CS.getCalledValue() == Other.CS.getCalledValue();
138 return Loc == Other.Loc;
139 }
140
141private:
Daniel Berlinf5361132016-10-22 04:15:41 +0000142 union {
Daniel Berlind602e042017-01-25 20:56:19 +0000143 ImmutableCallSite CS;
144 MemoryLocation Loc;
Daniel Berlinf5361132016-10-22 04:15:41 +0000145 };
Daniel Berlindff31de2016-08-02 21:57:52 +0000146};
147}
148
149namespace llvm {
150template <> struct DenseMapInfo<MemoryLocOrCall> {
151 static inline MemoryLocOrCall getEmptyKey() {
152 return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getEmptyKey());
153 }
154 static inline MemoryLocOrCall getTombstoneKey() {
155 return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getTombstoneKey());
156 }
157 static unsigned getHashValue(const MemoryLocOrCall &MLOC) {
158 if (MLOC.IsCall)
159 return hash_combine(MLOC.IsCall,
160 DenseMapInfo<const Value *>::getHashValue(
161 MLOC.getCS().getCalledValue()));
162 return hash_combine(
163 MLOC.IsCall, DenseMapInfo<MemoryLocation>::getHashValue(MLOC.getLoc()));
164 }
165 static bool isEqual(const MemoryLocOrCall &LHS, const MemoryLocOrCall &RHS) {
166 return LHS == RHS;
167 }
168};
Daniel Berlindf101192016-08-03 00:01:46 +0000169
George Burgess IVf7672852016-08-03 19:59:11 +0000170enum class Reorderability { Always, IfNoAlias, Never };
George Burgess IV82e355c2016-08-03 19:39:54 +0000171
172/// This does one-way checks to see if Use could theoretically be hoisted above
173/// MayClobber. This will not check the other way around.
174///
175/// This assumes that, for the purposes of MemorySSA, Use comes directly after
176/// MayClobber, with no potentially clobbering operations in between them.
177/// (Where potentially clobbering ops are memory barriers, aliased stores, etc.)
178static Reorderability getLoadReorderability(const LoadInst *Use,
179 const LoadInst *MayClobber) {
180 bool VolatileUse = Use->isVolatile();
181 bool VolatileClobber = MayClobber->isVolatile();
182 // Volatile operations may never be reordered with other volatile operations.
183 if (VolatileUse && VolatileClobber)
184 return Reorderability::Never;
185
186 // The lang ref allows reordering of volatile and non-volatile operations.
187 // Whether an aliasing nonvolatile load and volatile load can be reordered,
188 // though, is ambiguous. Because it may not be best to exploit this ambiguity,
189 // we only allow volatile/non-volatile reordering if the volatile and
190 // non-volatile operations don't alias.
191 Reorderability Result = VolatileUse || VolatileClobber
192 ? Reorderability::IfNoAlias
193 : Reorderability::Always;
194
195 // If a load is seq_cst, it cannot be moved above other loads. If its ordering
196 // is weaker, it can be moved above other loads. We just need to be sure that
197 // MayClobber isn't an acquire load, because loads can't be moved above
198 // acquire loads.
199 //
200 // Note that this explicitly *does* allow the free reordering of monotonic (or
201 // weaker) loads of the same address.
202 bool SeqCstUse = Use->getOrdering() == AtomicOrdering::SequentiallyConsistent;
203 bool MayClobberIsAcquire = isAtLeastOrStrongerThan(MayClobber->getOrdering(),
204 AtomicOrdering::Acquire);
205 if (SeqCstUse || MayClobberIsAcquire)
206 return Reorderability::Never;
207 return Result;
208}
209
Sebastian Popd57d93c2016-10-12 03:08:40 +0000210static bool instructionClobbersQuery(MemoryDef *MD,
211 const MemoryLocation &UseLoc,
212 const Instruction *UseInst,
213 AliasAnalysis &AA) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000214 Instruction *DefInst = MD->getMemoryInst();
215 assert(DefInst && "Defining instruction not actually an instruction");
Daniel Berlin74603a62017-04-10 18:46:00 +0000216 ImmutableCallSite UseCS(UseInst);
George Burgess IV5f308972016-07-19 01:29:15 +0000217
Daniel Berlindf101192016-08-03 00:01:46 +0000218 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) {
219 // These intrinsics will show up as affecting memory, but they are just
220 // markers.
221 switch (II->getIntrinsicID()) {
222 case Intrinsic::lifetime_start:
Daniel Berlin74603a62017-04-10 18:46:00 +0000223 if (UseCS)
224 return false;
225 return AA.isMustAlias(MemoryLocation(II->getArgOperand(1)), UseLoc);
Daniel Berlindf101192016-08-03 00:01:46 +0000226 case Intrinsic::lifetime_end:
227 case Intrinsic::invariant_start:
228 case Intrinsic::invariant_end:
229 case Intrinsic::assume:
230 return false;
231 default:
232 break;
233 }
234 }
235
Daniel Berlindff31de2016-08-02 21:57:52 +0000236 if (UseCS) {
237 ModRefInfo I = AA.getModRefInfo(DefInst, UseCS);
238 return I != MRI_NoModRef;
239 }
George Burgess IV82e355c2016-08-03 19:39:54 +0000240
241 if (auto *DefLoad = dyn_cast<LoadInst>(DefInst)) {
242 if (auto *UseLoad = dyn_cast<LoadInst>(UseInst)) {
243 switch (getLoadReorderability(UseLoad, DefLoad)) {
244 case Reorderability::Always:
245 return false;
246 case Reorderability::Never:
247 return true;
248 case Reorderability::IfNoAlias:
249 return !AA.isNoAlias(UseLoc, MemoryLocation::get(DefLoad));
250 }
251 }
252 }
253
Daniel Berlindff31de2016-08-02 21:57:52 +0000254 return AA.getModRefInfo(DefInst, UseLoc) & MRI_Mod;
255}
256
Sebastian Pop5068d7a2016-10-13 03:23:33 +0000257static bool instructionClobbersQuery(MemoryDef *MD, const MemoryUseOrDef *MU,
258 const MemoryLocOrCall &UseMLOC,
259 AliasAnalysis &AA) {
260 // FIXME: This is a temporary hack to allow a single instructionClobbersQuery
261 // to exist while MemoryLocOrCall is pushed through places.
262 if (UseMLOC.IsCall)
263 return instructionClobbersQuery(MD, MemoryLocation(), MU->getMemoryInst(),
264 AA);
265 return instructionClobbersQuery(MD, UseMLOC.getLoc(), MU->getMemoryInst(),
266 AA);
267}
268
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000269// Return true when MD may alias MU, return false otherwise.
Daniel Berlindcb004f2017-03-02 23:06:46 +0000270bool MemorySSAUtil::defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU,
271 AliasAnalysis &AA) {
Sebastian Pop5068d7a2016-10-13 03:23:33 +0000272 return instructionClobbersQuery(MD, MU, MemoryLocOrCall(MU), AA);
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000273}
274}
275
276namespace {
277struct UpwardsMemoryQuery {
278 // True if our original query started off as a call
279 bool IsCall;
280 // The pointer location we started the query with. This will be empty if
281 // IsCall is true.
282 MemoryLocation StartingLoc;
283 // This is the instruction we were querying about.
284 const Instruction *Inst;
285 // The MemoryAccess we actually got called with, used to test local domination
286 const MemoryAccess *OriginalAccess;
287
288 UpwardsMemoryQuery()
289 : IsCall(false), Inst(nullptr), OriginalAccess(nullptr) {}
290
291 UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access)
292 : IsCall(ImmutableCallSite(Inst)), Inst(Inst), OriginalAccess(Access) {
293 if (!IsCall)
294 StartingLoc = MemoryLocation::get(Inst);
295 }
296};
297
298static bool lifetimeEndsAt(MemoryDef *MD, const MemoryLocation &Loc,
299 AliasAnalysis &AA) {
300 Instruction *Inst = MD->getMemoryInst();
301 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
302 switch (II->getIntrinsicID()) {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000303 case Intrinsic::lifetime_end:
304 return AA.isMustAlias(MemoryLocation(II->getArgOperand(1)), Loc);
305 default:
306 return false;
307 }
308 }
309 return false;
310}
311
312static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysis &AA,
313 const Instruction *I) {
314 // If the memory can't be changed, then loads of the memory can't be
315 // clobbered.
316 //
317 // FIXME: We should handle invariant groups, as well. It's a bit harder,
318 // because we need to pay close attention to invariant group barriers.
319 return isa<LoadInst>(I) && (I->getMetadata(LLVMContext::MD_invariant_load) ||
Hal Finkela9d67cf2017-04-09 12:57:50 +0000320 AA.pointsToConstantMemory(cast<LoadInst>(I)->
321 getPointerOperand()));
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000322}
323
George Burgess IV5f308972016-07-19 01:29:15 +0000324/// Verifies that `Start` is clobbered by `ClobberAt`, and that nothing
325/// inbetween `Start` and `ClobberAt` can clobbers `Start`.
326///
327/// This is meant to be as simple and self-contained as possible. Because it
328/// uses no cache, etc., it can be relatively expensive.
329///
330/// \param Start The MemoryAccess that we want to walk from.
331/// \param ClobberAt A clobber for Start.
332/// \param StartLoc The MemoryLocation for Start.
333/// \param MSSA The MemorySSA isntance that Start and ClobberAt belong to.
334/// \param Query The UpwardsMemoryQuery we used for our search.
335/// \param AA The AliasAnalysis we used for our search.
336static void LLVM_ATTRIBUTE_UNUSED
337checkClobberSanity(MemoryAccess *Start, MemoryAccess *ClobberAt,
338 const MemoryLocation &StartLoc, const MemorySSA &MSSA,
339 const UpwardsMemoryQuery &Query, AliasAnalysis &AA) {
340 assert(MSSA.dominates(ClobberAt, Start) && "Clobber doesn't dominate start?");
341
342 if (MSSA.isLiveOnEntryDef(Start)) {
343 assert(MSSA.isLiveOnEntryDef(ClobberAt) &&
344 "liveOnEntry must clobber itself");
345 return;
346 }
347
George Burgess IV5f308972016-07-19 01:29:15 +0000348 bool FoundClobber = false;
349 DenseSet<MemoryAccessPair> VisitedPhis;
350 SmallVector<MemoryAccessPair, 8> Worklist;
351 Worklist.emplace_back(Start, StartLoc);
352 // Walk all paths from Start to ClobberAt, while looking for clobbers. If one
353 // is found, complain.
354 while (!Worklist.empty()) {
355 MemoryAccessPair MAP = Worklist.pop_back_val();
356 // All we care about is that nothing from Start to ClobberAt clobbers Start.
357 // We learn nothing from revisiting nodes.
358 if (!VisitedPhis.insert(MAP).second)
359 continue;
360
361 for (MemoryAccess *MA : def_chain(MAP.first)) {
362 if (MA == ClobberAt) {
363 if (auto *MD = dyn_cast<MemoryDef>(MA)) {
364 // instructionClobbersQuery isn't essentially free, so don't use `|=`,
365 // since it won't let us short-circuit.
366 //
367 // Also, note that this can't be hoisted out of the `Worklist` loop,
368 // since MD may only act as a clobber for 1 of N MemoryLocations.
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000369 FoundClobber =
370 FoundClobber || MSSA.isLiveOnEntryDef(MD) ||
371 instructionClobbersQuery(MD, MAP.second, Query.Inst, AA);
George Burgess IV5f308972016-07-19 01:29:15 +0000372 }
373 break;
374 }
375
376 // We should never hit liveOnEntry, unless it's the clobber.
377 assert(!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?");
378
379 if (auto *MD = dyn_cast<MemoryDef>(MA)) {
380 (void)MD;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000381 assert(!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA) &&
George Burgess IV5f308972016-07-19 01:29:15 +0000382 "Found clobber before reaching ClobberAt!");
383 continue;
384 }
385
386 assert(isa<MemoryPhi>(MA));
387 Worklist.append(upward_defs_begin({MA, MAP.second}), upward_defs_end());
388 }
389 }
390
391 // If ClobberAt is a MemoryPhi, we can assume something above it acted as a
392 // clobber. Otherwise, `ClobberAt` should've acted as a clobber at some point.
393 assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&
394 "ClobberAt never acted as a clobber");
395}
396
397/// Our algorithm for walking (and trying to optimize) clobbers, all wrapped up
398/// in one class.
399class ClobberWalker {
400 /// Save a few bytes by using unsigned instead of size_t.
401 using ListIndex = unsigned;
402
403 /// Represents a span of contiguous MemoryDefs, potentially ending in a
404 /// MemoryPhi.
405 struct DefPath {
406 MemoryLocation Loc;
407 // Note that, because we always walk in reverse, Last will always dominate
408 // First. Also note that First and Last are inclusive.
409 MemoryAccess *First;
410 MemoryAccess *Last;
George Burgess IV5f308972016-07-19 01:29:15 +0000411 Optional<ListIndex> Previous;
412
413 DefPath(const MemoryLocation &Loc, MemoryAccess *First, MemoryAccess *Last,
414 Optional<ListIndex> Previous)
415 : Loc(Loc), First(First), Last(Last), Previous(Previous) {}
416
417 DefPath(const MemoryLocation &Loc, MemoryAccess *Init,
418 Optional<ListIndex> Previous)
419 : DefPath(Loc, Init, Init, Previous) {}
420 };
421
422 const MemorySSA &MSSA;
423 AliasAnalysis &AA;
424 DominatorTree &DT;
George Burgess IV5f308972016-07-19 01:29:15 +0000425 UpwardsMemoryQuery *Query;
George Burgess IV5f308972016-07-19 01:29:15 +0000426
427 // Phi optimization bookkeeping
428 SmallVector<DefPath, 32> Paths;
429 DenseSet<ConstMemoryAccessPair> VisitedPhis;
George Burgess IV5f308972016-07-19 01:29:15 +0000430
George Burgess IV5f308972016-07-19 01:29:15 +0000431 /// Find the nearest def or phi that `From` can legally be optimized to.
Daniel Berlind0420312017-04-01 09:01:12 +0000432 const MemoryAccess *getWalkTarget(const MemoryPhi *From) const {
George Burgess IV5f308972016-07-19 01:29:15 +0000433 assert(From->getNumOperands() && "Phi with no operands?");
434
435 BasicBlock *BB = From->getBlock();
George Burgess IV5f308972016-07-19 01:29:15 +0000436 MemoryAccess *Result = MSSA.getLiveOnEntryDef();
437 DomTreeNode *Node = DT.getNode(BB);
438 while ((Node = Node->getIDom())) {
Daniel Berlin7500c562017-04-01 08:59:45 +0000439 auto *Defs = MSSA.getBlockDefs(Node->getBlock());
440 if (Defs)
Daniel Berlind0420312017-04-01 09:01:12 +0000441 return &*Defs->rbegin();
George Burgess IV5f308972016-07-19 01:29:15 +0000442 }
George Burgess IV5f308972016-07-19 01:29:15 +0000443 return Result;
444 }
445
446 /// Result of calling walkToPhiOrClobber.
447 struct UpwardsWalkResult {
448 /// The "Result" of the walk. Either a clobber, the last thing we walked, or
449 /// both.
450 MemoryAccess *Result;
451 bool IsKnownClobber;
George Burgess IV5f308972016-07-19 01:29:15 +0000452 };
453
454 /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last.
455 /// This will update Desc.Last as it walks. It will (optionally) also stop at
456 /// StopAt.
457 ///
458 /// This does not test for whether StopAt is a clobber
Daniel Berlind0420312017-04-01 09:01:12 +0000459 UpwardsWalkResult
460 walkToPhiOrClobber(DefPath &Desc,
461 const MemoryAccess *StopAt = nullptr) const {
George Burgess IV5f308972016-07-19 01:29:15 +0000462 assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");
463
464 for (MemoryAccess *Current : def_chain(Desc.Last)) {
465 Desc.Last = Current;
466 if (Current == StopAt)
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000467 return {Current, false};
George Burgess IV5f308972016-07-19 01:29:15 +0000468
469 if (auto *MD = dyn_cast<MemoryDef>(Current))
470 if (MSSA.isLiveOnEntryDef(MD) ||
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000471 instructionClobbersQuery(MD, Desc.Loc, Query->Inst, AA))
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000472 return {MD, true};
George Burgess IV5f308972016-07-19 01:29:15 +0000473 }
474
475 assert(isa<MemoryPhi>(Desc.Last) &&
476 "Ended at a non-clobber that's not a phi?");
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000477 return {Desc.Last, false};
George Burgess IV5f308972016-07-19 01:29:15 +0000478 }
479
480 void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches,
481 ListIndex PriorNode) {
482 auto UpwardDefs = make_range(upward_defs_begin({Phi, Paths[PriorNode].Loc}),
483 upward_defs_end());
484 for (const MemoryAccessPair &P : UpwardDefs) {
485 PausedSearches.push_back(Paths.size());
486 Paths.emplace_back(P.second, P.first, PriorNode);
487 }
488 }
489
490 /// Represents a search that terminated after finding a clobber. This clobber
491 /// may or may not be present in the path of defs from LastNode..SearchStart,
492 /// since it may have been retrieved from cache.
493 struct TerminatedPath {
494 MemoryAccess *Clobber;
495 ListIndex LastNode;
496 };
497
498 /// Get an access that keeps us from optimizing to the given phi.
499 ///
500 /// PausedSearches is an array of indices into the Paths array. Its incoming
501 /// value is the indices of searches that stopped at the last phi optimization
502 /// target. It's left in an unspecified state.
503 ///
504 /// If this returns None, NewPaused is a vector of searches that terminated
505 /// at StopWhere. Otherwise, NewPaused is left in an unspecified state.
George Burgess IV14633b52016-08-03 01:22:19 +0000506 Optional<TerminatedPath>
Daniel Berlind0420312017-04-01 09:01:12 +0000507 getBlockingAccess(const MemoryAccess *StopWhere,
George Burgess IV5f308972016-07-19 01:29:15 +0000508 SmallVectorImpl<ListIndex> &PausedSearches,
509 SmallVectorImpl<ListIndex> &NewPaused,
510 SmallVectorImpl<TerminatedPath> &Terminated) {
511 assert(!PausedSearches.empty() && "No searches to continue?");
512
513 // BFS vs DFS really doesn't make a difference here, so just do a DFS with
514 // PausedSearches as our stack.
515 while (!PausedSearches.empty()) {
516 ListIndex PathIndex = PausedSearches.pop_back_val();
517 DefPath &Node = Paths[PathIndex];
518
519 // If we've already visited this path with this MemoryLocation, we don't
520 // need to do so again.
521 //
522 // NOTE: That we just drop these paths on the ground makes caching
523 // behavior sporadic. e.g. given a diamond:
524 // A
525 // B C
526 // D
527 //
528 // ...If we walk D, B, A, C, we'll only cache the result of phi
529 // optimization for A, B, and D; C will be skipped because it dies here.
530 // This arguably isn't the worst thing ever, since:
531 // - We generally query things in a top-down order, so if we got below D
532 // without needing cache entries for {C, MemLoc}, then chances are
533 // that those cache entries would end up ultimately unused.
534 // - We still cache things for A, so C only needs to walk up a bit.
535 // If this behavior becomes problematic, we can fix without a ton of extra
536 // work.
537 if (!VisitedPhis.insert({Node.Last, Node.Loc}).second)
538 continue;
539
540 UpwardsWalkResult Res = walkToPhiOrClobber(Node, /*StopAt=*/StopWhere);
541 if (Res.IsKnownClobber) {
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000542 assert(Res.Result != StopWhere);
George Burgess IV5f308972016-07-19 01:29:15 +0000543 // If this wasn't a cache hit, we hit a clobber when walking. That's a
544 // failure.
George Burgess IV14633b52016-08-03 01:22:19 +0000545 TerminatedPath Term{Res.Result, PathIndex};
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000546 if (!MSSA.dominates(Res.Result, StopWhere))
George Burgess IV14633b52016-08-03 01:22:19 +0000547 return Term;
George Burgess IV5f308972016-07-19 01:29:15 +0000548
549 // Otherwise, it's a valid thing to potentially optimize to.
George Burgess IV14633b52016-08-03 01:22:19 +0000550 Terminated.push_back(Term);
George Burgess IV5f308972016-07-19 01:29:15 +0000551 continue;
552 }
553
554 if (Res.Result == StopWhere) {
555 // We've hit our target. Save this path off for if we want to continue
556 // walking.
557 NewPaused.push_back(PathIndex);
558 continue;
559 }
560
561 assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");
562 addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
563 }
564
565 return None;
566 }
567
568 template <typename T, typename Walker>
569 struct generic_def_path_iterator
570 : public iterator_facade_base<generic_def_path_iterator<T, Walker>,
571 std::forward_iterator_tag, T *> {
572 generic_def_path_iterator() : W(nullptr), N(None) {}
573 generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}
574
575 T &operator*() const { return curNode(); }
576
577 generic_def_path_iterator &operator++() {
578 N = curNode().Previous;
579 return *this;
580 }
581
582 bool operator==(const generic_def_path_iterator &O) const {
583 if (N.hasValue() != O.N.hasValue())
584 return false;
585 return !N.hasValue() || *N == *O.N;
586 }
587
588 private:
589 T &curNode() const { return W->Paths[*N]; }
590
591 Walker *W;
592 Optional<ListIndex> N;
593 };
594
595 using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
596 using const_def_path_iterator =
597 generic_def_path_iterator<const DefPath, const ClobberWalker>;
598
599 iterator_range<def_path_iterator> def_path(ListIndex From) {
600 return make_range(def_path_iterator(this, From), def_path_iterator());
601 }
602
603 iterator_range<const_def_path_iterator> const_def_path(ListIndex From) const {
604 return make_range(const_def_path_iterator(this, From),
605 const_def_path_iterator());
606 }
607
608 struct OptznResult {
609 /// The path that contains our result.
610 TerminatedPath PrimaryClobber;
611 /// The paths that we can legally cache back from, but that aren't
612 /// necessarily the result of the Phi optimization.
613 SmallVector<TerminatedPath, 4> OtherClobbers;
614 };
615
616 ListIndex defPathIndex(const DefPath &N) const {
617 // The assert looks nicer if we don't need to do &N
618 const DefPath *NP = &N;
619 assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
620 "Out of bounds DefPath!");
621 return NP - &Paths.front();
622 }
623
624 /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths
625 /// that act as legal clobbers. Note that this won't return *all* clobbers.
626 ///
627 /// Phi optimization algorithm tl;dr:
628 /// - Find the earliest def/phi, A, we can optimize to
629 /// - Find if all paths from the starting memory access ultimately reach A
630 /// - If not, optimization isn't possible.
631 /// - Otherwise, walk from A to another clobber or phi, A'.
632 /// - If A' is a def, we're done.
633 /// - If A' is a phi, try to optimize it.
634 ///
635 /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path
636 /// terminates when a MemoryAccess that clobbers said MemoryLocation is found.
637 OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start,
638 const MemoryLocation &Loc) {
639 assert(Paths.empty() && VisitedPhis.empty() &&
640 "Reset the optimization state.");
641
642 Paths.emplace_back(Loc, Start, Phi, None);
643 // Stores how many "valid" optimization nodes we had prior to calling
644 // addSearches/getBlockingAccess. Necessary for caching if we had a blocker.
645 auto PriorPathsSize = Paths.size();
646
647 SmallVector<ListIndex, 16> PausedSearches;
648 SmallVector<ListIndex, 8> NewPaused;
649 SmallVector<TerminatedPath, 4> TerminatedPaths;
650
651 addSearches(Phi, PausedSearches, 0);
652
653 // Moves the TerminatedPath with the "most dominated" Clobber to the end of
654 // Paths.
655 auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
656 assert(!Paths.empty() && "Need a path to move");
George Burgess IV5f308972016-07-19 01:29:15 +0000657 auto Dom = Paths.begin();
658 for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I)
659 if (!MSSA.dominates(I->Clobber, Dom->Clobber))
660 Dom = I;
661 auto Last = Paths.end() - 1;
662 if (Last != Dom)
663 std::iter_swap(Last, Dom);
664 };
665
666 MemoryPhi *Current = Phi;
667 while (1) {
668 assert(!MSSA.isLiveOnEntryDef(Current) &&
669 "liveOnEntry wasn't treated as a clobber?");
670
Daniel Berlind0420312017-04-01 09:01:12 +0000671 const auto *Target = getWalkTarget(Current);
George Burgess IV5f308972016-07-19 01:29:15 +0000672 // If a TerminatedPath doesn't dominate Target, then it wasn't a legal
673 // optimization for the prior phi.
674 assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {
675 return MSSA.dominates(P.Clobber, Target);
676 }));
677
678 // FIXME: This is broken, because the Blocker may be reported to be
679 // liveOnEntry, and we'll happily wait for that to disappear (read: never)
George Burgess IV7f414b92016-08-22 23:40:01 +0000680 // For the moment, this is fine, since we do nothing with blocker info.
George Burgess IV14633b52016-08-03 01:22:19 +0000681 if (Optional<TerminatedPath> Blocker = getBlockingAccess(
George Burgess IV5f308972016-07-19 01:29:15 +0000682 Target, PausedSearches, NewPaused, TerminatedPaths)) {
George Burgess IV5f308972016-07-19 01:29:15 +0000683
684 // Find the node we started at. We can't search based on N->Last, since
685 // we may have gone around a loop with a different MemoryLocation.
George Burgess IV14633b52016-08-03 01:22:19 +0000686 auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) {
George Burgess IV5f308972016-07-19 01:29:15 +0000687 return defPathIndex(N) < PriorPathsSize;
688 });
689 assert(Iter != def_path_iterator());
690
691 DefPath &CurNode = *Iter;
692 assert(CurNode.Last == Current);
George Burgess IV5f308972016-07-19 01:29:15 +0000693
694 // Two things:
695 // A. We can't reliably cache all of NewPaused back. Consider a case
696 // where we have two paths in NewPaused; one of which can't optimize
697 // above this phi, whereas the other can. If we cache the second path
698 // back, we'll end up with suboptimal cache entries. We can handle
699 // cases like this a bit better when we either try to find all
700 // clobbers that block phi optimization, or when our cache starts
701 // supporting unfinished searches.
702 // B. We can't reliably cache TerminatedPaths back here without doing
703 // extra checks; consider a case like:
704 // T
705 // / \
706 // D C
707 // \ /
708 // S
709 // Where T is our target, C is a node with a clobber on it, D is a
710 // diamond (with a clobber *only* on the left or right node, N), and
711 // S is our start. Say we walk to D, through the node opposite N
712 // (read: ignoring the clobber), and see a cache entry in the top
713 // node of D. That cache entry gets put into TerminatedPaths. We then
714 // walk up to C (N is later in our worklist), find the clobber, and
715 // quit. If we append TerminatedPaths to OtherClobbers, we'll cache
716 // the bottom part of D to the cached clobber, ignoring the clobber
717 // in N. Again, this problem goes away if we start tracking all
718 // blockers for a given phi optimization.
719 TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
720 return {Result, {}};
721 }
722
723 // If there's nothing left to search, then all paths led to valid clobbers
724 // that we got from our cache; pick the nearest to the start, and allow
725 // the rest to be cached back.
726 if (NewPaused.empty()) {
727 MoveDominatedPathToEnd(TerminatedPaths);
728 TerminatedPath Result = TerminatedPaths.pop_back_val();
729 return {Result, std::move(TerminatedPaths)};
730 }
731
732 MemoryAccess *DefChainEnd = nullptr;
733 SmallVector<TerminatedPath, 4> Clobbers;
734 for (ListIndex Paused : NewPaused) {
735 UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
736 if (WR.IsKnownClobber)
737 Clobbers.push_back({WR.Result, Paused});
738 else
739 // Micro-opt: If we hit the end of the chain, save it.
740 DefChainEnd = WR.Result;
741 }
742
743 if (!TerminatedPaths.empty()) {
744 // If we couldn't find the dominating phi/liveOnEntry in the above loop,
745 // do it now.
746 if (!DefChainEnd)
Daniel Berlind0420312017-04-01 09:01:12 +0000747 for (auto *MA : def_chain(const_cast<MemoryAccess *>(Target)))
George Burgess IV5f308972016-07-19 01:29:15 +0000748 DefChainEnd = MA;
749
750 // If any of the terminated paths don't dominate the phi we'll try to
751 // optimize, we need to figure out what they are and quit.
752 const BasicBlock *ChainBB = DefChainEnd->getBlock();
753 for (const TerminatedPath &TP : TerminatedPaths) {
754 // Because we know that DefChainEnd is as "high" as we can go, we
755 // don't need local dominance checks; BB dominance is sufficient.
756 if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
757 Clobbers.push_back(TP);
758 }
759 }
760
761 // If we have clobbers in the def chain, find the one closest to Current
762 // and quit.
763 if (!Clobbers.empty()) {
764 MoveDominatedPathToEnd(Clobbers);
765 TerminatedPath Result = Clobbers.pop_back_val();
766 return {Result, std::move(Clobbers)};
767 }
768
769 assert(all_of(NewPaused,
770 [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
771
772 // Because liveOnEntry is a clobber, this must be a phi.
773 auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
774
775 PriorPathsSize = Paths.size();
776 PausedSearches.clear();
777 for (ListIndex I : NewPaused)
778 addSearches(DefChainPhi, PausedSearches, I);
779 NewPaused.clear();
780
781 Current = DefChainPhi;
782 }
783 }
784
George Burgess IV5f308972016-07-19 01:29:15 +0000785 void verifyOptResult(const OptznResult &R) const {
786 assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
787 return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
788 }));
789 }
790
791 void resetPhiOptznState() {
792 Paths.clear();
793 VisitedPhis.clear();
794 }
795
796public:
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000797 ClobberWalker(const MemorySSA &MSSA, AliasAnalysis &AA, DominatorTree &DT)
798 : MSSA(MSSA), AA(AA), DT(DT) {}
George Burgess IV5f308972016-07-19 01:29:15 +0000799
Daniel Berlin7500c562017-04-01 08:59:45 +0000800 void reset() {}
George Burgess IV5f308972016-07-19 01:29:15 +0000801
802 /// Finds the nearest clobber for the given query, optimizing phis if
803 /// possible.
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000804 MemoryAccess *findClobber(MemoryAccess *Start, UpwardsMemoryQuery &Q) {
George Burgess IV5f308972016-07-19 01:29:15 +0000805 Query = &Q;
806
807 MemoryAccess *Current = Start;
808 // This walker pretends uses don't exist. If we're handed one, silently grab
809 // its def. (This has the nice side-effect of ensuring we never cache uses)
810 if (auto *MU = dyn_cast<MemoryUse>(Start))
811 Current = MU->getDefiningAccess();
812
813 DefPath FirstDesc(Q.StartingLoc, Current, Current, None);
814 // Fast path for the overly-common case (no crazy phi optimization
815 // necessary)
816 UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
George Burgess IV93ea19b2016-07-24 07:03:49 +0000817 MemoryAccess *Result;
George Burgess IV5f308972016-07-19 01:29:15 +0000818 if (WalkResult.IsKnownClobber) {
George Burgess IV93ea19b2016-07-24 07:03:49 +0000819 Result = WalkResult.Result;
820 } else {
821 OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
822 Current, Q.StartingLoc);
823 verifyOptResult(OptRes);
George Burgess IV93ea19b2016-07-24 07:03:49 +0000824 resetPhiOptznState();
825 Result = OptRes.PrimaryClobber.Clobber;
George Burgess IV5f308972016-07-19 01:29:15 +0000826 }
827
George Burgess IV5f308972016-07-19 01:29:15 +0000828#ifdef EXPENSIVE_CHECKS
George Burgess IV93ea19b2016-07-24 07:03:49 +0000829 checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, AA);
George Burgess IV5f308972016-07-19 01:29:15 +0000830#endif
George Burgess IV93ea19b2016-07-24 07:03:49 +0000831 return Result;
George Burgess IV5f308972016-07-19 01:29:15 +0000832 }
Geoff Berrycdf53332016-08-08 17:52:01 +0000833
834 void verify(const MemorySSA *MSSA) { assert(MSSA == &this->MSSA); }
George Burgess IV5f308972016-07-19 01:29:15 +0000835};
836
837struct RenamePassData {
838 DomTreeNode *DTN;
839 DomTreeNode::const_iterator ChildIt;
840 MemoryAccess *IncomingVal;
841
842 RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
843 MemoryAccess *M)
844 : DTN(D), ChildIt(It), IncomingVal(M) {}
845 void swap(RenamePassData &RHS) {
846 std::swap(DTN, RHS.DTN);
847 std::swap(ChildIt, RHS.ChildIt);
848 std::swap(IncomingVal, RHS.IncomingVal);
849 }
850};
851} // anonymous namespace
852
853namespace llvm {
Daniel Berlind952cea2017-04-07 01:28:36 +0000854/// \brief A MemorySSAWalker that does AA walks to disambiguate accesses. It no
855/// longer does caching on its own,
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000856/// but the name has been retained for the moment.
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000857class MemorySSA::CachingWalker final : public MemorySSAWalker {
George Burgess IV5f308972016-07-19 01:29:15 +0000858 ClobberWalker Walker;
859 bool AutoResetWalker;
860
861 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *, UpwardsMemoryQuery &);
862 void verifyRemoved(MemoryAccess *);
863
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000864public:
865 CachingWalker(MemorySSA *, AliasAnalysis *, DominatorTree *);
866 ~CachingWalker() override;
867
George Burgess IV400ae402016-07-20 19:51:34 +0000868 using MemorySSAWalker::getClobberingMemoryAccess;
869 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) override;
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000870 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
George Burgess IV013fd732016-10-28 19:22:46 +0000871 const MemoryLocation &) override;
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000872 void invalidateInfo(MemoryAccess *) override;
873
George Burgess IV5f308972016-07-19 01:29:15 +0000874 /// Whether we call resetClobberWalker() after each time we *actually* walk to
875 /// answer a clobber query.
876 void setAutoResetWalker(bool AutoReset) { AutoResetWalker = AutoReset; }
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000877
Daniel Berlin7500c562017-04-01 08:59:45 +0000878 /// Drop the walker's persistent data structures.
George Burgess IV5f308972016-07-19 01:29:15 +0000879 void resetClobberWalker() { Walker.reset(); }
Geoff Berrycdf53332016-08-08 17:52:01 +0000880
881 void verify(const MemorySSA *MSSA) override {
882 MemorySSAWalker::verify(MSSA);
883 Walker.verify(MSSA);
884 }
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000885};
George Burgess IVe1100f52016-02-02 22:46:49 +0000886
Daniel Berlin78cbd282017-02-20 22:26:03 +0000887void MemorySSA::renameSuccessorPhis(BasicBlock *BB, MemoryAccess *IncomingVal,
888 bool RenameAllUses) {
George Burgess IVe1100f52016-02-02 22:46:49 +0000889 // Pass through values to our successors
890 for (const BasicBlock *S : successors(BB)) {
891 auto It = PerBlockAccesses.find(S);
892 // Rename the phi nodes in our successor block
893 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
894 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +0000895 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +0000896 auto *Phi = cast<MemoryPhi>(&Accesses->front());
Daniel Berlin78cbd282017-02-20 22:26:03 +0000897 if (RenameAllUses) {
898 int PhiIndex = Phi->getBasicBlockIndex(BB);
899 assert(PhiIndex != -1 && "Incomplete phi during partial rename");
900 Phi->setIncomingValue(PhiIndex, IncomingVal);
901 } else
902 Phi->addIncoming(IncomingVal, BB);
George Burgess IVe1100f52016-02-02 22:46:49 +0000903 }
Daniel Berlin78cbd282017-02-20 22:26:03 +0000904}
George Burgess IVe1100f52016-02-02 22:46:49 +0000905
Daniel Berlin78cbd282017-02-20 22:26:03 +0000906/// \brief Rename a single basic block into MemorySSA form.
907/// Uses the standard SSA renaming algorithm.
908/// \returns The new incoming value.
909MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB, MemoryAccess *IncomingVal,
910 bool RenameAllUses) {
911 auto It = PerBlockAccesses.find(BB);
912 // Skip most processing if the list is empty.
913 if (It != PerBlockAccesses.end()) {
914 AccessList *Accesses = It->second.get();
915 for (MemoryAccess &L : *Accesses) {
916 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&L)) {
917 if (MUD->getDefiningAccess() == nullptr || RenameAllUses)
918 MUD->setDefiningAccess(IncomingVal);
919 if (isa<MemoryDef>(&L))
920 IncomingVal = &L;
921 } else {
922 IncomingVal = &L;
923 }
924 }
925 }
George Burgess IVe1100f52016-02-02 22:46:49 +0000926 return IncomingVal;
927}
928
929/// \brief This is the standard SSA renaming algorithm.
930///
931/// We walk the dominator tree in preorder, renaming accesses, and then filling
932/// in phi nodes in our successors.
933void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
Daniel Berlin78cbd282017-02-20 22:26:03 +0000934 SmallPtrSetImpl<BasicBlock *> &Visited,
935 bool SkipVisited, bool RenameAllUses) {
George Burgess IVe1100f52016-02-02 22:46:49 +0000936 SmallVector<RenamePassData, 32> WorkStack;
Daniel Berlin78cbd282017-02-20 22:26:03 +0000937 // Skip everything if we already renamed this block and we are skipping.
938 // Note: You can't sink this into the if, because we need it to occur
939 // regardless of whether we skip blocks or not.
940 bool AlreadyVisited = !Visited.insert(Root->getBlock()).second;
941 if (SkipVisited && AlreadyVisited)
942 return;
943
944 IncomingVal = renameBlock(Root->getBlock(), IncomingVal, RenameAllUses);
945 renameSuccessorPhis(Root->getBlock(), IncomingVal, RenameAllUses);
George Burgess IVe1100f52016-02-02 22:46:49 +0000946 WorkStack.push_back({Root, Root->begin(), IncomingVal});
George Burgess IVe1100f52016-02-02 22:46:49 +0000947
948 while (!WorkStack.empty()) {
949 DomTreeNode *Node = WorkStack.back().DTN;
950 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
951 IncomingVal = WorkStack.back().IncomingVal;
952
953 if (ChildIt == Node->end()) {
954 WorkStack.pop_back();
955 } else {
956 DomTreeNode *Child = *ChildIt;
957 ++WorkStack.back().ChildIt;
958 BasicBlock *BB = Child->getBlock();
Daniel Berlin78cbd282017-02-20 22:26:03 +0000959 // Note: You can't sink this into the if, because we need it to occur
960 // regardless of whether we skip blocks or not.
961 AlreadyVisited = !Visited.insert(BB).second;
962 if (SkipVisited && AlreadyVisited) {
963 // We already visited this during our renaming, which can happen when
964 // being asked to rename multiple blocks. Figure out the incoming val,
965 // which is the last def.
966 // Incoming value can only change if there is a block def, and in that
967 // case, it's the last block def in the list.
968 if (auto *BlockDefs = getWritableBlockDefs(BB))
969 IncomingVal = &*BlockDefs->rbegin();
970 } else
971 IncomingVal = renameBlock(BB, IncomingVal, RenameAllUses);
972 renameSuccessorPhis(BB, IncomingVal, RenameAllUses);
George Burgess IVe1100f52016-02-02 22:46:49 +0000973 WorkStack.push_back({Child, Child->begin(), IncomingVal});
974 }
975 }
976}
977
George Burgess IVa362b092016-07-06 00:28:43 +0000978/// \brief This handles unreachable block accesses by deleting phi nodes in
George Burgess IVe1100f52016-02-02 22:46:49 +0000979/// unreachable blocks, and marking all other unreachable MemoryAccess's as
980/// being uses of the live on entry definition.
981void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
982 assert(!DT->isReachableFromEntry(BB) &&
983 "Reachable block found while handling unreachable blocks");
984
Daniel Berlinfc7e6512016-07-06 05:32:05 +0000985 // Make sure phi nodes in our reachable successors end up with a
986 // LiveOnEntryDef for our incoming edge, even though our block is forward
987 // unreachable. We could just disconnect these blocks from the CFG fully,
988 // but we do not right now.
989 for (const BasicBlock *S : successors(BB)) {
990 if (!DT->isReachableFromEntry(S))
991 continue;
992 auto It = PerBlockAccesses.find(S);
993 // Rename the phi nodes in our successor block
994 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
995 continue;
996 AccessList *Accesses = It->second.get();
997 auto *Phi = cast<MemoryPhi>(&Accesses->front());
998 Phi->addIncoming(LiveOnEntryDef.get(), BB);
999 }
1000
George Burgess IVe1100f52016-02-02 22:46:49 +00001001 auto It = PerBlockAccesses.find(BB);
1002 if (It == PerBlockAccesses.end())
1003 return;
1004
1005 auto &Accesses = It->second;
1006 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1007 auto Next = std::next(AI);
1008 // If we have a phi, just remove it. We are going to replace all
1009 // users with live on entry.
1010 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1011 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1012 else
1013 Accesses->erase(AI);
1014 AI = Next;
1015 }
1016}
1017
Geoff Berryb96d3b22016-06-01 21:30:40 +00001018MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
1019 : AA(AA), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
Daniel Berlincd2deac2016-10-20 20:13:45 +00001020 NextID(INVALID_MEMORYACCESS_ID) {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001021 buildMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001022}
1023
George Burgess IVe1100f52016-02-02 22:46:49 +00001024MemorySSA::~MemorySSA() {
1025 // Drop all our references
1026 for (const auto &Pair : PerBlockAccesses)
1027 for (MemoryAccess &MA : *Pair.second)
1028 MA.dropAllReferences();
1029}
1030
Daniel Berlin14300262016-06-21 18:39:20 +00001031MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001032 auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
1033
1034 if (Res.second)
Daniel Berlinada263d2016-06-20 20:21:33 +00001035 Res.first->second = make_unique<AccessList>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001036 return Res.first->second.get();
1037}
Daniel Berlind602e042017-01-25 20:56:19 +00001038MemorySSA::DefsList *MemorySSA::getOrCreateDefsList(const BasicBlock *BB) {
1039 auto Res = PerBlockDefs.insert(std::make_pair(BB, nullptr));
1040
1041 if (Res.second)
1042 Res.first->second = make_unique<DefsList>();
1043 return Res.first->second.get();
1044}
George Burgess IVe1100f52016-02-02 22:46:49 +00001045
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001046/// This class is a batch walker of all MemoryUse's in the program, and points
1047/// their defining access at the thing that actually clobbers them. Because it
1048/// is a batch walker that touches everything, it does not operate like the
1049/// other walkers. This walker is basically performing a top-down SSA renaming
1050/// pass, where the version stack is used as the cache. This enables it to be
1051/// significantly more time and memory efficient than using the regular walker,
1052/// which is walking bottom-up.
1053class MemorySSA::OptimizeUses {
1054public:
1055 OptimizeUses(MemorySSA *MSSA, MemorySSAWalker *Walker, AliasAnalysis *AA,
1056 DominatorTree *DT)
1057 : MSSA(MSSA), Walker(Walker), AA(AA), DT(DT) {
1058 Walker = MSSA->getWalker();
1059 }
1060
1061 void optimizeUses();
1062
1063private:
1064 /// This represents where a given memorylocation is in the stack.
1065 struct MemlocStackInfo {
1066 // This essentially is keeping track of versions of the stack. Whenever
1067 // the stack changes due to pushes or pops, these versions increase.
1068 unsigned long StackEpoch;
1069 unsigned long PopEpoch;
1070 // This is the lower bound of places on the stack to check. It is equal to
1071 // the place the last stack walk ended.
1072 // Note: Correctness depends on this being initialized to 0, which densemap
1073 // does
1074 unsigned long LowerBound;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001075 const BasicBlock *LowerBoundBlock;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001076 // This is where the last walk for this memory location ended.
1077 unsigned long LastKill;
1078 bool LastKillValid;
1079 };
1080 void optimizeUsesInBlock(const BasicBlock *, unsigned long &, unsigned long &,
1081 SmallVectorImpl<MemoryAccess *> &,
1082 DenseMap<MemoryLocOrCall, MemlocStackInfo> &);
1083 MemorySSA *MSSA;
1084 MemorySSAWalker *Walker;
1085 AliasAnalysis *AA;
1086 DominatorTree *DT;
1087};
1088
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001089/// Optimize the uses in a given block This is basically the SSA renaming
1090/// algorithm, with one caveat: We are able to use a single stack for all
1091/// MemoryUses. This is because the set of *possible* reaching MemoryDefs is
1092/// the same for every MemoryUse. The *actual* clobbering MemoryDef is just
1093/// going to be some position in that stack of possible ones.
1094///
1095/// We track the stack positions that each MemoryLocation needs
1096/// to check, and last ended at. This is because we only want to check the
1097/// things that changed since last time. The same MemoryLocation should
1098/// get clobbered by the same store (getModRefInfo does not use invariantness or
1099/// things like this, and if they start, we can modify MemoryLocOrCall to
1100/// include relevant data)
1101void MemorySSA::OptimizeUses::optimizeUsesInBlock(
1102 const BasicBlock *BB, unsigned long &StackEpoch, unsigned long &PopEpoch,
1103 SmallVectorImpl<MemoryAccess *> &VersionStack,
1104 DenseMap<MemoryLocOrCall, MemlocStackInfo> &LocStackInfo) {
1105
1106 /// If no accesses, nothing to do.
1107 MemorySSA::AccessList *Accesses = MSSA->getWritableBlockAccesses(BB);
1108 if (Accesses == nullptr)
1109 return;
1110
1111 // Pop everything that doesn't dominate the current block off the stack,
1112 // increment the PopEpoch to account for this.
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001113 while (true) {
1114 assert(
1115 !VersionStack.empty() &&
1116 "Version stack should have liveOnEntry sentinel dominating everything");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001117 BasicBlock *BackBlock = VersionStack.back()->getBlock();
1118 if (DT->dominates(BackBlock, BB))
1119 break;
1120 while (VersionStack.back()->getBlock() == BackBlock)
1121 VersionStack.pop_back();
1122 ++PopEpoch;
1123 }
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001124
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001125 for (MemoryAccess &MA : *Accesses) {
1126 auto *MU = dyn_cast<MemoryUse>(&MA);
1127 if (!MU) {
1128 VersionStack.push_back(&MA);
1129 ++StackEpoch;
1130 continue;
1131 }
1132
George Burgess IV024f3d22016-08-03 19:57:02 +00001133 if (isUseTriviallyOptimizableToLiveOnEntry(*AA, MU->getMemoryInst())) {
Daniel Berlincd2deac2016-10-20 20:13:45 +00001134 MU->setDefiningAccess(MSSA->getLiveOnEntryDef(), true);
George Burgess IV024f3d22016-08-03 19:57:02 +00001135 continue;
1136 }
1137
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001138 MemoryLocOrCall UseMLOC(MU);
1139 auto &LocInfo = LocStackInfo[UseMLOC];
Daniel Berlin26fcea92016-08-02 20:02:21 +00001140 // If the pop epoch changed, it means we've removed stuff from top of
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001141 // stack due to changing blocks. We may have to reset the lower bound or
1142 // last kill info.
1143 if (LocInfo.PopEpoch != PopEpoch) {
1144 LocInfo.PopEpoch = PopEpoch;
1145 LocInfo.StackEpoch = StackEpoch;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001146 // If the lower bound was in something that no longer dominates us, we
1147 // have to reset it.
1148 // We can't simply track stack size, because the stack may have had
1149 // pushes/pops in the meantime.
1150 // XXX: This is non-optimal, but only is slower cases with heavily
1151 // branching dominator trees. To get the optimal number of queries would
1152 // be to make lowerbound and lastkill a per-loc stack, and pop it until
1153 // the top of that stack dominates us. This does not seem worth it ATM.
1154 // A much cheaper optimization would be to always explore the deepest
1155 // branch of the dominator tree first. This will guarantee this resets on
1156 // the smallest set of blocks.
1157 if (LocInfo.LowerBoundBlock && LocInfo.LowerBoundBlock != BB &&
Daniel Berlin1e98c042016-09-26 17:22:54 +00001158 !DT->dominates(LocInfo.LowerBoundBlock, BB)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001159 // Reset the lower bound of things to check.
1160 // TODO: Some day we should be able to reset to last kill, rather than
1161 // 0.
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001162 LocInfo.LowerBound = 0;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001163 LocInfo.LowerBoundBlock = VersionStack[0]->getBlock();
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001164 LocInfo.LastKillValid = false;
1165 }
1166 } else if (LocInfo.StackEpoch != StackEpoch) {
1167 // If all that has changed is the StackEpoch, we only have to check the
1168 // new things on the stack, because we've checked everything before. In
1169 // this case, the lower bound of things to check remains the same.
1170 LocInfo.PopEpoch = PopEpoch;
1171 LocInfo.StackEpoch = StackEpoch;
1172 }
1173 if (!LocInfo.LastKillValid) {
1174 LocInfo.LastKill = VersionStack.size() - 1;
1175 LocInfo.LastKillValid = true;
1176 }
1177
1178 // At this point, we should have corrected last kill and LowerBound to be
1179 // in bounds.
1180 assert(LocInfo.LowerBound < VersionStack.size() &&
1181 "Lower bound out of range");
1182 assert(LocInfo.LastKill < VersionStack.size() &&
1183 "Last kill info out of range");
1184 // In any case, the new upper bound is the top of the stack.
1185 unsigned long UpperBound = VersionStack.size() - 1;
1186
1187 if (UpperBound - LocInfo.LowerBound > MaxCheckLimit) {
Daniel Berlin26fcea92016-08-02 20:02:21 +00001188 DEBUG(dbgs() << "MemorySSA skipping optimization of " << *MU << " ("
1189 << *(MU->getMemoryInst()) << ")"
1190 << " because there are " << UpperBound - LocInfo.LowerBound
1191 << " stores to disambiguate\n");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001192 // Because we did not walk, LastKill is no longer valid, as this may
1193 // have been a kill.
1194 LocInfo.LastKillValid = false;
1195 continue;
1196 }
1197 bool FoundClobberResult = false;
1198 while (UpperBound > LocInfo.LowerBound) {
1199 if (isa<MemoryPhi>(VersionStack[UpperBound])) {
1200 // For phis, use the walker, see where we ended up, go there
1201 Instruction *UseInst = MU->getMemoryInst();
1202 MemoryAccess *Result = Walker->getClobberingMemoryAccess(UseInst);
1203 // We are guaranteed to find it or something is wrong
1204 while (VersionStack[UpperBound] != Result) {
1205 assert(UpperBound != 0);
1206 --UpperBound;
1207 }
1208 FoundClobberResult = true;
1209 break;
1210 }
1211
1212 MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]);
Daniel Berlindf101192016-08-03 00:01:46 +00001213 // If the lifetime of the pointer ends at this instruction, it's live on
1214 // entry.
1215 if (!UseMLOC.IsCall && lifetimeEndsAt(MD, UseMLOC.getLoc(), *AA)) {
1216 // Reset UpperBound to liveOnEntryDef's place in the stack
1217 UpperBound = 0;
1218 FoundClobberResult = true;
1219 break;
1220 }
Daniel Berlindff31de2016-08-02 21:57:52 +00001221 if (instructionClobbersQuery(MD, MU, UseMLOC, *AA)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001222 FoundClobberResult = true;
1223 break;
1224 }
1225 --UpperBound;
1226 }
1227 // At the end of this loop, UpperBound is either a clobber, or lower bound
1228 // PHI walking may cause it to be < LowerBound, and in fact, < LastKill.
1229 if (FoundClobberResult || UpperBound < LocInfo.LastKill) {
Daniel Berlincd2deac2016-10-20 20:13:45 +00001230 MU->setDefiningAccess(VersionStack[UpperBound], true);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001231 // We were last killed now by where we got to
1232 LocInfo.LastKill = UpperBound;
1233 } else {
1234 // Otherwise, we checked all the new ones, and now we know we can get to
1235 // LastKill.
Daniel Berlincd2deac2016-10-20 20:13:45 +00001236 MU->setDefiningAccess(VersionStack[LocInfo.LastKill], true);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001237 }
1238 LocInfo.LowerBound = VersionStack.size() - 1;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001239 LocInfo.LowerBoundBlock = BB;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001240 }
1241}
1242
1243/// Optimize uses to point to their actual clobbering definitions.
1244void MemorySSA::OptimizeUses::optimizeUses() {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001245 SmallVector<MemoryAccess *, 16> VersionStack;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001246 DenseMap<MemoryLocOrCall, MemlocStackInfo> LocStackInfo;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001247 VersionStack.push_back(MSSA->getLiveOnEntryDef());
1248
1249 unsigned long StackEpoch = 1;
1250 unsigned long PopEpoch = 1;
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001251 // We perform a non-recursive top-down dominator tree walk.
Daniel Berlin7ac3d742016-08-05 22:09:14 +00001252 for (const auto *DomNode : depth_first(DT->getRootNode()))
1253 optimizeUsesInBlock(DomNode->getBlock(), StackEpoch, PopEpoch, VersionStack,
1254 LocStackInfo);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001255}
1256
Daniel Berlin3d512a22016-08-22 19:14:30 +00001257void MemorySSA::placePHINodes(
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001258 const SmallPtrSetImpl<BasicBlock *> &DefiningBlocks,
1259 const DenseMap<const BasicBlock *, unsigned int> &BBNumbers) {
Daniel Berlin3d512a22016-08-22 19:14:30 +00001260 // Determine where our MemoryPhi's should go
1261 ForwardIDFCalculator IDFs(*DT);
1262 IDFs.setDefiningBlocks(DefiningBlocks);
Daniel Berlin3d512a22016-08-22 19:14:30 +00001263 SmallVector<BasicBlock *, 32> IDFBlocks;
1264 IDFs.calculate(IDFBlocks);
1265
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001266 std::sort(IDFBlocks.begin(), IDFBlocks.end(),
1267 [&BBNumbers](const BasicBlock *A, const BasicBlock *B) {
1268 return BBNumbers.lookup(A) < BBNumbers.lookup(B);
1269 });
1270
Daniel Berlin3d512a22016-08-22 19:14:30 +00001271 // Now place MemoryPhi nodes.
Daniel Berlind602e042017-01-25 20:56:19 +00001272 for (auto &BB : IDFBlocks)
1273 createMemoryPhi(BB);
Daniel Berlin3d512a22016-08-22 19:14:30 +00001274}
1275
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001276void MemorySSA::buildMemorySSA() {
George Burgess IVe1100f52016-02-02 22:46:49 +00001277 // We create an access to represent "live on entry", for things like
1278 // arguments or users of globals, where the memory they use is defined before
1279 // the beginning of the function. We do not actually insert it into the IR.
1280 // We do not define a live on exit for the immediate uses, and thus our
1281 // semantics do *not* imply that something with no immediate uses can simply
1282 // be removed.
1283 BasicBlock &StartingPoint = F.getEntryBlock();
1284 LiveOnEntryDef = make_unique<MemoryDef>(F.getContext(), nullptr, nullptr,
1285 &StartingPoint, NextID++);
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001286 DenseMap<const BasicBlock *, unsigned int> BBNumbers;
1287 unsigned NextBBNum = 0;
George Burgess IVe1100f52016-02-02 22:46:49 +00001288
1289 // We maintain lists of memory accesses per-block, trading memory for time. We
1290 // could just look up the memory access for every possible instruction in the
1291 // stream.
1292 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
George Burgess IVe1100f52016-02-02 22:46:49 +00001293 // Go through each block, figure out where defs occur, and chain together all
1294 // the accesses.
1295 for (BasicBlock &B : F) {
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001296 BBNumbers[&B] = NextBBNum++;
Daniel Berlin7898ca62016-02-07 01:52:15 +00001297 bool InsertIntoDef = false;
Daniel Berlinada263d2016-06-20 20:21:33 +00001298 AccessList *Accesses = nullptr;
Daniel Berlind602e042017-01-25 20:56:19 +00001299 DefsList *Defs = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +00001300 for (Instruction &I : B) {
Peter Collingbourneffecb142016-05-26 01:19:17 +00001301 MemoryUseOrDef *MUD = createNewAccess(&I);
George Burgess IVb42b7622016-03-11 19:34:03 +00001302 if (!MUD)
George Burgess IVe1100f52016-02-02 22:46:49 +00001303 continue;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001304
George Burgess IVe1100f52016-02-02 22:46:49 +00001305 if (!Accesses)
1306 Accesses = getOrCreateAccessList(&B);
George Burgess IVb42b7622016-03-11 19:34:03 +00001307 Accesses->push_back(MUD);
Daniel Berlind602e042017-01-25 20:56:19 +00001308 if (isa<MemoryDef>(MUD)) {
1309 InsertIntoDef = true;
1310 if (!Defs)
1311 Defs = getOrCreateDefsList(&B);
1312 Defs->push_back(*MUD);
1313 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001314 }
Daniel Berlin7898ca62016-02-07 01:52:15 +00001315 if (InsertIntoDef)
1316 DefiningBlocks.insert(&B);
Daniel Berlin1b51a292016-02-07 01:52:19 +00001317 }
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001318 placePHINodes(DefiningBlocks, BBNumbers);
George Burgess IVe1100f52016-02-02 22:46:49 +00001319
1320 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
1321 // filled in with all blocks.
1322 SmallPtrSet<BasicBlock *, 16> Visited;
1323 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1324
George Burgess IV5f308972016-07-19 01:29:15 +00001325 CachingWalker *Walker = getWalkerImpl();
1326
1327 // We're doing a batch of updates; don't drop useful caches between them.
1328 Walker->setAutoResetWalker(false);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001329 OptimizeUses(this, Walker, AA, DT).optimizeUses();
George Burgess IV5f308972016-07-19 01:29:15 +00001330 Walker->setAutoResetWalker(true);
1331 Walker->resetClobberWalker();
1332
George Burgess IVe1100f52016-02-02 22:46:49 +00001333 // Mark the uses in unreachable blocks as live on entry, so that they go
1334 // somewhere.
1335 for (auto &BB : F)
1336 if (!Visited.count(&BB))
1337 markUnreachableAsLiveOnEntry(&BB);
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001338}
George Burgess IVe1100f52016-02-02 22:46:49 +00001339
George Burgess IV5f308972016-07-19 01:29:15 +00001340MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
1341
1342MemorySSA::CachingWalker *MemorySSA::getWalkerImpl() {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001343 if (Walker)
1344 return Walker.get();
1345
1346 Walker = make_unique<CachingWalker>(this, AA, DT);
Geoff Berryb96d3b22016-06-01 21:30:40 +00001347 return Walker.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001348}
1349
Daniel Berlind602e042017-01-25 20:56:19 +00001350// This is a helper function used by the creation routines. It places NewAccess
1351// into the access and defs lists for a given basic block, at the given
1352// insertion point.
1353void MemorySSA::insertIntoListsForBlock(MemoryAccess *NewAccess,
1354 const BasicBlock *BB,
1355 InsertionPlace Point) {
1356 auto *Accesses = getOrCreateAccessList(BB);
1357 if (Point == Beginning) {
1358 // If it's a phi node, it goes first, otherwise, it goes after any phi
1359 // nodes.
1360 if (isa<MemoryPhi>(NewAccess)) {
1361 Accesses->push_front(NewAccess);
1362 auto *Defs = getOrCreateDefsList(BB);
1363 Defs->push_front(*NewAccess);
1364 } else {
1365 auto AI = find_if_not(
1366 *Accesses, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1367 Accesses->insert(AI, NewAccess);
1368 if (!isa<MemoryUse>(NewAccess)) {
1369 auto *Defs = getOrCreateDefsList(BB);
1370 auto DI = find_if_not(
1371 *Defs, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1372 Defs->insert(DI, *NewAccess);
1373 }
1374 }
1375 } else {
1376 Accesses->push_back(NewAccess);
1377 if (!isa<MemoryUse>(NewAccess)) {
1378 auto *Defs = getOrCreateDefsList(BB);
1379 Defs->push_back(*NewAccess);
1380 }
1381 }
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001382 BlockNumberingValid.erase(BB);
Daniel Berlind602e042017-01-25 20:56:19 +00001383}
1384
1385void MemorySSA::insertIntoListsBefore(MemoryAccess *What, const BasicBlock *BB,
1386 AccessList::iterator InsertPt) {
1387 auto *Accesses = getWritableBlockAccesses(BB);
1388 bool WasEnd = InsertPt == Accesses->end();
1389 Accesses->insert(AccessList::iterator(InsertPt), What);
1390 if (!isa<MemoryUse>(What)) {
1391 auto *Defs = getOrCreateDefsList(BB);
1392 // If we got asked to insert at the end, we have an easy job, just shove it
1393 // at the end. If we got asked to insert before an existing def, we also get
1394 // an terator. If we got asked to insert before a use, we have to hunt for
1395 // the next def.
1396 if (WasEnd) {
1397 Defs->push_back(*What);
1398 } else if (isa<MemoryDef>(InsertPt)) {
1399 Defs->insert(InsertPt->getDefsIterator(), *What);
1400 } else {
1401 while (InsertPt != Accesses->end() && !isa<MemoryDef>(InsertPt))
1402 ++InsertPt;
1403 // Either we found a def, or we are inserting at the end
1404 if (InsertPt == Accesses->end())
1405 Defs->push_back(*What);
1406 else
1407 Defs->insert(InsertPt->getDefsIterator(), *What);
1408 }
1409 }
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001410 BlockNumberingValid.erase(BB);
Daniel Berlind602e042017-01-25 20:56:19 +00001411}
1412
Daniel Berlin60ead052017-01-28 01:23:13 +00001413// Move What before Where in the IR. The end result is taht What will belong to
1414// the right lists and have the right Block set, but will not otherwise be
1415// correct. It will not have the right defining access, and if it is a def,
1416// things below it will not properly be updated.
1417void MemorySSA::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
1418 AccessList::iterator Where) {
1419 // Keep it in the lookup tables, remove from the lists
1420 removeFromLists(What, false);
1421 What->setBlock(BB);
1422 insertIntoListsBefore(What, BB, Where);
1423}
1424
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001425void MemorySSA::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
1426 InsertionPlace Point) {
1427 removeFromLists(What, false);
1428 What->setBlock(BB);
1429 insertIntoListsForBlock(What, BB, Point);
1430}
1431
Daniel Berlin14300262016-06-21 18:39:20 +00001432MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
1433 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
Daniel Berlin14300262016-06-21 18:39:20 +00001434 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001435 // Phi's always are placed at the front of the block.
Daniel Berlind602e042017-01-25 20:56:19 +00001436 insertIntoListsForBlock(Phi, BB, Beginning);
Daniel Berlin5130cc82016-07-31 21:08:20 +00001437 ValueToMemoryAccess[BB] = Phi;
Daniel Berlin14300262016-06-21 18:39:20 +00001438 return Phi;
1439}
1440
1441MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
1442 MemoryAccess *Definition) {
1443 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
1444 MemoryUseOrDef *NewAccess = createNewAccess(I);
1445 assert(
1446 NewAccess != nullptr &&
1447 "Tried to create a memory access for a non-memory touching instruction");
1448 NewAccess->setDefiningAccess(Definition);
1449 return NewAccess;
1450}
1451
Daniel Berlind952cea2017-04-07 01:28:36 +00001452// Return true if the instruction has ordering constraints.
1453// Note specifically that this only considers stores and loads
1454// because others are still considered ModRef by getModRefInfo.
1455static inline bool isOrdered(const Instruction *I) {
1456 if (auto *SI = dyn_cast<StoreInst>(I)) {
1457 if (!SI->isUnordered())
1458 return true;
1459 } else if (auto *LI = dyn_cast<LoadInst>(I)) {
1460 if (!LI->isUnordered())
1461 return true;
1462 }
1463 return false;
1464}
George Burgess IVe1100f52016-02-02 22:46:49 +00001465/// \brief Helper function to create new memory accesses
Peter Collingbourneffecb142016-05-26 01:19:17 +00001466MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I) {
Peter Collingbourneb9aa1f42016-05-26 04:58:46 +00001467 // The assume intrinsic has a control dependency which we model by claiming
1468 // that it writes arbitrarily. Ignore that fake memory dependency here.
1469 // FIXME: Replace this special casing with a more accurate modelling of
1470 // assume's control dependency.
1471 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1472 if (II->getIntrinsicID() == Intrinsic::assume)
1473 return nullptr;
1474
George Burgess IVe1100f52016-02-02 22:46:49 +00001475 // Find out what affect this instruction has on memory.
Alina Sbirlea967e7962017-08-01 00:28:29 +00001476 ModRefInfo ModRef = AA->getModRefInfo(I, None);
Daniel Berlind952cea2017-04-07 01:28:36 +00001477 // The isOrdered check is used to ensure that volatiles end up as defs
1478 // (atomics end up as ModRef right now anyway). Until we separate the
1479 // ordering chain from the memory chain, this enables people to see at least
1480 // some relative ordering to volatiles. Note that getClobberingMemoryAccess
1481 // will still give an answer that bypasses other volatile loads. TODO:
1482 // Separate memory aliasing and ordering into two different chains so that we
1483 // can precisely represent both "what memory will this read/write/is clobbered
1484 // by" and "what instructions can I move this past".
1485 bool Def = bool(ModRef & MRI_Mod) || isOrdered(I);
George Burgess IVe1100f52016-02-02 22:46:49 +00001486 bool Use = bool(ModRef & MRI_Ref);
1487
1488 // It's possible for an instruction to not modify memory at all. During
1489 // construction, we ignore them.
Peter Collingbourneffecb142016-05-26 01:19:17 +00001490 if (!Def && !Use)
George Burgess IVe1100f52016-02-02 22:46:49 +00001491 return nullptr;
1492
1493 assert((Def || Use) &&
1494 "Trying to create a memory access with a non-memory instruction");
1495
George Burgess IVb42b7622016-03-11 19:34:03 +00001496 MemoryUseOrDef *MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001497 if (Def)
George Burgess IVb42b7622016-03-11 19:34:03 +00001498 MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
George Burgess IVe1100f52016-02-02 22:46:49 +00001499 else
George Burgess IVb42b7622016-03-11 19:34:03 +00001500 MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
Daniel Berlin5130cc82016-07-31 21:08:20 +00001501 ValueToMemoryAccess[I] = MUD;
George Burgess IVb42b7622016-03-11 19:34:03 +00001502 return MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001503}
1504
George Burgess IVe1100f52016-02-02 22:46:49 +00001505/// \brief Returns true if \p Replacer dominates \p Replacee .
1506bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
1507 const MemoryAccess *Replacee) const {
1508 if (isa<MemoryUseOrDef>(Replacee))
1509 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
1510 const auto *MP = cast<MemoryPhi>(Replacee);
1511 // For a phi node, the use occurs in the predecessor block of the phi node.
1512 // Since we may occur multiple times in the phi node, we have to check each
1513 // operand to ensure Replacer dominates each operand where Replacee occurs.
1514 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +00001515 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +00001516 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
1517 return false;
1518 }
1519 return true;
1520}
1521
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001522/// \brief Properly remove \p MA from all of MemorySSA's lookup tables.
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001523void MemorySSA::removeFromLookups(MemoryAccess *MA) {
1524 assert(MA->use_empty() &&
1525 "Trying to remove memory access that still has uses");
Daniel Berlin5c46b942016-07-19 22:49:43 +00001526 BlockNumbering.erase(MA);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001527 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA))
1528 MUD->setDefiningAccess(nullptr);
1529 // Invalidate our walker's cache if necessary
1530 if (!isa<MemoryUse>(MA))
1531 Walker->invalidateInfo(MA);
1532 // The call below to erase will destroy MA, so we can't change the order we
1533 // are doing things here
1534 Value *MemoryInst;
1535 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
1536 MemoryInst = MUD->getMemoryInst();
1537 } else {
1538 MemoryInst = MA->getBlock();
1539 }
Daniel Berlin5130cc82016-07-31 21:08:20 +00001540 auto VMA = ValueToMemoryAccess.find(MemoryInst);
1541 if (VMA->second == MA)
1542 ValueToMemoryAccess.erase(VMA);
Daniel Berlin60ead052017-01-28 01:23:13 +00001543}
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001544
Daniel Berlin60ead052017-01-28 01:23:13 +00001545/// \brief Properly remove \p MA from all of MemorySSA's lists.
1546///
1547/// Because of the way the intrusive list and use lists work, it is important to
1548/// do removal in the right order.
1549/// ShouldDelete defaults to true, and will cause the memory access to also be
1550/// deleted, not just removed.
1551void MemorySSA::removeFromLists(MemoryAccess *MA, bool ShouldDelete) {
Daniel Berlind602e042017-01-25 20:56:19 +00001552 // The access list owns the reference, so we erase it from the non-owning list
1553 // first.
1554 if (!isa<MemoryUse>(MA)) {
1555 auto DefsIt = PerBlockDefs.find(MA->getBlock());
1556 std::unique_ptr<DefsList> &Defs = DefsIt->second;
1557 Defs->remove(*MA);
1558 if (Defs->empty())
1559 PerBlockDefs.erase(DefsIt);
1560 }
1561
Daniel Berlin60ead052017-01-28 01:23:13 +00001562 // The erase call here will delete it. If we don't want it deleted, we call
1563 // remove instead.
George Burgess IVe0e6e482016-03-02 02:35:04 +00001564 auto AccessIt = PerBlockAccesses.find(MA->getBlock());
Daniel Berlinada263d2016-06-20 20:21:33 +00001565 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
Daniel Berlin60ead052017-01-28 01:23:13 +00001566 if (ShouldDelete)
1567 Accesses->erase(MA);
1568 else
1569 Accesses->remove(MA);
1570
George Burgess IVe0e6e482016-03-02 02:35:04 +00001571 if (Accesses->empty())
1572 PerBlockAccesses.erase(AccessIt);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001573}
1574
George Burgess IVe1100f52016-02-02 22:46:49 +00001575void MemorySSA::print(raw_ostream &OS) const {
1576 MemorySSAAnnotatedWriter Writer(this);
1577 F.print(OS, &Writer);
1578}
1579
Matthias Braun8c209aa2017-01-28 02:02:38 +00001580#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Daniel Berlin78cbd282017-02-20 22:26:03 +00001581LLVM_DUMP_METHOD void MemorySSA::dump() const { print(dbgs()); }
Matthias Braun8c209aa2017-01-28 02:02:38 +00001582#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001583
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001584void MemorySSA::verifyMemorySSA() const {
1585 verifyDefUses(F);
1586 verifyDomination(F);
Daniel Berlin14300262016-06-21 18:39:20 +00001587 verifyOrdering(F);
Geoff Berrycdf53332016-08-08 17:52:01 +00001588 Walker->verify(this);
Daniel Berlin14300262016-06-21 18:39:20 +00001589}
1590
1591/// \brief Verify that the order and existence of MemoryAccesses matches the
1592/// order and existence of memory affecting instructions.
1593void MemorySSA::verifyOrdering(Function &F) const {
1594 // Walk all the blocks, comparing what the lookups think and what the access
1595 // lists think, as well as the order in the blocks vs the order in the access
1596 // lists.
1597 SmallVector<MemoryAccess *, 32> ActualAccesses;
Daniel Berlind602e042017-01-25 20:56:19 +00001598 SmallVector<MemoryAccess *, 32> ActualDefs;
Daniel Berlin14300262016-06-21 18:39:20 +00001599 for (BasicBlock &B : F) {
1600 const AccessList *AL = getBlockAccesses(&B);
Daniel Berlind602e042017-01-25 20:56:19 +00001601 const auto *DL = getBlockDefs(&B);
Daniel Berlin14300262016-06-21 18:39:20 +00001602 MemoryAccess *Phi = getMemoryAccess(&B);
Daniel Berlind602e042017-01-25 20:56:19 +00001603 if (Phi) {
Daniel Berlin14300262016-06-21 18:39:20 +00001604 ActualAccesses.push_back(Phi);
Daniel Berlind602e042017-01-25 20:56:19 +00001605 ActualDefs.push_back(Phi);
1606 }
1607
Daniel Berlin14300262016-06-21 18:39:20 +00001608 for (Instruction &I : B) {
1609 MemoryAccess *MA = getMemoryAccess(&I);
Daniel Berlind602e042017-01-25 20:56:19 +00001610 assert((!MA || (AL && (isa<MemoryUse>(MA) || DL))) &&
1611 "We have memory affecting instructions "
1612 "in this block but they are not in the "
1613 "access list or defs list");
1614 if (MA) {
Daniel Berlin14300262016-06-21 18:39:20 +00001615 ActualAccesses.push_back(MA);
Daniel Berlind602e042017-01-25 20:56:19 +00001616 if (isa<MemoryDef>(MA))
1617 ActualDefs.push_back(MA);
1618 }
Daniel Berlin14300262016-06-21 18:39:20 +00001619 }
1620 // Either we hit the assert, really have no accesses, or we have both
Daniel Berlind602e042017-01-25 20:56:19 +00001621 // accesses and an access list.
1622 // Same with defs.
1623 if (!AL && !DL)
Daniel Berlin14300262016-06-21 18:39:20 +00001624 continue;
1625 assert(AL->size() == ActualAccesses.size() &&
1626 "We don't have the same number of accesses in the block as on the "
1627 "access list");
Davide Italiano6c77de02017-01-30 03:16:43 +00001628 assert((DL || ActualDefs.size() == 0) &&
1629 "Either we should have a defs list, or we should have no defs");
Daniel Berlind602e042017-01-25 20:56:19 +00001630 assert((!DL || DL->size() == ActualDefs.size()) &&
1631 "We don't have the same number of defs in the block as on the "
1632 "def list");
Daniel Berlin14300262016-06-21 18:39:20 +00001633 auto ALI = AL->begin();
1634 auto AAI = ActualAccesses.begin();
1635 while (ALI != AL->end() && AAI != ActualAccesses.end()) {
1636 assert(&*ALI == *AAI && "Not the same accesses in the same order");
1637 ++ALI;
1638 ++AAI;
1639 }
1640 ActualAccesses.clear();
Daniel Berlind602e042017-01-25 20:56:19 +00001641 if (DL) {
1642 auto DLI = DL->begin();
1643 auto ADI = ActualDefs.begin();
1644 while (DLI != DL->end() && ADI != ActualDefs.end()) {
1645 assert(&*DLI == *ADI && "Not the same defs in the same order");
1646 ++DLI;
1647 ++ADI;
1648 }
1649 }
1650 ActualDefs.clear();
Daniel Berlin14300262016-06-21 18:39:20 +00001651 }
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001652}
1653
George Burgess IVe1100f52016-02-02 22:46:49 +00001654/// \brief Verify the domination properties of MemorySSA by checking that each
1655/// definition dominates all of its uses.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001656void MemorySSA::verifyDomination(Function &F) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001657#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001658 for (BasicBlock &B : F) {
1659 // Phi nodes are attached to basic blocks
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001660 if (MemoryPhi *MP = getMemoryAccess(&B))
1661 for (const Use &U : MP->uses())
1662 assert(dominates(MP, U) && "Memory PHI does not dominate it's uses");
Daniel Berlin7af95872016-08-05 21:47:20 +00001663
George Burgess IVe1100f52016-02-02 22:46:49 +00001664 for (Instruction &I : B) {
1665 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
1666 if (!MD)
1667 continue;
1668
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001669 for (const Use &U : MD->uses())
1670 assert(dominates(MD, U) && "Memory Def does not dominate it's uses");
George Burgess IVe1100f52016-02-02 22:46:49 +00001671 }
1672 }
Daniel Berlin7af95872016-08-05 21:47:20 +00001673#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001674}
1675
1676/// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use
1677/// appears in the use list of \p Def.
Daniel Berlin7af95872016-08-05 21:47:20 +00001678
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001679void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001680#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001681 // The live on entry use may cause us to get a NULL def here
Daniel Berlin7af95872016-08-05 21:47:20 +00001682 if (!Def)
1683 assert(isLiveOnEntryDef(Use) &&
1684 "Null def but use not point to live on entry def");
1685 else
Daniel Berlinda2f38e2016-08-11 21:26:50 +00001686 assert(is_contained(Def->users(), Use) &&
Daniel Berlin7af95872016-08-05 21:47:20 +00001687 "Did not find use in def's use list");
1688#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001689}
1690
1691/// \brief Verify the immediate use information, by walking all the memory
1692/// accesses and verifying that, for each use, it appears in the
1693/// appropriate def's use list
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001694void MemorySSA::verifyDefUses(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001695 for (BasicBlock &B : F) {
1696 // Phi nodes are attached to basic blocks
Daniel Berlin14300262016-06-21 18:39:20 +00001697 if (MemoryPhi *Phi = getMemoryAccess(&B)) {
David Majnemer580e7542016-06-25 00:04:06 +00001698 assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
1699 pred_begin(&B), pred_end(&B))) &&
Daniel Berlin14300262016-06-21 18:39:20 +00001700 "Incomplete MemoryPhi Node");
George Burgess IVe1100f52016-02-02 22:46:49 +00001701 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
1702 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
Daniel Berlin14300262016-06-21 18:39:20 +00001703 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001704
1705 for (Instruction &I : B) {
George Burgess IV66837ab2016-11-01 21:17:46 +00001706 if (MemoryUseOrDef *MA = getMemoryAccess(&I)) {
1707 verifyUseInDefs(MA->getDefiningAccess(), MA);
George Burgess IVe1100f52016-02-02 22:46:49 +00001708 }
1709 }
1710 }
1711}
1712
George Burgess IV66837ab2016-11-01 21:17:46 +00001713MemoryUseOrDef *MemorySSA::getMemoryAccess(const Instruction *I) const {
1714 return cast_or_null<MemoryUseOrDef>(ValueToMemoryAccess.lookup(I));
George Burgess IVe1100f52016-02-02 22:46:49 +00001715}
1716
1717MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const {
George Burgess IV66837ab2016-11-01 21:17:46 +00001718 return cast_or_null<MemoryPhi>(ValueToMemoryAccess.lookup(cast<Value>(BB)));
George Burgess IVe1100f52016-02-02 22:46:49 +00001719}
1720
Daniel Berlin5c46b942016-07-19 22:49:43 +00001721/// Perform a local numbering on blocks so that instruction ordering can be
1722/// determined in constant time.
1723/// TODO: We currently just number in order. If we numbered by N, we could
1724/// allow at least N-1 sequences of insertBefore or insertAfter (and at least
1725/// log2(N) sequences of mixed before and after) without needing to invalidate
1726/// the numbering.
1727void MemorySSA::renumberBlock(const BasicBlock *B) const {
1728 // The pre-increment ensures the numbers really start at 1.
1729 unsigned long CurrentNumber = 0;
1730 const AccessList *AL = getBlockAccesses(B);
1731 assert(AL != nullptr && "Asking to renumber an empty block");
1732 for (const auto &I : *AL)
1733 BlockNumbering[&I] = ++CurrentNumber;
1734 BlockNumberingValid.insert(B);
1735}
1736
George Burgess IVe1100f52016-02-02 22:46:49 +00001737/// \brief Determine, for two memory accesses in the same block,
1738/// whether \p Dominator dominates \p Dominatee.
1739/// \returns True if \p Dominator dominates \p Dominatee.
1740bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
1741 const MemoryAccess *Dominatee) const {
Sebastian Pope1f60b12016-06-10 21:36:41 +00001742
Daniel Berlin5c46b942016-07-19 22:49:43 +00001743 const BasicBlock *DominatorBlock = Dominator->getBlock();
Daniel Berlin5c46b942016-07-19 22:49:43 +00001744
Daniel Berlin19860302016-07-19 23:08:08 +00001745 assert((DominatorBlock == Dominatee->getBlock()) &&
Daniel Berlin5c46b942016-07-19 22:49:43 +00001746 "Asking for local domination when accesses are in different blocks!");
Sebastian Pope1f60b12016-06-10 21:36:41 +00001747 // A node dominates itself.
1748 if (Dominatee == Dominator)
1749 return true;
1750
1751 // When Dominatee is defined on function entry, it is not dominated by another
1752 // memory access.
1753 if (isLiveOnEntryDef(Dominatee))
1754 return false;
1755
1756 // When Dominator is defined on function entry, it dominates the other memory
1757 // access.
1758 if (isLiveOnEntryDef(Dominator))
1759 return true;
1760
Daniel Berlin5c46b942016-07-19 22:49:43 +00001761 if (!BlockNumberingValid.count(DominatorBlock))
1762 renumberBlock(DominatorBlock);
George Burgess IVe1100f52016-02-02 22:46:49 +00001763
Daniel Berlin5c46b942016-07-19 22:49:43 +00001764 unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
1765 // All numbers start with 1
1766 assert(DominatorNum != 0 && "Block was not numbered properly");
1767 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
1768 assert(DominateeNum != 0 && "Block was not numbered properly");
1769 return DominatorNum < DominateeNum;
George Burgess IVe1100f52016-02-02 22:46:49 +00001770}
1771
George Burgess IV5f308972016-07-19 01:29:15 +00001772bool MemorySSA::dominates(const MemoryAccess *Dominator,
1773 const MemoryAccess *Dominatee) const {
1774 if (Dominator == Dominatee)
1775 return true;
1776
1777 if (isLiveOnEntryDef(Dominatee))
1778 return false;
1779
1780 if (Dominator->getBlock() != Dominatee->getBlock())
1781 return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
1782 return locallyDominates(Dominator, Dominatee);
1783}
1784
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001785bool MemorySSA::dominates(const MemoryAccess *Dominator,
1786 const Use &Dominatee) const {
1787 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Dominatee.getUser())) {
1788 BasicBlock *UseBB = MP->getIncomingBlock(Dominatee);
1789 // The def must dominate the incoming block of the phi.
1790 if (UseBB != Dominator->getBlock())
1791 return DT->dominates(Dominator->getBlock(), UseBB);
1792 // If the UseBB and the DefBB are the same, compare locally.
1793 return locallyDominates(Dominator, cast<MemoryAccess>(Dominatee));
1794 }
1795 // If it's not a PHI node use, the normal dominates can already handle it.
1796 return dominates(Dominator, cast<MemoryAccess>(Dominatee.getUser()));
1797}
1798
George Burgess IVe1100f52016-02-02 22:46:49 +00001799const static char LiveOnEntryStr[] = "liveOnEntry";
1800
Reid Kleckner96ab8722017-05-18 17:24:10 +00001801void MemoryAccess::print(raw_ostream &OS) const {
1802 switch (getValueID()) {
1803 case MemoryPhiVal: return static_cast<const MemoryPhi *>(this)->print(OS);
1804 case MemoryDefVal: return static_cast<const MemoryDef *>(this)->print(OS);
1805 case MemoryUseVal: return static_cast<const MemoryUse *>(this)->print(OS);
1806 }
1807 llvm_unreachable("invalid value id");
1808}
1809
George Burgess IVe1100f52016-02-02 22:46:49 +00001810void MemoryDef::print(raw_ostream &OS) const {
1811 MemoryAccess *UO = getDefiningAccess();
1812
1813 OS << getID() << " = MemoryDef(";
1814 if (UO && UO->getID())
1815 OS << UO->getID();
1816 else
1817 OS << LiveOnEntryStr;
1818 OS << ')';
1819}
1820
1821void MemoryPhi::print(raw_ostream &OS) const {
1822 bool First = true;
1823 OS << getID() << " = MemoryPhi(";
1824 for (const auto &Op : operands()) {
1825 BasicBlock *BB = getIncomingBlock(Op);
1826 MemoryAccess *MA = cast<MemoryAccess>(Op);
1827 if (!First)
1828 OS << ',';
1829 else
1830 First = false;
1831
1832 OS << '{';
1833 if (BB->hasName())
1834 OS << BB->getName();
1835 else
1836 BB->printAsOperand(OS, false);
1837 OS << ',';
1838 if (unsigned ID = MA->getID())
1839 OS << ID;
1840 else
1841 OS << LiveOnEntryStr;
1842 OS << '}';
1843 }
1844 OS << ')';
1845}
1846
George Burgess IVe1100f52016-02-02 22:46:49 +00001847void MemoryUse::print(raw_ostream &OS) const {
1848 MemoryAccess *UO = getDefiningAccess();
1849 OS << "MemoryUse(";
1850 if (UO && UO->getID())
1851 OS << UO->getID();
1852 else
1853 OS << LiveOnEntryStr;
1854 OS << ')';
1855}
1856
1857void MemoryAccess::dump() const {
Daniel Berlin78cbd282017-02-20 22:26:03 +00001858// Cannot completely remove virtual function even in release mode.
Matthias Braun8c209aa2017-01-28 02:02:38 +00001859#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
George Burgess IVe1100f52016-02-02 22:46:49 +00001860 print(dbgs());
1861 dbgs() << "\n";
Matthias Braun8c209aa2017-01-28 02:02:38 +00001862#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001863}
1864
Chad Rosier232e29e2016-07-06 21:20:47 +00001865char MemorySSAPrinterLegacyPass::ID = 0;
1866
1867MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) {
1868 initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
1869}
1870
1871void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
1872 AU.setPreservesAll();
1873 AU.addRequired<MemorySSAWrapperPass>();
Chad Rosier232e29e2016-07-06 21:20:47 +00001874}
1875
1876bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) {
1877 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
1878 MSSA.print(dbgs());
1879 if (VerifyMemorySSA)
1880 MSSA.verifyMemorySSA();
1881 return false;
1882}
1883
Chandler Carruthdab4eae2016-11-23 17:53:26 +00001884AnalysisKey MemorySSAAnalysis::Key;
George Burgess IVe1100f52016-02-02 22:46:49 +00001885
Daniel Berlin1e98c042016-09-26 17:22:54 +00001886MemorySSAAnalysis::Result MemorySSAAnalysis::run(Function &F,
1887 FunctionAnalysisManager &AM) {
Geoff Berryb96d3b22016-06-01 21:30:40 +00001888 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1889 auto &AA = AM.getResult<AAManager>(F);
Geoff Berry290a13e2016-08-08 18:27:22 +00001890 return MemorySSAAnalysis::Result(make_unique<MemorySSA>(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00001891}
1892
Geoff Berryb96d3b22016-06-01 21:30:40 +00001893PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
1894 FunctionAnalysisManager &AM) {
1895 OS << "MemorySSA for function: " << F.getName() << "\n";
Geoff Berry290a13e2016-08-08 18:27:22 +00001896 AM.getResult<MemorySSAAnalysis>(F).getMSSA().print(OS);
Geoff Berryb96d3b22016-06-01 21:30:40 +00001897
1898 return PreservedAnalyses::all();
George Burgess IVe1100f52016-02-02 22:46:49 +00001899}
1900
Geoff Berryb96d3b22016-06-01 21:30:40 +00001901PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
1902 FunctionAnalysisManager &AM) {
Geoff Berry290a13e2016-08-08 18:27:22 +00001903 AM.getResult<MemorySSAAnalysis>(F).getMSSA().verifyMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001904
1905 return PreservedAnalyses::all();
1906}
1907
1908char MemorySSAWrapperPass::ID = 0;
1909
1910MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
1911 initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
1912}
1913
1914void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
1915
1916void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001917 AU.setPreservesAll();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001918 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
1919 AU.addRequiredTransitive<AAResultsWrapperPass>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001920}
1921
Geoff Berryb96d3b22016-06-01 21:30:40 +00001922bool MemorySSAWrapperPass::runOnFunction(Function &F) {
1923 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1924 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1925 MSSA.reset(new MemorySSA(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00001926 return false;
1927}
1928
Geoff Berryb96d3b22016-06-01 21:30:40 +00001929void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); }
George Burgess IVe1100f52016-02-02 22:46:49 +00001930
Geoff Berryb96d3b22016-06-01 21:30:40 +00001931void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001932 MSSA->print(OS);
1933}
1934
George Burgess IVe1100f52016-02-02 22:46:49 +00001935MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
1936
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001937MemorySSA::CachingWalker::CachingWalker(MemorySSA *M, AliasAnalysis *A,
1938 DominatorTree *D)
Daniel Berlind7a7ae02017-04-05 19:01:58 +00001939 : MemorySSAWalker(M), Walker(*M, *A, *D), AutoResetWalker(true) {}
George Burgess IVe1100f52016-02-02 22:46:49 +00001940
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001941MemorySSA::CachingWalker::~CachingWalker() {}
George Burgess IVe1100f52016-02-02 22:46:49 +00001942
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001943void MemorySSA::CachingWalker::invalidateInfo(MemoryAccess *MA) {
Daniel Berlind7a7ae02017-04-05 19:01:58 +00001944 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1945 MUD->resetOptimized();
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001946}
1947
George Burgess IVe1100f52016-02-02 22:46:49 +00001948/// \brief Walk the use-def chains starting at \p MA and find
1949/// the MemoryAccess that actually clobbers Loc.
1950///
1951/// \returns our clobbering memory access
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001952MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
1953 MemoryAccess *StartingAccess, UpwardsMemoryQuery &Q) {
George Burgess IV5f308972016-07-19 01:29:15 +00001954 MemoryAccess *New = Walker.findClobber(StartingAccess, Q);
1955#ifdef EXPENSIVE_CHECKS
Daniel Berlind7a7ae02017-04-05 19:01:58 +00001956 MemoryAccess *NewNoCache = Walker.findClobber(StartingAccess, Q);
George Burgess IV5f308972016-07-19 01:29:15 +00001957 assert(NewNoCache == New && "Cache made us hand back a different result?");
Simon Pilgrim51693842017-06-11 12:49:29 +00001958 (void)NewNoCache;
George Burgess IV5f308972016-07-19 01:29:15 +00001959#endif
1960 if (AutoResetWalker)
1961 resetClobberWalker();
1962 return New;
George Burgess IVe1100f52016-02-02 22:46:49 +00001963}
1964
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001965MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
George Burgess IV013fd732016-10-28 19:22:46 +00001966 MemoryAccess *StartingAccess, const MemoryLocation &Loc) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001967 if (isa<MemoryPhi>(StartingAccess))
1968 return StartingAccess;
1969
1970 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
1971 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
1972 return StartingUseOrDef;
1973
1974 Instruction *I = StartingUseOrDef->getMemoryInst();
1975
1976 // Conservatively, fences are always clobbers, so don't perform the walk if we
1977 // hit a fence.
David Majnemera940f362016-07-15 17:19:24 +00001978 if (!ImmutableCallSite(I) && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00001979 return StartingUseOrDef;
1980
1981 UpwardsMemoryQuery Q;
1982 Q.OriginalAccess = StartingUseOrDef;
1983 Q.StartingLoc = Loc;
George Burgess IV5f308972016-07-19 01:29:15 +00001984 Q.Inst = I;
George Burgess IVe1100f52016-02-02 22:46:49 +00001985 Q.IsCall = false;
George Burgess IVe1100f52016-02-02 22:46:49 +00001986
George Burgess IVe1100f52016-02-02 22:46:49 +00001987 // Unlike the other function, do not walk to the def of a def, because we are
1988 // handed something we already believe is the clobbering access.
1989 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
1990 ? StartingUseOrDef->getDefiningAccess()
1991 : StartingUseOrDef;
1992
1993 MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00001994 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
1995 DEBUG(dbgs() << *StartingUseOrDef << "\n");
1996 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
1997 DEBUG(dbgs() << *Clobber << "\n");
1998 return Clobber;
1999}
2000
2001MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002002MemorySSA::CachingWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
2003 auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
2004 // If this is a MemoryPhi, we can't do anything.
2005 if (!StartingAccess)
2006 return MA;
George Burgess IVe1100f52016-02-02 22:46:49 +00002007
Daniel Berlincd2deac2016-10-20 20:13:45 +00002008 // If this is an already optimized use or def, return the optimized result.
2009 // Note: Currently, we do not store the optimized def result because we'd need
2010 // a separate field, since we can't use it as the defining access.
Daniel Berline33bc312017-04-04 23:43:10 +00002011 if (auto *MUD = dyn_cast<MemoryUseOrDef>(StartingAccess))
2012 if (MUD->isOptimized())
2013 return MUD->getOptimized();
Daniel Berlincd2deac2016-10-20 20:13:45 +00002014
George Burgess IV400ae402016-07-20 19:51:34 +00002015 const Instruction *I = StartingAccess->getMemoryInst();
George Burgess IV5f308972016-07-19 01:29:15 +00002016 UpwardsMemoryQuery Q(I, StartingAccess);
David Majnemera940f362016-07-15 17:19:24 +00002017 // We can't sanely do anything with a fences, they conservatively
George Burgess IVe1100f52016-02-02 22:46:49 +00002018 // clobber all memory, and have no locations to get pointers from to
David Majnemera940f362016-07-15 17:19:24 +00002019 // try to disambiguate.
George Burgess IV5f308972016-07-19 01:29:15 +00002020 if (!Q.IsCall && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002021 return StartingAccess;
2022
George Burgess IV024f3d22016-08-03 19:57:02 +00002023 if (isUseTriviallyOptimizableToLiveOnEntry(*MSSA->AA, I)) {
2024 MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef();
Daniel Berline33bc312017-04-04 23:43:10 +00002025 if (auto *MUD = dyn_cast<MemoryUseOrDef>(StartingAccess))
2026 MUD->setOptimized(LiveOnEntry);
George Burgess IV024f3d22016-08-03 19:57:02 +00002027 return LiveOnEntry;
2028 }
2029
George Burgess IVe1100f52016-02-02 22:46:49 +00002030 // Start with the thing we already think clobbers this location
2031 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
2032
2033 // At this point, DefiningAccess may be the live on entry def.
2034 // If it is, we will not get a better result.
2035 if (MSSA->isLiveOnEntryDef(DefiningAccess))
2036 return DefiningAccess;
2037
2038 MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00002039 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2040 DEBUG(dbgs() << *DefiningAccess << "\n");
2041 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2042 DEBUG(dbgs() << *Result << "\n");
Daniel Berline33bc312017-04-04 23:43:10 +00002043 if (auto *MUD = dyn_cast<MemoryUseOrDef>(StartingAccess))
2044 MUD->setOptimized(Result);
George Burgess IVe1100f52016-02-02 22:46:49 +00002045
2046 return Result;
2047}
2048
George Burgess IVe1100f52016-02-02 22:46:49 +00002049MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002050DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002051 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
2052 return Use->getDefiningAccess();
2053 return MA;
2054}
2055
2056MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
George Burgess IV013fd732016-10-28 19:22:46 +00002057 MemoryAccess *StartingAccess, const MemoryLocation &) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002058 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
2059 return Use->getDefiningAccess();
2060 return StartingAccess;
2061}
George Burgess IV5f308972016-07-19 01:29:15 +00002062} // namespace llvm
Reid Kleckner96ab8722017-05-18 17:24:10 +00002063
2064void MemoryPhi::deleteMe(DerivedUser *Self) {
2065 delete static_cast<MemoryPhi *>(Self);
2066}
2067
2068void MemoryDef::deleteMe(DerivedUser *Self) {
2069 delete static_cast<MemoryDef *>(Self);
2070}
2071
2072void MemoryUse::deleteMe(DerivedUser *Self) {
2073 delete static_cast<MemoryUse *>(Self);
2074}