blob: f2fc7e165b57f6944ff7142e6d4e9952d9bee67c [file] [log] [blame]
George Burgess IVe1100f52016-02-02 22:46:49 +00001//===-- MemorySSA.cpp - Memory SSA Builder---------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------===//
9//
10// This file implements the MemorySSA class.
11//
12//===----------------------------------------------------------------===//
Daniel Berlin16ed57c2016-06-27 18:22:27 +000013#include "llvm/Transforms/Utils/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"
42#include "llvm/Transforms/Scalar.h"
George Burgess IVe1100f52016-02-02 22:46:49 +000043#include <algorithm>
44
45#define DEBUG_TYPE "memoryssa"
46using namespace llvm;
Geoff Berryefb0dd12016-06-14 21:19:40 +000047INITIALIZE_PASS_BEGIN(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
Geoff Berryb96d3b22016-06-01 21:30:40 +000048 true)
George Burgess IVe1100f52016-02-02 22:46:49 +000049INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
50INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Geoff Berryefb0dd12016-06-14 21:19:40 +000051INITIALIZE_PASS_END(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
52 true)
George Burgess IVe1100f52016-02-02 22:46:49 +000053
Chad Rosier232e29e2016-07-06 21:20:47 +000054INITIALIZE_PASS_BEGIN(MemorySSAPrinterLegacyPass, "print-memoryssa",
55 "Memory SSA Printer", false, false)
56INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
57INITIALIZE_PASS_END(MemorySSAPrinterLegacyPass, "print-memoryssa",
58 "Memory SSA Printer", false, false)
59
Daniel Berlinc43aa5a2016-08-02 16:24:03 +000060static cl::opt<unsigned> MaxCheckLimit(
61 "memssa-check-limit", cl::Hidden, cl::init(100),
62 cl::desc("The maximum number of stores/phis MemorySSA"
63 "will consider trying to walk past (default = 100)"));
64
Chad Rosier232e29e2016-07-06 21:20:47 +000065static cl::opt<bool>
66 VerifyMemorySSA("verify-memoryssa", cl::init(false), cl::Hidden,
67 cl::desc("Verify MemorySSA in legacy printer pass."));
68
George Burgess IVe1100f52016-02-02 22:46:49 +000069namespace llvm {
George Burgess IVe1100f52016-02-02 22:46:49 +000070/// \brief An assembly annotator class to print Memory SSA information in
71/// comments.
72class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter {
73 friend class MemorySSA;
74 const MemorySSA *MSSA;
75
76public:
77 MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {}
78
79 virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
80 formatted_raw_ostream &OS) {
81 if (MemoryAccess *MA = MSSA->getMemoryAccess(BB))
82 OS << "; " << *MA << "\n";
83 }
84
85 virtual void emitInstructionAnnot(const Instruction *I,
86 formatted_raw_ostream &OS) {
87 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
88 OS << "; " << *MA << "\n";
89 }
90};
George Burgess IV5f308972016-07-19 01:29:15 +000091}
George Burgess IVfd1f2f82016-06-24 21:02:12 +000092
George Burgess IV5f308972016-07-19 01:29:15 +000093namespace {
Daniel Berlindff31de2016-08-02 21:57:52 +000094/// Our current alias analysis API differentiates heavily between calls and
95/// non-calls, and functions called on one usually assert on the other.
96/// This class encapsulates the distinction to simplify other code that wants
97/// "Memory affecting instructions and related data" to use as a key.
98/// For example, this class is used as a densemap key in the use optimizer.
99class MemoryLocOrCall {
100public:
101 MemoryLocOrCall() : IsCall(false) {}
102 MemoryLocOrCall(MemoryUseOrDef *MUD)
103 : MemoryLocOrCall(MUD->getMemoryInst()) {}
Sebastian Pop5068d7a2016-10-13 03:23:33 +0000104 MemoryLocOrCall(const MemoryUseOrDef *MUD)
105 : MemoryLocOrCall(MUD->getMemoryInst()) {}
Daniel Berlindff31de2016-08-02 21:57:52 +0000106
107 MemoryLocOrCall(Instruction *Inst) {
108 if (ImmutableCallSite(Inst)) {
109 IsCall = true;
110 CS = ImmutableCallSite(Inst);
111 } else {
112 IsCall = false;
113 // There is no such thing as a memorylocation for a fence inst, and it is
114 // unique in that regard.
115 if (!isa<FenceInst>(Inst))
116 Loc = MemoryLocation::get(Inst);
117 }
118 }
119
120 explicit MemoryLocOrCall(const MemoryLocation &Loc)
121 : IsCall(false), Loc(Loc) {}
122
123 bool IsCall;
124 ImmutableCallSite getCS() const {
125 assert(IsCall);
126 return CS;
127 }
128 MemoryLocation getLoc() const {
129 assert(!IsCall);
130 return Loc;
131 }
132
133 bool operator==(const MemoryLocOrCall &Other) const {
134 if (IsCall != Other.IsCall)
135 return false;
136
137 if (IsCall)
138 return CS.getCalledValue() == Other.CS.getCalledValue();
139 return Loc == Other.Loc;
140 }
141
142private:
Daniel Berlinf5361132016-10-22 04:15:41 +0000143 union {
Daniel Berlind602e042017-01-25 20:56:19 +0000144 ImmutableCallSite CS;
145 MemoryLocation Loc;
Daniel Berlinf5361132016-10-22 04:15:41 +0000146 };
Daniel Berlindff31de2016-08-02 21:57:52 +0000147};
148}
149
150namespace llvm {
151template <> struct DenseMapInfo<MemoryLocOrCall> {
152 static inline MemoryLocOrCall getEmptyKey() {
153 return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getEmptyKey());
154 }
155 static inline MemoryLocOrCall getTombstoneKey() {
156 return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getTombstoneKey());
157 }
158 static unsigned getHashValue(const MemoryLocOrCall &MLOC) {
159 if (MLOC.IsCall)
160 return hash_combine(MLOC.IsCall,
161 DenseMapInfo<const Value *>::getHashValue(
162 MLOC.getCS().getCalledValue()));
163 return hash_combine(
164 MLOC.IsCall, DenseMapInfo<MemoryLocation>::getHashValue(MLOC.getLoc()));
165 }
166 static bool isEqual(const MemoryLocOrCall &LHS, const MemoryLocOrCall &RHS) {
167 return LHS == RHS;
168 }
169};
Daniel Berlindf101192016-08-03 00:01:46 +0000170
George Burgess IVf7672852016-08-03 19:59:11 +0000171enum class Reorderability { Always, IfNoAlias, Never };
George Burgess IV82e355c2016-08-03 19:39:54 +0000172
173/// This does one-way checks to see if Use could theoretically be hoisted above
174/// MayClobber. This will not check the other way around.
175///
176/// This assumes that, for the purposes of MemorySSA, Use comes directly after
177/// MayClobber, with no potentially clobbering operations in between them.
178/// (Where potentially clobbering ops are memory barriers, aliased stores, etc.)
179static Reorderability getLoadReorderability(const LoadInst *Use,
180 const LoadInst *MayClobber) {
181 bool VolatileUse = Use->isVolatile();
182 bool VolatileClobber = MayClobber->isVolatile();
183 // Volatile operations may never be reordered with other volatile operations.
184 if (VolatileUse && VolatileClobber)
185 return Reorderability::Never;
186
187 // The lang ref allows reordering of volatile and non-volatile operations.
188 // Whether an aliasing nonvolatile load and volatile load can be reordered,
189 // though, is ambiguous. Because it may not be best to exploit this ambiguity,
190 // we only allow volatile/non-volatile reordering if the volatile and
191 // non-volatile operations don't alias.
192 Reorderability Result = VolatileUse || VolatileClobber
193 ? Reorderability::IfNoAlias
194 : Reorderability::Always;
195
196 // If a load is seq_cst, it cannot be moved above other loads. If its ordering
197 // is weaker, it can be moved above other loads. We just need to be sure that
198 // MayClobber isn't an acquire load, because loads can't be moved above
199 // acquire loads.
200 //
201 // Note that this explicitly *does* allow the free reordering of monotonic (or
202 // weaker) loads of the same address.
203 bool SeqCstUse = Use->getOrdering() == AtomicOrdering::SequentiallyConsistent;
204 bool MayClobberIsAcquire = isAtLeastOrStrongerThan(MayClobber->getOrdering(),
205 AtomicOrdering::Acquire);
206 if (SeqCstUse || MayClobberIsAcquire)
207 return Reorderability::Never;
208 return Result;
209}
210
Sebastian Popd57d93c2016-10-12 03:08:40 +0000211static bool instructionClobbersQuery(MemoryDef *MD,
212 const MemoryLocation &UseLoc,
213 const Instruction *UseInst,
214 AliasAnalysis &AA) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000215 Instruction *DefInst = MD->getMemoryInst();
216 assert(DefInst && "Defining instruction not actually an instruction");
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:
223 case Intrinsic::lifetime_end:
224 case Intrinsic::invariant_start:
225 case Intrinsic::invariant_end:
226 case Intrinsic::assume:
227 return false;
228 default:
229 break;
230 }
231 }
232
Daniel Berlindff31de2016-08-02 21:57:52 +0000233 ImmutableCallSite UseCS(UseInst);
234 if (UseCS) {
235 ModRefInfo I = AA.getModRefInfo(DefInst, UseCS);
236 return I != MRI_NoModRef;
237 }
George Burgess IV82e355c2016-08-03 19:39:54 +0000238
239 if (auto *DefLoad = dyn_cast<LoadInst>(DefInst)) {
240 if (auto *UseLoad = dyn_cast<LoadInst>(UseInst)) {
241 switch (getLoadReorderability(UseLoad, DefLoad)) {
242 case Reorderability::Always:
243 return false;
244 case Reorderability::Never:
245 return true;
246 case Reorderability::IfNoAlias:
247 return !AA.isNoAlias(UseLoc, MemoryLocation::get(DefLoad));
248 }
249 }
250 }
251
Daniel Berlindff31de2016-08-02 21:57:52 +0000252 return AA.getModRefInfo(DefInst, UseLoc) & MRI_Mod;
253}
254
Sebastian Pop5068d7a2016-10-13 03:23:33 +0000255static bool instructionClobbersQuery(MemoryDef *MD, const MemoryUseOrDef *MU,
256 const MemoryLocOrCall &UseMLOC,
257 AliasAnalysis &AA) {
258 // FIXME: This is a temporary hack to allow a single instructionClobbersQuery
259 // to exist while MemoryLocOrCall is pushed through places.
260 if (UseMLOC.IsCall)
261 return instructionClobbersQuery(MD, MemoryLocation(), MU->getMemoryInst(),
262 AA);
263 return instructionClobbersQuery(MD, UseMLOC.getLoc(), MU->getMemoryInst(),
264 AA);
265}
266
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000267// Return true when MD may alias MU, return false otherwise.
Daniel Berlindcb004f2017-03-02 23:06:46 +0000268bool MemorySSAUtil::defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU,
269 AliasAnalysis &AA) {
Sebastian Pop5068d7a2016-10-13 03:23:33 +0000270 return instructionClobbersQuery(MD, MU, MemoryLocOrCall(MU), AA);
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000271}
272}
273
274namespace {
275struct UpwardsMemoryQuery {
276 // True if our original query started off as a call
277 bool IsCall;
278 // The pointer location we started the query with. This will be empty if
279 // IsCall is true.
280 MemoryLocation StartingLoc;
281 // This is the instruction we were querying about.
282 const Instruction *Inst;
283 // The MemoryAccess we actually got called with, used to test local domination
284 const MemoryAccess *OriginalAccess;
285
286 UpwardsMemoryQuery()
287 : IsCall(false), Inst(nullptr), OriginalAccess(nullptr) {}
288
289 UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access)
290 : IsCall(ImmutableCallSite(Inst)), Inst(Inst), OriginalAccess(Access) {
291 if (!IsCall)
292 StartingLoc = MemoryLocation::get(Inst);
293 }
294};
295
296static bool lifetimeEndsAt(MemoryDef *MD, const MemoryLocation &Loc,
297 AliasAnalysis &AA) {
298 Instruction *Inst = MD->getMemoryInst();
299 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
300 switch (II->getIntrinsicID()) {
301 case Intrinsic::lifetime_start:
302 case Intrinsic::lifetime_end:
303 return AA.isMustAlias(MemoryLocation(II->getArgOperand(1)), Loc);
304 default:
305 return false;
306 }
307 }
308 return false;
309}
310
311static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysis &AA,
312 const Instruction *I) {
313 // If the memory can't be changed, then loads of the memory can't be
314 // clobbered.
315 //
316 // FIXME: We should handle invariant groups, as well. It's a bit harder,
317 // because we need to pay close attention to invariant group barriers.
318 return isa<LoadInst>(I) && (I->getMetadata(LLVMContext::MD_invariant_load) ||
Hal Finkela9d67cf2017-04-09 12:57:50 +0000319 AA.pointsToConstantMemory(cast<LoadInst>(I)->
320 getPointerOperand()));
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000321}
322
George Burgess IV5f308972016-07-19 01:29:15 +0000323/// Verifies that `Start` is clobbered by `ClobberAt`, and that nothing
324/// inbetween `Start` and `ClobberAt` can clobbers `Start`.
325///
326/// This is meant to be as simple and self-contained as possible. Because it
327/// uses no cache, etc., it can be relatively expensive.
328///
329/// \param Start The MemoryAccess that we want to walk from.
330/// \param ClobberAt A clobber for Start.
331/// \param StartLoc The MemoryLocation for Start.
332/// \param MSSA The MemorySSA isntance that Start and ClobberAt belong to.
333/// \param Query The UpwardsMemoryQuery we used for our search.
334/// \param AA The AliasAnalysis we used for our search.
335static void LLVM_ATTRIBUTE_UNUSED
336checkClobberSanity(MemoryAccess *Start, MemoryAccess *ClobberAt,
337 const MemoryLocation &StartLoc, const MemorySSA &MSSA,
338 const UpwardsMemoryQuery &Query, AliasAnalysis &AA) {
339 assert(MSSA.dominates(ClobberAt, Start) && "Clobber doesn't dominate start?");
340
341 if (MSSA.isLiveOnEntryDef(Start)) {
342 assert(MSSA.isLiveOnEntryDef(ClobberAt) &&
343 "liveOnEntry must clobber itself");
344 return;
345 }
346
George Burgess IV5f308972016-07-19 01:29:15 +0000347 bool FoundClobber = false;
348 DenseSet<MemoryAccessPair> VisitedPhis;
349 SmallVector<MemoryAccessPair, 8> Worklist;
350 Worklist.emplace_back(Start, StartLoc);
351 // Walk all paths from Start to ClobberAt, while looking for clobbers. If one
352 // is found, complain.
353 while (!Worklist.empty()) {
354 MemoryAccessPair MAP = Worklist.pop_back_val();
355 // All we care about is that nothing from Start to ClobberAt clobbers Start.
356 // We learn nothing from revisiting nodes.
357 if (!VisitedPhis.insert(MAP).second)
358 continue;
359
360 for (MemoryAccess *MA : def_chain(MAP.first)) {
361 if (MA == ClobberAt) {
362 if (auto *MD = dyn_cast<MemoryDef>(MA)) {
363 // instructionClobbersQuery isn't essentially free, so don't use `|=`,
364 // since it won't let us short-circuit.
365 //
366 // Also, note that this can't be hoisted out of the `Worklist` loop,
367 // since MD may only act as a clobber for 1 of N MemoryLocations.
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000368 FoundClobber =
369 FoundClobber || MSSA.isLiveOnEntryDef(MD) ||
370 instructionClobbersQuery(MD, MAP.second, Query.Inst, AA);
George Burgess IV5f308972016-07-19 01:29:15 +0000371 }
372 break;
373 }
374
375 // We should never hit liveOnEntry, unless it's the clobber.
376 assert(!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?");
377
378 if (auto *MD = dyn_cast<MemoryDef>(MA)) {
379 (void)MD;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000380 assert(!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA) &&
George Burgess IV5f308972016-07-19 01:29:15 +0000381 "Found clobber before reaching ClobberAt!");
382 continue;
383 }
384
385 assert(isa<MemoryPhi>(MA));
386 Worklist.append(upward_defs_begin({MA, MAP.second}), upward_defs_end());
387 }
388 }
389
390 // If ClobberAt is a MemoryPhi, we can assume something above it acted as a
391 // clobber. Otherwise, `ClobberAt` should've acted as a clobber at some point.
392 assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&
393 "ClobberAt never acted as a clobber");
394}
395
396/// Our algorithm for walking (and trying to optimize) clobbers, all wrapped up
397/// in one class.
398class ClobberWalker {
399 /// Save a few bytes by using unsigned instead of size_t.
400 using ListIndex = unsigned;
401
402 /// Represents a span of contiguous MemoryDefs, potentially ending in a
403 /// MemoryPhi.
404 struct DefPath {
405 MemoryLocation Loc;
406 // Note that, because we always walk in reverse, Last will always dominate
407 // First. Also note that First and Last are inclusive.
408 MemoryAccess *First;
409 MemoryAccess *Last;
George Burgess IV5f308972016-07-19 01:29:15 +0000410 Optional<ListIndex> Previous;
411
412 DefPath(const MemoryLocation &Loc, MemoryAccess *First, MemoryAccess *Last,
413 Optional<ListIndex> Previous)
414 : Loc(Loc), First(First), Last(Last), Previous(Previous) {}
415
416 DefPath(const MemoryLocation &Loc, MemoryAccess *Init,
417 Optional<ListIndex> Previous)
418 : DefPath(Loc, Init, Init, Previous) {}
419 };
420
421 const MemorySSA &MSSA;
422 AliasAnalysis &AA;
423 DominatorTree &DT;
George Burgess IV5f308972016-07-19 01:29:15 +0000424 UpwardsMemoryQuery *Query;
George Burgess IV5f308972016-07-19 01:29:15 +0000425
426 // Phi optimization bookkeeping
427 SmallVector<DefPath, 32> Paths;
428 DenseSet<ConstMemoryAccessPair> VisitedPhis;
George Burgess IV5f308972016-07-19 01:29:15 +0000429
George Burgess IV5f308972016-07-19 01:29:15 +0000430 /// Find the nearest def or phi that `From` can legally be optimized to.
Daniel Berlind0420312017-04-01 09:01:12 +0000431 const MemoryAccess *getWalkTarget(const MemoryPhi *From) const {
George Burgess IV5f308972016-07-19 01:29:15 +0000432 assert(From->getNumOperands() && "Phi with no operands?");
433
434 BasicBlock *BB = From->getBlock();
George Burgess IV5f308972016-07-19 01:29:15 +0000435 MemoryAccess *Result = MSSA.getLiveOnEntryDef();
436 DomTreeNode *Node = DT.getNode(BB);
437 while ((Node = Node->getIDom())) {
Daniel Berlin7500c562017-04-01 08:59:45 +0000438 auto *Defs = MSSA.getBlockDefs(Node->getBlock());
439 if (Defs)
Daniel Berlind0420312017-04-01 09:01:12 +0000440 return &*Defs->rbegin();
George Burgess IV5f308972016-07-19 01:29:15 +0000441 }
George Burgess IV5f308972016-07-19 01:29:15 +0000442 return Result;
443 }
444
445 /// Result of calling walkToPhiOrClobber.
446 struct UpwardsWalkResult {
447 /// The "Result" of the walk. Either a clobber, the last thing we walked, or
448 /// both.
449 MemoryAccess *Result;
450 bool IsKnownClobber;
George Burgess IV5f308972016-07-19 01:29:15 +0000451 };
452
453 /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last.
454 /// This will update Desc.Last as it walks. It will (optionally) also stop at
455 /// StopAt.
456 ///
457 /// This does not test for whether StopAt is a clobber
Daniel Berlind0420312017-04-01 09:01:12 +0000458 UpwardsWalkResult
459 walkToPhiOrClobber(DefPath &Desc,
460 const MemoryAccess *StopAt = nullptr) const {
George Burgess IV5f308972016-07-19 01:29:15 +0000461 assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");
462
463 for (MemoryAccess *Current : def_chain(Desc.Last)) {
464 Desc.Last = Current;
465 if (Current == StopAt)
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000466 return {Current, false};
George Burgess IV5f308972016-07-19 01:29:15 +0000467
468 if (auto *MD = dyn_cast<MemoryDef>(Current))
469 if (MSSA.isLiveOnEntryDef(MD) ||
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000470 instructionClobbersQuery(MD, Desc.Loc, Query->Inst, AA))
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000471 return {MD, true};
George Burgess IV5f308972016-07-19 01:29:15 +0000472 }
473
474 assert(isa<MemoryPhi>(Desc.Last) &&
475 "Ended at a non-clobber that's not a phi?");
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000476 return {Desc.Last, false};
George Burgess IV5f308972016-07-19 01:29:15 +0000477 }
478
479 void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches,
480 ListIndex PriorNode) {
481 auto UpwardDefs = make_range(upward_defs_begin({Phi, Paths[PriorNode].Loc}),
482 upward_defs_end());
483 for (const MemoryAccessPair &P : UpwardDefs) {
484 PausedSearches.push_back(Paths.size());
485 Paths.emplace_back(P.second, P.first, PriorNode);
486 }
487 }
488
489 /// Represents a search that terminated after finding a clobber. This clobber
490 /// may or may not be present in the path of defs from LastNode..SearchStart,
491 /// since it may have been retrieved from cache.
492 struct TerminatedPath {
493 MemoryAccess *Clobber;
494 ListIndex LastNode;
495 };
496
497 /// Get an access that keeps us from optimizing to the given phi.
498 ///
499 /// PausedSearches is an array of indices into the Paths array. Its incoming
500 /// value is the indices of searches that stopped at the last phi optimization
501 /// target. It's left in an unspecified state.
502 ///
503 /// If this returns None, NewPaused is a vector of searches that terminated
504 /// at StopWhere. Otherwise, NewPaused is left in an unspecified state.
George Burgess IV14633b52016-08-03 01:22:19 +0000505 Optional<TerminatedPath>
Daniel Berlind0420312017-04-01 09:01:12 +0000506 getBlockingAccess(const MemoryAccess *StopWhere,
George Burgess IV5f308972016-07-19 01:29:15 +0000507 SmallVectorImpl<ListIndex> &PausedSearches,
508 SmallVectorImpl<ListIndex> &NewPaused,
509 SmallVectorImpl<TerminatedPath> &Terminated) {
510 assert(!PausedSearches.empty() && "No searches to continue?");
511
512 // BFS vs DFS really doesn't make a difference here, so just do a DFS with
513 // PausedSearches as our stack.
514 while (!PausedSearches.empty()) {
515 ListIndex PathIndex = PausedSearches.pop_back_val();
516 DefPath &Node = Paths[PathIndex];
517
518 // If we've already visited this path with this MemoryLocation, we don't
519 // need to do so again.
520 //
521 // NOTE: That we just drop these paths on the ground makes caching
522 // behavior sporadic. e.g. given a diamond:
523 // A
524 // B C
525 // D
526 //
527 // ...If we walk D, B, A, C, we'll only cache the result of phi
528 // optimization for A, B, and D; C will be skipped because it dies here.
529 // This arguably isn't the worst thing ever, since:
530 // - We generally query things in a top-down order, so if we got below D
531 // without needing cache entries for {C, MemLoc}, then chances are
532 // that those cache entries would end up ultimately unused.
533 // - We still cache things for A, so C only needs to walk up a bit.
534 // If this behavior becomes problematic, we can fix without a ton of extra
535 // work.
536 if (!VisitedPhis.insert({Node.Last, Node.Loc}).second)
537 continue;
538
539 UpwardsWalkResult Res = walkToPhiOrClobber(Node, /*StopAt=*/StopWhere);
540 if (Res.IsKnownClobber) {
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000541 assert(Res.Result != StopWhere);
George Burgess IV5f308972016-07-19 01:29:15 +0000542 // If this wasn't a cache hit, we hit a clobber when walking. That's a
543 // failure.
George Burgess IV14633b52016-08-03 01:22:19 +0000544 TerminatedPath Term{Res.Result, PathIndex};
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000545 if (!MSSA.dominates(Res.Result, StopWhere))
George Burgess IV14633b52016-08-03 01:22:19 +0000546 return Term;
George Burgess IV5f308972016-07-19 01:29:15 +0000547
548 // Otherwise, it's a valid thing to potentially optimize to.
George Burgess IV14633b52016-08-03 01:22:19 +0000549 Terminated.push_back(Term);
George Burgess IV5f308972016-07-19 01:29:15 +0000550 continue;
551 }
552
553 if (Res.Result == StopWhere) {
554 // We've hit our target. Save this path off for if we want to continue
555 // walking.
556 NewPaused.push_back(PathIndex);
557 continue;
558 }
559
560 assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");
561 addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
562 }
563
564 return None;
565 }
566
567 template <typename T, typename Walker>
568 struct generic_def_path_iterator
569 : public iterator_facade_base<generic_def_path_iterator<T, Walker>,
570 std::forward_iterator_tag, T *> {
571 generic_def_path_iterator() : W(nullptr), N(None) {}
572 generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}
573
574 T &operator*() const { return curNode(); }
575
576 generic_def_path_iterator &operator++() {
577 N = curNode().Previous;
578 return *this;
579 }
580
581 bool operator==(const generic_def_path_iterator &O) const {
582 if (N.hasValue() != O.N.hasValue())
583 return false;
584 return !N.hasValue() || *N == *O.N;
585 }
586
587 private:
588 T &curNode() const { return W->Paths[*N]; }
589
590 Walker *W;
591 Optional<ListIndex> N;
592 };
593
594 using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
595 using const_def_path_iterator =
596 generic_def_path_iterator<const DefPath, const ClobberWalker>;
597
598 iterator_range<def_path_iterator> def_path(ListIndex From) {
599 return make_range(def_path_iterator(this, From), def_path_iterator());
600 }
601
602 iterator_range<const_def_path_iterator> const_def_path(ListIndex From) const {
603 return make_range(const_def_path_iterator(this, From),
604 const_def_path_iterator());
605 }
606
607 struct OptznResult {
608 /// The path that contains our result.
609 TerminatedPath PrimaryClobber;
610 /// The paths that we can legally cache back from, but that aren't
611 /// necessarily the result of the Phi optimization.
612 SmallVector<TerminatedPath, 4> OtherClobbers;
613 };
614
615 ListIndex defPathIndex(const DefPath &N) const {
616 // The assert looks nicer if we don't need to do &N
617 const DefPath *NP = &N;
618 assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
619 "Out of bounds DefPath!");
620 return NP - &Paths.front();
621 }
622
623 /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths
624 /// that act as legal clobbers. Note that this won't return *all* clobbers.
625 ///
626 /// Phi optimization algorithm tl;dr:
627 /// - Find the earliest def/phi, A, we can optimize to
628 /// - Find if all paths from the starting memory access ultimately reach A
629 /// - If not, optimization isn't possible.
630 /// - Otherwise, walk from A to another clobber or phi, A'.
631 /// - If A' is a def, we're done.
632 /// - If A' is a phi, try to optimize it.
633 ///
634 /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path
635 /// terminates when a MemoryAccess that clobbers said MemoryLocation is found.
636 OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start,
637 const MemoryLocation &Loc) {
638 assert(Paths.empty() && VisitedPhis.empty() &&
639 "Reset the optimization state.");
640
641 Paths.emplace_back(Loc, Start, Phi, None);
642 // Stores how many "valid" optimization nodes we had prior to calling
643 // addSearches/getBlockingAccess. Necessary for caching if we had a blocker.
644 auto PriorPathsSize = Paths.size();
645
646 SmallVector<ListIndex, 16> PausedSearches;
647 SmallVector<ListIndex, 8> NewPaused;
648 SmallVector<TerminatedPath, 4> TerminatedPaths;
649
650 addSearches(Phi, PausedSearches, 0);
651
652 // Moves the TerminatedPath with the "most dominated" Clobber to the end of
653 // Paths.
654 auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
655 assert(!Paths.empty() && "Need a path to move");
George Burgess IV5f308972016-07-19 01:29:15 +0000656 auto Dom = Paths.begin();
657 for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I)
658 if (!MSSA.dominates(I->Clobber, Dom->Clobber))
659 Dom = I;
660 auto Last = Paths.end() - 1;
661 if (Last != Dom)
662 std::iter_swap(Last, Dom);
663 };
664
665 MemoryPhi *Current = Phi;
666 while (1) {
667 assert(!MSSA.isLiveOnEntryDef(Current) &&
668 "liveOnEntry wasn't treated as a clobber?");
669
Daniel Berlind0420312017-04-01 09:01:12 +0000670 const auto *Target = getWalkTarget(Current);
George Burgess IV5f308972016-07-19 01:29:15 +0000671 // If a TerminatedPath doesn't dominate Target, then it wasn't a legal
672 // optimization for the prior phi.
673 assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {
674 return MSSA.dominates(P.Clobber, Target);
675 }));
676
677 // FIXME: This is broken, because the Blocker may be reported to be
678 // liveOnEntry, and we'll happily wait for that to disappear (read: never)
George Burgess IV7f414b92016-08-22 23:40:01 +0000679 // For the moment, this is fine, since we do nothing with blocker info.
George Burgess IV14633b52016-08-03 01:22:19 +0000680 if (Optional<TerminatedPath> Blocker = getBlockingAccess(
George Burgess IV5f308972016-07-19 01:29:15 +0000681 Target, PausedSearches, NewPaused, TerminatedPaths)) {
George Burgess IV5f308972016-07-19 01:29:15 +0000682
683 // Find the node we started at. We can't search based on N->Last, since
684 // we may have gone around a loop with a different MemoryLocation.
George Burgess IV14633b52016-08-03 01:22:19 +0000685 auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) {
George Burgess IV5f308972016-07-19 01:29:15 +0000686 return defPathIndex(N) < PriorPathsSize;
687 });
688 assert(Iter != def_path_iterator());
689
690 DefPath &CurNode = *Iter;
691 assert(CurNode.Last == Current);
George Burgess IV5f308972016-07-19 01:29:15 +0000692
693 // Two things:
694 // A. We can't reliably cache all of NewPaused back. Consider a case
695 // where we have two paths in NewPaused; one of which can't optimize
696 // above this phi, whereas the other can. If we cache the second path
697 // back, we'll end up with suboptimal cache entries. We can handle
698 // cases like this a bit better when we either try to find all
699 // clobbers that block phi optimization, or when our cache starts
700 // supporting unfinished searches.
701 // B. We can't reliably cache TerminatedPaths back here without doing
702 // extra checks; consider a case like:
703 // T
704 // / \
705 // D C
706 // \ /
707 // S
708 // Where T is our target, C is a node with a clobber on it, D is a
709 // diamond (with a clobber *only* on the left or right node, N), and
710 // S is our start. Say we walk to D, through the node opposite N
711 // (read: ignoring the clobber), and see a cache entry in the top
712 // node of D. That cache entry gets put into TerminatedPaths. We then
713 // walk up to C (N is later in our worklist), find the clobber, and
714 // quit. If we append TerminatedPaths to OtherClobbers, we'll cache
715 // the bottom part of D to the cached clobber, ignoring the clobber
716 // in N. Again, this problem goes away if we start tracking all
717 // blockers for a given phi optimization.
718 TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
719 return {Result, {}};
720 }
721
722 // If there's nothing left to search, then all paths led to valid clobbers
723 // that we got from our cache; pick the nearest to the start, and allow
724 // the rest to be cached back.
725 if (NewPaused.empty()) {
726 MoveDominatedPathToEnd(TerminatedPaths);
727 TerminatedPath Result = TerminatedPaths.pop_back_val();
728 return {Result, std::move(TerminatedPaths)};
729 }
730
731 MemoryAccess *DefChainEnd = nullptr;
732 SmallVector<TerminatedPath, 4> Clobbers;
733 for (ListIndex Paused : NewPaused) {
734 UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
735 if (WR.IsKnownClobber)
736 Clobbers.push_back({WR.Result, Paused});
737 else
738 // Micro-opt: If we hit the end of the chain, save it.
739 DefChainEnd = WR.Result;
740 }
741
742 if (!TerminatedPaths.empty()) {
743 // If we couldn't find the dominating phi/liveOnEntry in the above loop,
744 // do it now.
745 if (!DefChainEnd)
Daniel Berlind0420312017-04-01 09:01:12 +0000746 for (auto *MA : def_chain(const_cast<MemoryAccess *>(Target)))
George Burgess IV5f308972016-07-19 01:29:15 +0000747 DefChainEnd = MA;
748
749 // If any of the terminated paths don't dominate the phi we'll try to
750 // optimize, we need to figure out what they are and quit.
751 const BasicBlock *ChainBB = DefChainEnd->getBlock();
752 for (const TerminatedPath &TP : TerminatedPaths) {
753 // Because we know that DefChainEnd is as "high" as we can go, we
754 // don't need local dominance checks; BB dominance is sufficient.
755 if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
756 Clobbers.push_back(TP);
757 }
758 }
759
760 // If we have clobbers in the def chain, find the one closest to Current
761 // and quit.
762 if (!Clobbers.empty()) {
763 MoveDominatedPathToEnd(Clobbers);
764 TerminatedPath Result = Clobbers.pop_back_val();
765 return {Result, std::move(Clobbers)};
766 }
767
768 assert(all_of(NewPaused,
769 [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
770
771 // Because liveOnEntry is a clobber, this must be a phi.
772 auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
773
774 PriorPathsSize = Paths.size();
775 PausedSearches.clear();
776 for (ListIndex I : NewPaused)
777 addSearches(DefChainPhi, PausedSearches, I);
778 NewPaused.clear();
779
780 Current = DefChainPhi;
781 }
782 }
783
George Burgess IV5f308972016-07-19 01:29:15 +0000784 void verifyOptResult(const OptznResult &R) const {
785 assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
786 return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
787 }));
788 }
789
790 void resetPhiOptznState() {
791 Paths.clear();
792 VisitedPhis.clear();
793 }
794
795public:
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000796 ClobberWalker(const MemorySSA &MSSA, AliasAnalysis &AA, DominatorTree &DT)
797 : MSSA(MSSA), AA(AA), DT(DT) {}
George Burgess IV5f308972016-07-19 01:29:15 +0000798
Daniel Berlin7500c562017-04-01 08:59:45 +0000799 void reset() {}
George Burgess IV5f308972016-07-19 01:29:15 +0000800
801 /// Finds the nearest clobber for the given query, optimizing phis if
802 /// possible.
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000803 MemoryAccess *findClobber(MemoryAccess *Start, UpwardsMemoryQuery &Q) {
George Burgess IV5f308972016-07-19 01:29:15 +0000804 Query = &Q;
805
806 MemoryAccess *Current = Start;
807 // This walker pretends uses don't exist. If we're handed one, silently grab
808 // its def. (This has the nice side-effect of ensuring we never cache uses)
809 if (auto *MU = dyn_cast<MemoryUse>(Start))
810 Current = MU->getDefiningAccess();
811
812 DefPath FirstDesc(Q.StartingLoc, Current, Current, None);
813 // Fast path for the overly-common case (no crazy phi optimization
814 // necessary)
815 UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
George Burgess IV93ea19b2016-07-24 07:03:49 +0000816 MemoryAccess *Result;
George Burgess IV5f308972016-07-19 01:29:15 +0000817 if (WalkResult.IsKnownClobber) {
George Burgess IV93ea19b2016-07-24 07:03:49 +0000818 Result = WalkResult.Result;
819 } else {
820 OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
821 Current, Q.StartingLoc);
822 verifyOptResult(OptRes);
George Burgess IV93ea19b2016-07-24 07:03:49 +0000823 resetPhiOptznState();
824 Result = OptRes.PrimaryClobber.Clobber;
George Burgess IV5f308972016-07-19 01:29:15 +0000825 }
826
George Burgess IV5f308972016-07-19 01:29:15 +0000827#ifdef EXPENSIVE_CHECKS
George Burgess IV93ea19b2016-07-24 07:03:49 +0000828 checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, AA);
George Burgess IV5f308972016-07-19 01:29:15 +0000829#endif
George Burgess IV93ea19b2016-07-24 07:03:49 +0000830 return Result;
George Burgess IV5f308972016-07-19 01:29:15 +0000831 }
Geoff Berrycdf53332016-08-08 17:52:01 +0000832
833 void verify(const MemorySSA *MSSA) { assert(MSSA == &this->MSSA); }
George Burgess IV5f308972016-07-19 01:29:15 +0000834};
835
836struct RenamePassData {
837 DomTreeNode *DTN;
838 DomTreeNode::const_iterator ChildIt;
839 MemoryAccess *IncomingVal;
840
841 RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
842 MemoryAccess *M)
843 : DTN(D), ChildIt(It), IncomingVal(M) {}
844 void swap(RenamePassData &RHS) {
845 std::swap(DTN, RHS.DTN);
846 std::swap(ChildIt, RHS.ChildIt);
847 std::swap(IncomingVal, RHS.IncomingVal);
848 }
849};
850} // anonymous namespace
851
852namespace llvm {
Daniel Berlind952cea2017-04-07 01:28:36 +0000853/// \brief A MemorySSAWalker that does AA walks to disambiguate accesses. It no
854/// longer does caching on its own,
Daniel Berlind7a7ae02017-04-05 19:01:58 +0000855/// but the name has been retained for the moment.
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000856class MemorySSA::CachingWalker final : public MemorySSAWalker {
George Burgess IV5f308972016-07-19 01:29:15 +0000857 ClobberWalker Walker;
858 bool AutoResetWalker;
859
860 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *, UpwardsMemoryQuery &);
861 void verifyRemoved(MemoryAccess *);
862
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000863public:
864 CachingWalker(MemorySSA *, AliasAnalysis *, DominatorTree *);
865 ~CachingWalker() override;
866
George Burgess IV400ae402016-07-20 19:51:34 +0000867 using MemorySSAWalker::getClobberingMemoryAccess;
868 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) override;
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000869 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
George Burgess IV013fd732016-10-28 19:22:46 +0000870 const MemoryLocation &) override;
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000871 void invalidateInfo(MemoryAccess *) override;
872
George Burgess IV5f308972016-07-19 01:29:15 +0000873 /// Whether we call resetClobberWalker() after each time we *actually* walk to
874 /// answer a clobber query.
875 void setAutoResetWalker(bool AutoReset) { AutoResetWalker = AutoReset; }
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000876
Daniel Berlin7500c562017-04-01 08:59:45 +0000877 /// Drop the walker's persistent data structures.
George Burgess IV5f308972016-07-19 01:29:15 +0000878 void resetClobberWalker() { Walker.reset(); }
Geoff Berrycdf53332016-08-08 17:52:01 +0000879
880 void verify(const MemorySSA *MSSA) override {
881 MemorySSAWalker::verify(MSSA);
882 Walker.verify(MSSA);
883 }
George Burgess IVfd1f2f82016-06-24 21:02:12 +0000884};
George Burgess IVe1100f52016-02-02 22:46:49 +0000885
Daniel Berlin78cbd282017-02-20 22:26:03 +0000886void MemorySSA::renameSuccessorPhis(BasicBlock *BB, MemoryAccess *IncomingVal,
887 bool RenameAllUses) {
George Burgess IVe1100f52016-02-02 22:46:49 +0000888 // Pass through values to our successors
889 for (const BasicBlock *S : successors(BB)) {
890 auto It = PerBlockAccesses.find(S);
891 // Rename the phi nodes in our successor block
892 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
893 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +0000894 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +0000895 auto *Phi = cast<MemoryPhi>(&Accesses->front());
Daniel Berlin78cbd282017-02-20 22:26:03 +0000896 if (RenameAllUses) {
897 int PhiIndex = Phi->getBasicBlockIndex(BB);
898 assert(PhiIndex != -1 && "Incomplete phi during partial rename");
899 Phi->setIncomingValue(PhiIndex, IncomingVal);
900 } else
901 Phi->addIncoming(IncomingVal, BB);
George Burgess IVe1100f52016-02-02 22:46:49 +0000902 }
Daniel Berlin78cbd282017-02-20 22:26:03 +0000903}
George Burgess IVe1100f52016-02-02 22:46:49 +0000904
Daniel Berlin78cbd282017-02-20 22:26:03 +0000905/// \brief Rename a single basic block into MemorySSA form.
906/// Uses the standard SSA renaming algorithm.
907/// \returns The new incoming value.
908MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB, MemoryAccess *IncomingVal,
909 bool RenameAllUses) {
910 auto It = PerBlockAccesses.find(BB);
911 // Skip most processing if the list is empty.
912 if (It != PerBlockAccesses.end()) {
913 AccessList *Accesses = It->second.get();
914 for (MemoryAccess &L : *Accesses) {
915 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&L)) {
916 if (MUD->getDefiningAccess() == nullptr || RenameAllUses)
917 MUD->setDefiningAccess(IncomingVal);
918 if (isa<MemoryDef>(&L))
919 IncomingVal = &L;
920 } else {
921 IncomingVal = &L;
922 }
923 }
924 }
George Burgess IVe1100f52016-02-02 22:46:49 +0000925 return IncomingVal;
926}
927
928/// \brief This is the standard SSA renaming algorithm.
929///
930/// We walk the dominator tree in preorder, renaming accesses, and then filling
931/// in phi nodes in our successors.
932void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
Daniel Berlin78cbd282017-02-20 22:26:03 +0000933 SmallPtrSetImpl<BasicBlock *> &Visited,
934 bool SkipVisited, bool RenameAllUses) {
George Burgess IVe1100f52016-02-02 22:46:49 +0000935 SmallVector<RenamePassData, 32> WorkStack;
Daniel Berlin78cbd282017-02-20 22:26:03 +0000936 // Skip everything if we already renamed this block and we are skipping.
937 // Note: You can't sink this into the if, because we need it to occur
938 // regardless of whether we skip blocks or not.
939 bool AlreadyVisited = !Visited.insert(Root->getBlock()).second;
940 if (SkipVisited && AlreadyVisited)
941 return;
942
943 IncomingVal = renameBlock(Root->getBlock(), IncomingVal, RenameAllUses);
944 renameSuccessorPhis(Root->getBlock(), IncomingVal, RenameAllUses);
George Burgess IVe1100f52016-02-02 22:46:49 +0000945 WorkStack.push_back({Root, Root->begin(), IncomingVal});
George Burgess IVe1100f52016-02-02 22:46:49 +0000946
947 while (!WorkStack.empty()) {
948 DomTreeNode *Node = WorkStack.back().DTN;
949 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
950 IncomingVal = WorkStack.back().IncomingVal;
951
952 if (ChildIt == Node->end()) {
953 WorkStack.pop_back();
954 } else {
955 DomTreeNode *Child = *ChildIt;
956 ++WorkStack.back().ChildIt;
957 BasicBlock *BB = Child->getBlock();
Daniel Berlin78cbd282017-02-20 22:26:03 +0000958 // Note: You can't sink this into the if, because we need it to occur
959 // regardless of whether we skip blocks or not.
960 AlreadyVisited = !Visited.insert(BB).second;
961 if (SkipVisited && AlreadyVisited) {
962 // We already visited this during our renaming, which can happen when
963 // being asked to rename multiple blocks. Figure out the incoming val,
964 // which is the last def.
965 // Incoming value can only change if there is a block def, and in that
966 // case, it's the last block def in the list.
967 if (auto *BlockDefs = getWritableBlockDefs(BB))
968 IncomingVal = &*BlockDefs->rbegin();
969 } else
970 IncomingVal = renameBlock(BB, IncomingVal, RenameAllUses);
971 renameSuccessorPhis(BB, IncomingVal, RenameAllUses);
George Burgess IVe1100f52016-02-02 22:46:49 +0000972 WorkStack.push_back({Child, Child->begin(), IncomingVal});
973 }
974 }
975}
976
977/// \brief Compute dominator levels, used by the phi insertion algorithm above.
978void MemorySSA::computeDomLevels(DenseMap<DomTreeNode *, unsigned> &DomLevels) {
979 for (auto DFI = df_begin(DT->getRootNode()), DFE = df_end(DT->getRootNode());
980 DFI != DFE; ++DFI)
981 DomLevels[*DFI] = DFI.getPathLength() - 1;
982}
983
George Burgess IVa362b092016-07-06 00:28:43 +0000984/// \brief This handles unreachable block accesses by deleting phi nodes in
George Burgess IVe1100f52016-02-02 22:46:49 +0000985/// unreachable blocks, and marking all other unreachable MemoryAccess's as
986/// being uses of the live on entry definition.
987void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
988 assert(!DT->isReachableFromEntry(BB) &&
989 "Reachable block found while handling unreachable blocks");
990
Daniel Berlinfc7e6512016-07-06 05:32:05 +0000991 // Make sure phi nodes in our reachable successors end up with a
992 // LiveOnEntryDef for our incoming edge, even though our block is forward
993 // unreachable. We could just disconnect these blocks from the CFG fully,
994 // but we do not right now.
995 for (const BasicBlock *S : successors(BB)) {
996 if (!DT->isReachableFromEntry(S))
997 continue;
998 auto It = PerBlockAccesses.find(S);
999 // Rename the phi nodes in our successor block
1000 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1001 continue;
1002 AccessList *Accesses = It->second.get();
1003 auto *Phi = cast<MemoryPhi>(&Accesses->front());
1004 Phi->addIncoming(LiveOnEntryDef.get(), BB);
1005 }
1006
George Burgess IVe1100f52016-02-02 22:46:49 +00001007 auto It = PerBlockAccesses.find(BB);
1008 if (It == PerBlockAccesses.end())
1009 return;
1010
1011 auto &Accesses = It->second;
1012 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1013 auto Next = std::next(AI);
1014 // If we have a phi, just remove it. We are going to replace all
1015 // users with live on entry.
1016 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1017 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1018 else
1019 Accesses->erase(AI);
1020 AI = Next;
1021 }
1022}
1023
Geoff Berryb96d3b22016-06-01 21:30:40 +00001024MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
1025 : AA(AA), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
Daniel Berlincd2deac2016-10-20 20:13:45 +00001026 NextID(INVALID_MEMORYACCESS_ID) {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001027 buildMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001028}
1029
George Burgess IVe1100f52016-02-02 22:46:49 +00001030MemorySSA::~MemorySSA() {
1031 // Drop all our references
1032 for (const auto &Pair : PerBlockAccesses)
1033 for (MemoryAccess &MA : *Pair.second)
1034 MA.dropAllReferences();
1035}
1036
Daniel Berlin14300262016-06-21 18:39:20 +00001037MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001038 auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
1039
1040 if (Res.second)
Daniel Berlinada263d2016-06-20 20:21:33 +00001041 Res.first->second = make_unique<AccessList>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001042 return Res.first->second.get();
1043}
Daniel Berlind602e042017-01-25 20:56:19 +00001044MemorySSA::DefsList *MemorySSA::getOrCreateDefsList(const BasicBlock *BB) {
1045 auto Res = PerBlockDefs.insert(std::make_pair(BB, nullptr));
1046
1047 if (Res.second)
1048 Res.first->second = make_unique<DefsList>();
1049 return Res.first->second.get();
1050}
George Burgess IVe1100f52016-02-02 22:46:49 +00001051
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001052/// This class is a batch walker of all MemoryUse's in the program, and points
1053/// their defining access at the thing that actually clobbers them. Because it
1054/// is a batch walker that touches everything, it does not operate like the
1055/// other walkers. This walker is basically performing a top-down SSA renaming
1056/// pass, where the version stack is used as the cache. This enables it to be
1057/// significantly more time and memory efficient than using the regular walker,
1058/// which is walking bottom-up.
1059class MemorySSA::OptimizeUses {
1060public:
1061 OptimizeUses(MemorySSA *MSSA, MemorySSAWalker *Walker, AliasAnalysis *AA,
1062 DominatorTree *DT)
1063 : MSSA(MSSA), Walker(Walker), AA(AA), DT(DT) {
1064 Walker = MSSA->getWalker();
1065 }
1066
1067 void optimizeUses();
1068
1069private:
1070 /// This represents where a given memorylocation is in the stack.
1071 struct MemlocStackInfo {
1072 // This essentially is keeping track of versions of the stack. Whenever
1073 // the stack changes due to pushes or pops, these versions increase.
1074 unsigned long StackEpoch;
1075 unsigned long PopEpoch;
1076 // This is the lower bound of places on the stack to check. It is equal to
1077 // the place the last stack walk ended.
1078 // Note: Correctness depends on this being initialized to 0, which densemap
1079 // does
1080 unsigned long LowerBound;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001081 const BasicBlock *LowerBoundBlock;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001082 // This is where the last walk for this memory location ended.
1083 unsigned long LastKill;
1084 bool LastKillValid;
1085 };
1086 void optimizeUsesInBlock(const BasicBlock *, unsigned long &, unsigned long &,
1087 SmallVectorImpl<MemoryAccess *> &,
1088 DenseMap<MemoryLocOrCall, MemlocStackInfo> &);
1089 MemorySSA *MSSA;
1090 MemorySSAWalker *Walker;
1091 AliasAnalysis *AA;
1092 DominatorTree *DT;
1093};
1094
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001095/// Optimize the uses in a given block This is basically the SSA renaming
1096/// algorithm, with one caveat: We are able to use a single stack for all
1097/// MemoryUses. This is because the set of *possible* reaching MemoryDefs is
1098/// the same for every MemoryUse. The *actual* clobbering MemoryDef is just
1099/// going to be some position in that stack of possible ones.
1100///
1101/// We track the stack positions that each MemoryLocation needs
1102/// to check, and last ended at. This is because we only want to check the
1103/// things that changed since last time. The same MemoryLocation should
1104/// get clobbered by the same store (getModRefInfo does not use invariantness or
1105/// things like this, and if they start, we can modify MemoryLocOrCall to
1106/// include relevant data)
1107void MemorySSA::OptimizeUses::optimizeUsesInBlock(
1108 const BasicBlock *BB, unsigned long &StackEpoch, unsigned long &PopEpoch,
1109 SmallVectorImpl<MemoryAccess *> &VersionStack,
1110 DenseMap<MemoryLocOrCall, MemlocStackInfo> &LocStackInfo) {
1111
1112 /// If no accesses, nothing to do.
1113 MemorySSA::AccessList *Accesses = MSSA->getWritableBlockAccesses(BB);
1114 if (Accesses == nullptr)
1115 return;
1116
1117 // Pop everything that doesn't dominate the current block off the stack,
1118 // increment the PopEpoch to account for this.
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001119 while (true) {
1120 assert(
1121 !VersionStack.empty() &&
1122 "Version stack should have liveOnEntry sentinel dominating everything");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001123 BasicBlock *BackBlock = VersionStack.back()->getBlock();
1124 if (DT->dominates(BackBlock, BB))
1125 break;
1126 while (VersionStack.back()->getBlock() == BackBlock)
1127 VersionStack.pop_back();
1128 ++PopEpoch;
1129 }
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001130
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001131 for (MemoryAccess &MA : *Accesses) {
1132 auto *MU = dyn_cast<MemoryUse>(&MA);
1133 if (!MU) {
1134 VersionStack.push_back(&MA);
1135 ++StackEpoch;
1136 continue;
1137 }
1138
George Burgess IV024f3d22016-08-03 19:57:02 +00001139 if (isUseTriviallyOptimizableToLiveOnEntry(*AA, MU->getMemoryInst())) {
Daniel Berlincd2deac2016-10-20 20:13:45 +00001140 MU->setDefiningAccess(MSSA->getLiveOnEntryDef(), true);
George Burgess IV024f3d22016-08-03 19:57:02 +00001141 continue;
1142 }
1143
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001144 MemoryLocOrCall UseMLOC(MU);
1145 auto &LocInfo = LocStackInfo[UseMLOC];
Daniel Berlin26fcea92016-08-02 20:02:21 +00001146 // If the pop epoch changed, it means we've removed stuff from top of
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001147 // stack due to changing blocks. We may have to reset the lower bound or
1148 // last kill info.
1149 if (LocInfo.PopEpoch != PopEpoch) {
1150 LocInfo.PopEpoch = PopEpoch;
1151 LocInfo.StackEpoch = StackEpoch;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001152 // If the lower bound was in something that no longer dominates us, we
1153 // have to reset it.
1154 // We can't simply track stack size, because the stack may have had
1155 // pushes/pops in the meantime.
1156 // XXX: This is non-optimal, but only is slower cases with heavily
1157 // branching dominator trees. To get the optimal number of queries would
1158 // be to make lowerbound and lastkill a per-loc stack, and pop it until
1159 // the top of that stack dominates us. This does not seem worth it ATM.
1160 // A much cheaper optimization would be to always explore the deepest
1161 // branch of the dominator tree first. This will guarantee this resets on
1162 // the smallest set of blocks.
1163 if (LocInfo.LowerBoundBlock && LocInfo.LowerBoundBlock != BB &&
Daniel Berlin1e98c042016-09-26 17:22:54 +00001164 !DT->dominates(LocInfo.LowerBoundBlock, BB)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001165 // Reset the lower bound of things to check.
1166 // TODO: Some day we should be able to reset to last kill, rather than
1167 // 0.
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001168 LocInfo.LowerBound = 0;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001169 LocInfo.LowerBoundBlock = VersionStack[0]->getBlock();
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001170 LocInfo.LastKillValid = false;
1171 }
1172 } else if (LocInfo.StackEpoch != StackEpoch) {
1173 // If all that has changed is the StackEpoch, we only have to check the
1174 // new things on the stack, because we've checked everything before. In
1175 // this case, the lower bound of things to check remains the same.
1176 LocInfo.PopEpoch = PopEpoch;
1177 LocInfo.StackEpoch = StackEpoch;
1178 }
1179 if (!LocInfo.LastKillValid) {
1180 LocInfo.LastKill = VersionStack.size() - 1;
1181 LocInfo.LastKillValid = true;
1182 }
1183
1184 // At this point, we should have corrected last kill and LowerBound to be
1185 // in bounds.
1186 assert(LocInfo.LowerBound < VersionStack.size() &&
1187 "Lower bound out of range");
1188 assert(LocInfo.LastKill < VersionStack.size() &&
1189 "Last kill info out of range");
1190 // In any case, the new upper bound is the top of the stack.
1191 unsigned long UpperBound = VersionStack.size() - 1;
1192
1193 if (UpperBound - LocInfo.LowerBound > MaxCheckLimit) {
Daniel Berlin26fcea92016-08-02 20:02:21 +00001194 DEBUG(dbgs() << "MemorySSA skipping optimization of " << *MU << " ("
1195 << *(MU->getMemoryInst()) << ")"
1196 << " because there are " << UpperBound - LocInfo.LowerBound
1197 << " stores to disambiguate\n");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001198 // Because we did not walk, LastKill is no longer valid, as this may
1199 // have been a kill.
1200 LocInfo.LastKillValid = false;
1201 continue;
1202 }
1203 bool FoundClobberResult = false;
1204 while (UpperBound > LocInfo.LowerBound) {
1205 if (isa<MemoryPhi>(VersionStack[UpperBound])) {
1206 // For phis, use the walker, see where we ended up, go there
1207 Instruction *UseInst = MU->getMemoryInst();
1208 MemoryAccess *Result = Walker->getClobberingMemoryAccess(UseInst);
1209 // We are guaranteed to find it or something is wrong
1210 while (VersionStack[UpperBound] != Result) {
1211 assert(UpperBound != 0);
1212 --UpperBound;
1213 }
1214 FoundClobberResult = true;
1215 break;
1216 }
1217
1218 MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]);
Daniel Berlindf101192016-08-03 00:01:46 +00001219 // If the lifetime of the pointer ends at this instruction, it's live on
1220 // entry.
1221 if (!UseMLOC.IsCall && lifetimeEndsAt(MD, UseMLOC.getLoc(), *AA)) {
1222 // Reset UpperBound to liveOnEntryDef's place in the stack
1223 UpperBound = 0;
1224 FoundClobberResult = true;
1225 break;
1226 }
Daniel Berlindff31de2016-08-02 21:57:52 +00001227 if (instructionClobbersQuery(MD, MU, UseMLOC, *AA)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001228 FoundClobberResult = true;
1229 break;
1230 }
1231 --UpperBound;
1232 }
1233 // At the end of this loop, UpperBound is either a clobber, or lower bound
1234 // PHI walking may cause it to be < LowerBound, and in fact, < LastKill.
1235 if (FoundClobberResult || UpperBound < LocInfo.LastKill) {
Daniel Berlincd2deac2016-10-20 20:13:45 +00001236 MU->setDefiningAccess(VersionStack[UpperBound], true);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001237 // We were last killed now by where we got to
1238 LocInfo.LastKill = UpperBound;
1239 } else {
1240 // Otherwise, we checked all the new ones, and now we know we can get to
1241 // LastKill.
Daniel Berlincd2deac2016-10-20 20:13:45 +00001242 MU->setDefiningAccess(VersionStack[LocInfo.LastKill], true);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001243 }
1244 LocInfo.LowerBound = VersionStack.size() - 1;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001245 LocInfo.LowerBoundBlock = BB;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001246 }
1247}
1248
1249/// Optimize uses to point to their actual clobbering definitions.
1250void MemorySSA::OptimizeUses::optimizeUses() {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001251 SmallVector<MemoryAccess *, 16> VersionStack;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001252 DenseMap<MemoryLocOrCall, MemlocStackInfo> LocStackInfo;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001253 VersionStack.push_back(MSSA->getLiveOnEntryDef());
1254
1255 unsigned long StackEpoch = 1;
1256 unsigned long PopEpoch = 1;
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001257 // We perform a non-recursive top-down dominator tree walk.
Daniel Berlin7ac3d742016-08-05 22:09:14 +00001258 for (const auto *DomNode : depth_first(DT->getRootNode()))
1259 optimizeUsesInBlock(DomNode->getBlock(), StackEpoch, PopEpoch, VersionStack,
1260 LocStackInfo);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001261}
1262
Daniel Berlin3d512a22016-08-22 19:14:30 +00001263void MemorySSA::placePHINodes(
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001264 const SmallPtrSetImpl<BasicBlock *> &DefiningBlocks,
1265 const DenseMap<const BasicBlock *, unsigned int> &BBNumbers) {
Daniel Berlin3d512a22016-08-22 19:14:30 +00001266 // Determine where our MemoryPhi's should go
1267 ForwardIDFCalculator IDFs(*DT);
1268 IDFs.setDefiningBlocks(DefiningBlocks);
Daniel Berlin3d512a22016-08-22 19:14:30 +00001269 SmallVector<BasicBlock *, 32> IDFBlocks;
1270 IDFs.calculate(IDFBlocks);
1271
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001272 std::sort(IDFBlocks.begin(), IDFBlocks.end(),
1273 [&BBNumbers](const BasicBlock *A, const BasicBlock *B) {
1274 return BBNumbers.lookup(A) < BBNumbers.lookup(B);
1275 });
1276
Daniel Berlin3d512a22016-08-22 19:14:30 +00001277 // Now place MemoryPhi nodes.
Daniel Berlind602e042017-01-25 20:56:19 +00001278 for (auto &BB : IDFBlocks)
1279 createMemoryPhi(BB);
Daniel Berlin3d512a22016-08-22 19:14:30 +00001280}
1281
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001282void MemorySSA::buildMemorySSA() {
George Burgess IVe1100f52016-02-02 22:46:49 +00001283 // We create an access to represent "live on entry", for things like
1284 // arguments or users of globals, where the memory they use is defined before
1285 // the beginning of the function. We do not actually insert it into the IR.
1286 // We do not define a live on exit for the immediate uses, and thus our
1287 // semantics do *not* imply that something with no immediate uses can simply
1288 // be removed.
1289 BasicBlock &StartingPoint = F.getEntryBlock();
1290 LiveOnEntryDef = make_unique<MemoryDef>(F.getContext(), nullptr, nullptr,
1291 &StartingPoint, NextID++);
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001292 DenseMap<const BasicBlock *, unsigned int> BBNumbers;
1293 unsigned NextBBNum = 0;
George Burgess IVe1100f52016-02-02 22:46:49 +00001294
1295 // We maintain lists of memory accesses per-block, trading memory for time. We
1296 // could just look up the memory access for every possible instruction in the
1297 // stream.
1298 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001299 SmallPtrSet<BasicBlock *, 32> DefUseBlocks;
George Burgess IVe1100f52016-02-02 22:46:49 +00001300 // Go through each block, figure out where defs occur, and chain together all
1301 // the accesses.
1302 for (BasicBlock &B : F) {
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001303 BBNumbers[&B] = NextBBNum++;
Daniel Berlin7898ca62016-02-07 01:52:15 +00001304 bool InsertIntoDef = false;
Daniel Berlinada263d2016-06-20 20:21:33 +00001305 AccessList *Accesses = nullptr;
Daniel Berlind602e042017-01-25 20:56:19 +00001306 DefsList *Defs = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +00001307 for (Instruction &I : B) {
Peter Collingbourneffecb142016-05-26 01:19:17 +00001308 MemoryUseOrDef *MUD = createNewAccess(&I);
George Burgess IVb42b7622016-03-11 19:34:03 +00001309 if (!MUD)
George Burgess IVe1100f52016-02-02 22:46:49 +00001310 continue;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001311
George Burgess IVe1100f52016-02-02 22:46:49 +00001312 if (!Accesses)
1313 Accesses = getOrCreateAccessList(&B);
George Burgess IVb42b7622016-03-11 19:34:03 +00001314 Accesses->push_back(MUD);
Daniel Berlind602e042017-01-25 20:56:19 +00001315 if (isa<MemoryDef>(MUD)) {
1316 InsertIntoDef = true;
1317 if (!Defs)
1318 Defs = getOrCreateDefsList(&B);
1319 Defs->push_back(*MUD);
1320 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001321 }
Daniel Berlin7898ca62016-02-07 01:52:15 +00001322 if (InsertIntoDef)
1323 DefiningBlocks.insert(&B);
George Burgess IV3887a412016-03-21 21:25:39 +00001324 if (Accesses)
Daniel Berlin1b51a292016-02-07 01:52:19 +00001325 DefUseBlocks.insert(&B);
1326 }
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001327 placePHINodes(DefiningBlocks, BBNumbers);
George Burgess IVe1100f52016-02-02 22:46:49 +00001328
1329 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
1330 // filled in with all blocks.
1331 SmallPtrSet<BasicBlock *, 16> Visited;
1332 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1333
George Burgess IV5f308972016-07-19 01:29:15 +00001334 CachingWalker *Walker = getWalkerImpl();
1335
1336 // We're doing a batch of updates; don't drop useful caches between them.
1337 Walker->setAutoResetWalker(false);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001338 OptimizeUses(this, Walker, AA, DT).optimizeUses();
George Burgess IV5f308972016-07-19 01:29:15 +00001339 Walker->setAutoResetWalker(true);
1340 Walker->resetClobberWalker();
1341
George Burgess IVe1100f52016-02-02 22:46:49 +00001342 // Mark the uses in unreachable blocks as live on entry, so that they go
1343 // somewhere.
1344 for (auto &BB : F)
1345 if (!Visited.count(&BB))
1346 markUnreachableAsLiveOnEntry(&BB);
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001347}
George Burgess IVe1100f52016-02-02 22:46:49 +00001348
George Burgess IV5f308972016-07-19 01:29:15 +00001349MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
1350
1351MemorySSA::CachingWalker *MemorySSA::getWalkerImpl() {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001352 if (Walker)
1353 return Walker.get();
1354
1355 Walker = make_unique<CachingWalker>(this, AA, DT);
Geoff Berryb96d3b22016-06-01 21:30:40 +00001356 return Walker.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001357}
1358
Daniel Berlind602e042017-01-25 20:56:19 +00001359// This is a helper function used by the creation routines. It places NewAccess
1360// into the access and defs lists for a given basic block, at the given
1361// insertion point.
1362void MemorySSA::insertIntoListsForBlock(MemoryAccess *NewAccess,
1363 const BasicBlock *BB,
1364 InsertionPlace Point) {
1365 auto *Accesses = getOrCreateAccessList(BB);
1366 if (Point == Beginning) {
1367 // If it's a phi node, it goes first, otherwise, it goes after any phi
1368 // nodes.
1369 if (isa<MemoryPhi>(NewAccess)) {
1370 Accesses->push_front(NewAccess);
1371 auto *Defs = getOrCreateDefsList(BB);
1372 Defs->push_front(*NewAccess);
1373 } else {
1374 auto AI = find_if_not(
1375 *Accesses, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1376 Accesses->insert(AI, NewAccess);
1377 if (!isa<MemoryUse>(NewAccess)) {
1378 auto *Defs = getOrCreateDefsList(BB);
1379 auto DI = find_if_not(
1380 *Defs, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1381 Defs->insert(DI, *NewAccess);
1382 }
1383 }
1384 } else {
1385 Accesses->push_back(NewAccess);
1386 if (!isa<MemoryUse>(NewAccess)) {
1387 auto *Defs = getOrCreateDefsList(BB);
1388 Defs->push_back(*NewAccess);
1389 }
1390 }
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001391 BlockNumberingValid.erase(BB);
Daniel Berlind602e042017-01-25 20:56:19 +00001392}
1393
1394void MemorySSA::insertIntoListsBefore(MemoryAccess *What, const BasicBlock *BB,
1395 AccessList::iterator InsertPt) {
1396 auto *Accesses = getWritableBlockAccesses(BB);
1397 bool WasEnd = InsertPt == Accesses->end();
1398 Accesses->insert(AccessList::iterator(InsertPt), What);
1399 if (!isa<MemoryUse>(What)) {
1400 auto *Defs = getOrCreateDefsList(BB);
1401 // If we got asked to insert at the end, we have an easy job, just shove it
1402 // at the end. If we got asked to insert before an existing def, we also get
1403 // an terator. If we got asked to insert before a use, we have to hunt for
1404 // the next def.
1405 if (WasEnd) {
1406 Defs->push_back(*What);
1407 } else if (isa<MemoryDef>(InsertPt)) {
1408 Defs->insert(InsertPt->getDefsIterator(), *What);
1409 } else {
1410 while (InsertPt != Accesses->end() && !isa<MemoryDef>(InsertPt))
1411 ++InsertPt;
1412 // Either we found a def, or we are inserting at the end
1413 if (InsertPt == Accesses->end())
1414 Defs->push_back(*What);
1415 else
1416 Defs->insert(InsertPt->getDefsIterator(), *What);
1417 }
1418 }
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001419 BlockNumberingValid.erase(BB);
Daniel Berlind602e042017-01-25 20:56:19 +00001420}
1421
Daniel Berlin60ead052017-01-28 01:23:13 +00001422// Move What before Where in the IR. The end result is taht What will belong to
1423// the right lists and have the right Block set, but will not otherwise be
1424// correct. It will not have the right defining access, and if it is a def,
1425// things below it will not properly be updated.
1426void MemorySSA::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
1427 AccessList::iterator Where) {
1428 // Keep it in the lookup tables, remove from the lists
1429 removeFromLists(What, false);
1430 What->setBlock(BB);
1431 insertIntoListsBefore(What, BB, Where);
1432}
1433
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001434void MemorySSA::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
1435 InsertionPlace Point) {
1436 removeFromLists(What, false);
1437 What->setBlock(BB);
1438 insertIntoListsForBlock(What, BB, Point);
1439}
1440
Daniel Berlin14300262016-06-21 18:39:20 +00001441MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
1442 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
Daniel Berlin14300262016-06-21 18:39:20 +00001443 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001444 // Phi's always are placed at the front of the block.
Daniel Berlind602e042017-01-25 20:56:19 +00001445 insertIntoListsForBlock(Phi, BB, Beginning);
Daniel Berlin5130cc82016-07-31 21:08:20 +00001446 ValueToMemoryAccess[BB] = Phi;
Daniel Berlin14300262016-06-21 18:39:20 +00001447 return Phi;
1448}
1449
1450MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
1451 MemoryAccess *Definition) {
1452 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
1453 MemoryUseOrDef *NewAccess = createNewAccess(I);
1454 assert(
1455 NewAccess != nullptr &&
1456 "Tried to create a memory access for a non-memory touching instruction");
1457 NewAccess->setDefiningAccess(Definition);
1458 return NewAccess;
1459}
1460
Daniel Berlind952cea2017-04-07 01:28:36 +00001461// Return true if the instruction has ordering constraints.
1462// Note specifically that this only considers stores and loads
1463// because others are still considered ModRef by getModRefInfo.
1464static inline bool isOrdered(const Instruction *I) {
1465 if (auto *SI = dyn_cast<StoreInst>(I)) {
1466 if (!SI->isUnordered())
1467 return true;
1468 } else if (auto *LI = dyn_cast<LoadInst>(I)) {
1469 if (!LI->isUnordered())
1470 return true;
1471 }
1472 return false;
1473}
George Burgess IVe1100f52016-02-02 22:46:49 +00001474/// \brief Helper function to create new memory accesses
Peter Collingbourneffecb142016-05-26 01:19:17 +00001475MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I) {
Peter Collingbourneb9aa1f42016-05-26 04:58:46 +00001476 // The assume intrinsic has a control dependency which we model by claiming
1477 // that it writes arbitrarily. Ignore that fake memory dependency here.
1478 // FIXME: Replace this special casing with a more accurate modelling of
1479 // assume's control dependency.
1480 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1481 if (II->getIntrinsicID() == Intrinsic::assume)
1482 return nullptr;
1483
George Burgess IVe1100f52016-02-02 22:46:49 +00001484 // Find out what affect this instruction has on memory.
1485 ModRefInfo ModRef = AA->getModRefInfo(I);
Daniel Berlind952cea2017-04-07 01:28:36 +00001486 // The isOrdered check is used to ensure that volatiles end up as defs
1487 // (atomics end up as ModRef right now anyway). Until we separate the
1488 // ordering chain from the memory chain, this enables people to see at least
1489 // some relative ordering to volatiles. Note that getClobberingMemoryAccess
1490 // will still give an answer that bypasses other volatile loads. TODO:
1491 // Separate memory aliasing and ordering into two different chains so that we
1492 // can precisely represent both "what memory will this read/write/is clobbered
1493 // by" and "what instructions can I move this past".
1494 bool Def = bool(ModRef & MRI_Mod) || isOrdered(I);
George Burgess IVe1100f52016-02-02 22:46:49 +00001495 bool Use = bool(ModRef & MRI_Ref);
1496
1497 // It's possible for an instruction to not modify memory at all. During
1498 // construction, we ignore them.
Peter Collingbourneffecb142016-05-26 01:19:17 +00001499 if (!Def && !Use)
George Burgess IVe1100f52016-02-02 22:46:49 +00001500 return nullptr;
1501
1502 assert((Def || Use) &&
1503 "Trying to create a memory access with a non-memory instruction");
1504
George Burgess IVb42b7622016-03-11 19:34:03 +00001505 MemoryUseOrDef *MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001506 if (Def)
George Burgess IVb42b7622016-03-11 19:34:03 +00001507 MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
George Burgess IVe1100f52016-02-02 22:46:49 +00001508 else
George Burgess IVb42b7622016-03-11 19:34:03 +00001509 MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
Daniel Berlin5130cc82016-07-31 21:08:20 +00001510 ValueToMemoryAccess[I] = MUD;
George Burgess IVb42b7622016-03-11 19:34:03 +00001511 return MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001512}
1513
George Burgess IVe1100f52016-02-02 22:46:49 +00001514/// \brief Returns true if \p Replacer dominates \p Replacee .
1515bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
1516 const MemoryAccess *Replacee) const {
1517 if (isa<MemoryUseOrDef>(Replacee))
1518 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
1519 const auto *MP = cast<MemoryPhi>(Replacee);
1520 // For a phi node, the use occurs in the predecessor block of the phi node.
1521 // Since we may occur multiple times in the phi node, we have to check each
1522 // operand to ensure Replacer dominates each operand where Replacee occurs.
1523 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +00001524 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +00001525 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
1526 return false;
1527 }
1528 return true;
1529}
1530
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001531/// \brief Properly remove \p MA from all of MemorySSA's lookup tables.
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001532void MemorySSA::removeFromLookups(MemoryAccess *MA) {
1533 assert(MA->use_empty() &&
1534 "Trying to remove memory access that still has uses");
Daniel Berlin5c46b942016-07-19 22:49:43 +00001535 BlockNumbering.erase(MA);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001536 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA))
1537 MUD->setDefiningAccess(nullptr);
1538 // Invalidate our walker's cache if necessary
1539 if (!isa<MemoryUse>(MA))
1540 Walker->invalidateInfo(MA);
1541 // The call below to erase will destroy MA, so we can't change the order we
1542 // are doing things here
1543 Value *MemoryInst;
1544 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
1545 MemoryInst = MUD->getMemoryInst();
1546 } else {
1547 MemoryInst = MA->getBlock();
1548 }
Daniel Berlin5130cc82016-07-31 21:08:20 +00001549 auto VMA = ValueToMemoryAccess.find(MemoryInst);
1550 if (VMA->second == MA)
1551 ValueToMemoryAccess.erase(VMA);
Daniel Berlin60ead052017-01-28 01:23:13 +00001552}
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001553
Daniel Berlin60ead052017-01-28 01:23:13 +00001554/// \brief Properly remove \p MA from all of MemorySSA's lists.
1555///
1556/// Because of the way the intrusive list and use lists work, it is important to
1557/// do removal in the right order.
1558/// ShouldDelete defaults to true, and will cause the memory access to also be
1559/// deleted, not just removed.
1560void MemorySSA::removeFromLists(MemoryAccess *MA, bool ShouldDelete) {
Daniel Berlind602e042017-01-25 20:56:19 +00001561 // The access list owns the reference, so we erase it from the non-owning list
1562 // first.
1563 if (!isa<MemoryUse>(MA)) {
1564 auto DefsIt = PerBlockDefs.find(MA->getBlock());
1565 std::unique_ptr<DefsList> &Defs = DefsIt->second;
1566 Defs->remove(*MA);
1567 if (Defs->empty())
1568 PerBlockDefs.erase(DefsIt);
1569 }
1570
Daniel Berlin60ead052017-01-28 01:23:13 +00001571 // The erase call here will delete it. If we don't want it deleted, we call
1572 // remove instead.
George Burgess IVe0e6e482016-03-02 02:35:04 +00001573 auto AccessIt = PerBlockAccesses.find(MA->getBlock());
Daniel Berlinada263d2016-06-20 20:21:33 +00001574 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
Daniel Berlin60ead052017-01-28 01:23:13 +00001575 if (ShouldDelete)
1576 Accesses->erase(MA);
1577 else
1578 Accesses->remove(MA);
1579
George Burgess IVe0e6e482016-03-02 02:35:04 +00001580 if (Accesses->empty())
1581 PerBlockAccesses.erase(AccessIt);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001582}
1583
George Burgess IVe1100f52016-02-02 22:46:49 +00001584void MemorySSA::print(raw_ostream &OS) const {
1585 MemorySSAAnnotatedWriter Writer(this);
1586 F.print(OS, &Writer);
1587}
1588
Matthias Braun8c209aa2017-01-28 02:02:38 +00001589#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Daniel Berlin78cbd282017-02-20 22:26:03 +00001590LLVM_DUMP_METHOD void MemorySSA::dump() const { print(dbgs()); }
Matthias Braun8c209aa2017-01-28 02:02:38 +00001591#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001592
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001593void MemorySSA::verifyMemorySSA() const {
1594 verifyDefUses(F);
1595 verifyDomination(F);
Daniel Berlin14300262016-06-21 18:39:20 +00001596 verifyOrdering(F);
Geoff Berrycdf53332016-08-08 17:52:01 +00001597 Walker->verify(this);
Daniel Berlin14300262016-06-21 18:39:20 +00001598}
1599
1600/// \brief Verify that the order and existence of MemoryAccesses matches the
1601/// order and existence of memory affecting instructions.
1602void MemorySSA::verifyOrdering(Function &F) const {
1603 // Walk all the blocks, comparing what the lookups think and what the access
1604 // lists think, as well as the order in the blocks vs the order in the access
1605 // lists.
1606 SmallVector<MemoryAccess *, 32> ActualAccesses;
Daniel Berlind602e042017-01-25 20:56:19 +00001607 SmallVector<MemoryAccess *, 32> ActualDefs;
Daniel Berlin14300262016-06-21 18:39:20 +00001608 for (BasicBlock &B : F) {
1609 const AccessList *AL = getBlockAccesses(&B);
Daniel Berlind602e042017-01-25 20:56:19 +00001610 const auto *DL = getBlockDefs(&B);
Daniel Berlin14300262016-06-21 18:39:20 +00001611 MemoryAccess *Phi = getMemoryAccess(&B);
Daniel Berlind602e042017-01-25 20:56:19 +00001612 if (Phi) {
Daniel Berlin14300262016-06-21 18:39:20 +00001613 ActualAccesses.push_back(Phi);
Daniel Berlind602e042017-01-25 20:56:19 +00001614 ActualDefs.push_back(Phi);
1615 }
1616
Daniel Berlin14300262016-06-21 18:39:20 +00001617 for (Instruction &I : B) {
1618 MemoryAccess *MA = getMemoryAccess(&I);
Daniel Berlind602e042017-01-25 20:56:19 +00001619 assert((!MA || (AL && (isa<MemoryUse>(MA) || DL))) &&
1620 "We have memory affecting instructions "
1621 "in this block but they are not in the "
1622 "access list or defs list");
1623 if (MA) {
Daniel Berlin14300262016-06-21 18:39:20 +00001624 ActualAccesses.push_back(MA);
Daniel Berlind602e042017-01-25 20:56:19 +00001625 if (isa<MemoryDef>(MA))
1626 ActualDefs.push_back(MA);
1627 }
Daniel Berlin14300262016-06-21 18:39:20 +00001628 }
1629 // Either we hit the assert, really have no accesses, or we have both
Daniel Berlind602e042017-01-25 20:56:19 +00001630 // accesses and an access list.
1631 // Same with defs.
1632 if (!AL && !DL)
Daniel Berlin14300262016-06-21 18:39:20 +00001633 continue;
1634 assert(AL->size() == ActualAccesses.size() &&
1635 "We don't have the same number of accesses in the block as on the "
1636 "access list");
Davide Italiano6c77de02017-01-30 03:16:43 +00001637 assert((DL || ActualDefs.size() == 0) &&
1638 "Either we should have a defs list, or we should have no defs");
Daniel Berlind602e042017-01-25 20:56:19 +00001639 assert((!DL || DL->size() == ActualDefs.size()) &&
1640 "We don't have the same number of defs in the block as on the "
1641 "def list");
Daniel Berlin14300262016-06-21 18:39:20 +00001642 auto ALI = AL->begin();
1643 auto AAI = ActualAccesses.begin();
1644 while (ALI != AL->end() && AAI != ActualAccesses.end()) {
1645 assert(&*ALI == *AAI && "Not the same accesses in the same order");
1646 ++ALI;
1647 ++AAI;
1648 }
1649 ActualAccesses.clear();
Daniel Berlind602e042017-01-25 20:56:19 +00001650 if (DL) {
1651 auto DLI = DL->begin();
1652 auto ADI = ActualDefs.begin();
1653 while (DLI != DL->end() && ADI != ActualDefs.end()) {
1654 assert(&*DLI == *ADI && "Not the same defs in the same order");
1655 ++DLI;
1656 ++ADI;
1657 }
1658 }
1659 ActualDefs.clear();
Daniel Berlin14300262016-06-21 18:39:20 +00001660 }
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001661}
1662
George Burgess IVe1100f52016-02-02 22:46:49 +00001663/// \brief Verify the domination properties of MemorySSA by checking that each
1664/// definition dominates all of its uses.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001665void MemorySSA::verifyDomination(Function &F) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001666#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001667 for (BasicBlock &B : F) {
1668 // Phi nodes are attached to basic blocks
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001669 if (MemoryPhi *MP = getMemoryAccess(&B))
1670 for (const Use &U : MP->uses())
1671 assert(dominates(MP, U) && "Memory PHI does not dominate it's uses");
Daniel Berlin7af95872016-08-05 21:47:20 +00001672
George Burgess IVe1100f52016-02-02 22:46:49 +00001673 for (Instruction &I : B) {
1674 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
1675 if (!MD)
1676 continue;
1677
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001678 for (const Use &U : MD->uses())
1679 assert(dominates(MD, U) && "Memory Def does not dominate it's uses");
George Burgess IVe1100f52016-02-02 22:46:49 +00001680 }
1681 }
Daniel Berlin7af95872016-08-05 21:47:20 +00001682#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001683}
1684
1685/// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use
1686/// appears in the use list of \p Def.
Daniel Berlin7af95872016-08-05 21:47:20 +00001687
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001688void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001689#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001690 // The live on entry use may cause us to get a NULL def here
Daniel Berlin7af95872016-08-05 21:47:20 +00001691 if (!Def)
1692 assert(isLiveOnEntryDef(Use) &&
1693 "Null def but use not point to live on entry def");
1694 else
Daniel Berlinda2f38e2016-08-11 21:26:50 +00001695 assert(is_contained(Def->users(), Use) &&
Daniel Berlin7af95872016-08-05 21:47:20 +00001696 "Did not find use in def's use list");
1697#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001698}
1699
1700/// \brief Verify the immediate use information, by walking all the memory
1701/// accesses and verifying that, for each use, it appears in the
1702/// appropriate def's use list
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001703void MemorySSA::verifyDefUses(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001704 for (BasicBlock &B : F) {
1705 // Phi nodes are attached to basic blocks
Daniel Berlin14300262016-06-21 18:39:20 +00001706 if (MemoryPhi *Phi = getMemoryAccess(&B)) {
David Majnemer580e7542016-06-25 00:04:06 +00001707 assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
1708 pred_begin(&B), pred_end(&B))) &&
Daniel Berlin14300262016-06-21 18:39:20 +00001709 "Incomplete MemoryPhi Node");
George Burgess IVe1100f52016-02-02 22:46:49 +00001710 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
1711 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
Daniel Berlin14300262016-06-21 18:39:20 +00001712 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001713
1714 for (Instruction &I : B) {
George Burgess IV66837ab2016-11-01 21:17:46 +00001715 if (MemoryUseOrDef *MA = getMemoryAccess(&I)) {
1716 verifyUseInDefs(MA->getDefiningAccess(), MA);
George Burgess IVe1100f52016-02-02 22:46:49 +00001717 }
1718 }
1719 }
1720}
1721
George Burgess IV66837ab2016-11-01 21:17:46 +00001722MemoryUseOrDef *MemorySSA::getMemoryAccess(const Instruction *I) const {
1723 return cast_or_null<MemoryUseOrDef>(ValueToMemoryAccess.lookup(I));
George Burgess IVe1100f52016-02-02 22:46:49 +00001724}
1725
1726MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const {
George Burgess IV66837ab2016-11-01 21:17:46 +00001727 return cast_or_null<MemoryPhi>(ValueToMemoryAccess.lookup(cast<Value>(BB)));
George Burgess IVe1100f52016-02-02 22:46:49 +00001728}
1729
Daniel Berlin5c46b942016-07-19 22:49:43 +00001730/// Perform a local numbering on blocks so that instruction ordering can be
1731/// determined in constant time.
1732/// TODO: We currently just number in order. If we numbered by N, we could
1733/// allow at least N-1 sequences of insertBefore or insertAfter (and at least
1734/// log2(N) sequences of mixed before and after) without needing to invalidate
1735/// the numbering.
1736void MemorySSA::renumberBlock(const BasicBlock *B) const {
1737 // The pre-increment ensures the numbers really start at 1.
1738 unsigned long CurrentNumber = 0;
1739 const AccessList *AL = getBlockAccesses(B);
1740 assert(AL != nullptr && "Asking to renumber an empty block");
1741 for (const auto &I : *AL)
1742 BlockNumbering[&I] = ++CurrentNumber;
1743 BlockNumberingValid.insert(B);
1744}
1745
George Burgess IVe1100f52016-02-02 22:46:49 +00001746/// \brief Determine, for two memory accesses in the same block,
1747/// whether \p Dominator dominates \p Dominatee.
1748/// \returns True if \p Dominator dominates \p Dominatee.
1749bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
1750 const MemoryAccess *Dominatee) const {
Sebastian Pope1f60b12016-06-10 21:36:41 +00001751
Daniel Berlin5c46b942016-07-19 22:49:43 +00001752 const BasicBlock *DominatorBlock = Dominator->getBlock();
Daniel Berlin5c46b942016-07-19 22:49:43 +00001753
Daniel Berlin19860302016-07-19 23:08:08 +00001754 assert((DominatorBlock == Dominatee->getBlock()) &&
Daniel Berlin5c46b942016-07-19 22:49:43 +00001755 "Asking for local domination when accesses are in different blocks!");
Sebastian Pope1f60b12016-06-10 21:36:41 +00001756 // A node dominates itself.
1757 if (Dominatee == Dominator)
1758 return true;
1759
1760 // When Dominatee is defined on function entry, it is not dominated by another
1761 // memory access.
1762 if (isLiveOnEntryDef(Dominatee))
1763 return false;
1764
1765 // When Dominator is defined on function entry, it dominates the other memory
1766 // access.
1767 if (isLiveOnEntryDef(Dominator))
1768 return true;
1769
Daniel Berlin5c46b942016-07-19 22:49:43 +00001770 if (!BlockNumberingValid.count(DominatorBlock))
1771 renumberBlock(DominatorBlock);
George Burgess IVe1100f52016-02-02 22:46:49 +00001772
Daniel Berlin5c46b942016-07-19 22:49:43 +00001773 unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
1774 // All numbers start with 1
1775 assert(DominatorNum != 0 && "Block was not numbered properly");
1776 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
1777 assert(DominateeNum != 0 && "Block was not numbered properly");
1778 return DominatorNum < DominateeNum;
George Burgess IVe1100f52016-02-02 22:46:49 +00001779}
1780
George Burgess IV5f308972016-07-19 01:29:15 +00001781bool MemorySSA::dominates(const MemoryAccess *Dominator,
1782 const MemoryAccess *Dominatee) const {
1783 if (Dominator == Dominatee)
1784 return true;
1785
1786 if (isLiveOnEntryDef(Dominatee))
1787 return false;
1788
1789 if (Dominator->getBlock() != Dominatee->getBlock())
1790 return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
1791 return locallyDominates(Dominator, Dominatee);
1792}
1793
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001794bool MemorySSA::dominates(const MemoryAccess *Dominator,
1795 const Use &Dominatee) const {
1796 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Dominatee.getUser())) {
1797 BasicBlock *UseBB = MP->getIncomingBlock(Dominatee);
1798 // The def must dominate the incoming block of the phi.
1799 if (UseBB != Dominator->getBlock())
1800 return DT->dominates(Dominator->getBlock(), UseBB);
1801 // If the UseBB and the DefBB are the same, compare locally.
1802 return locallyDominates(Dominator, cast<MemoryAccess>(Dominatee));
1803 }
1804 // If it's not a PHI node use, the normal dominates can already handle it.
1805 return dominates(Dominator, cast<MemoryAccess>(Dominatee.getUser()));
1806}
1807
George Burgess IVe1100f52016-02-02 22:46:49 +00001808const static char LiveOnEntryStr[] = "liveOnEntry";
1809
1810void 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
1847MemoryAccess::~MemoryAccess() {}
1848
1849void MemoryUse::print(raw_ostream &OS) const {
1850 MemoryAccess *UO = getDefiningAccess();
1851 OS << "MemoryUse(";
1852 if (UO && UO->getID())
1853 OS << UO->getID();
1854 else
1855 OS << LiveOnEntryStr;
1856 OS << ')';
1857}
1858
1859void MemoryAccess::dump() const {
Daniel Berlin78cbd282017-02-20 22:26:03 +00001860// Cannot completely remove virtual function even in release mode.
Matthias Braun8c209aa2017-01-28 02:02:38 +00001861#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
George Burgess IVe1100f52016-02-02 22:46:49 +00001862 print(dbgs());
1863 dbgs() << "\n";
Matthias Braun8c209aa2017-01-28 02:02:38 +00001864#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001865}
1866
Chad Rosier232e29e2016-07-06 21:20:47 +00001867char MemorySSAPrinterLegacyPass::ID = 0;
1868
1869MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) {
1870 initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
1871}
1872
1873void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
1874 AU.setPreservesAll();
1875 AU.addRequired<MemorySSAWrapperPass>();
1876 AU.addPreserved<MemorySSAWrapperPass>();
1877}
1878
1879bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) {
1880 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
1881 MSSA.print(dbgs());
1882 if (VerifyMemorySSA)
1883 MSSA.verifyMemorySSA();
1884 return false;
1885}
1886
Chandler Carruthdab4eae2016-11-23 17:53:26 +00001887AnalysisKey MemorySSAAnalysis::Key;
George Burgess IVe1100f52016-02-02 22:46:49 +00001888
Daniel Berlin1e98c042016-09-26 17:22:54 +00001889MemorySSAAnalysis::Result MemorySSAAnalysis::run(Function &F,
1890 FunctionAnalysisManager &AM) {
Geoff Berryb96d3b22016-06-01 21:30:40 +00001891 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1892 auto &AA = AM.getResult<AAManager>(F);
Geoff Berry290a13e2016-08-08 18:27:22 +00001893 return MemorySSAAnalysis::Result(make_unique<MemorySSA>(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00001894}
1895
Geoff Berryb96d3b22016-06-01 21:30:40 +00001896PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
1897 FunctionAnalysisManager &AM) {
1898 OS << "MemorySSA for function: " << F.getName() << "\n";
Geoff Berry290a13e2016-08-08 18:27:22 +00001899 AM.getResult<MemorySSAAnalysis>(F).getMSSA().print(OS);
Geoff Berryb96d3b22016-06-01 21:30:40 +00001900
1901 return PreservedAnalyses::all();
George Burgess IVe1100f52016-02-02 22:46:49 +00001902}
1903
Geoff Berryb96d3b22016-06-01 21:30:40 +00001904PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
1905 FunctionAnalysisManager &AM) {
Geoff Berry290a13e2016-08-08 18:27:22 +00001906 AM.getResult<MemorySSAAnalysis>(F).getMSSA().verifyMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001907
1908 return PreservedAnalyses::all();
1909}
1910
1911char MemorySSAWrapperPass::ID = 0;
1912
1913MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
1914 initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
1915}
1916
1917void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
1918
1919void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001920 AU.setPreservesAll();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001921 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
1922 AU.addRequiredTransitive<AAResultsWrapperPass>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001923}
1924
Geoff Berryb96d3b22016-06-01 21:30:40 +00001925bool MemorySSAWrapperPass::runOnFunction(Function &F) {
1926 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1927 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1928 MSSA.reset(new MemorySSA(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00001929 return false;
1930}
1931
Geoff Berryb96d3b22016-06-01 21:30:40 +00001932void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); }
George Burgess IVe1100f52016-02-02 22:46:49 +00001933
Geoff Berryb96d3b22016-06-01 21:30:40 +00001934void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001935 MSSA->print(OS);
1936}
1937
George Burgess IVe1100f52016-02-02 22:46:49 +00001938MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
1939
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001940MemorySSA::CachingWalker::CachingWalker(MemorySSA *M, AliasAnalysis *A,
1941 DominatorTree *D)
Daniel Berlind7a7ae02017-04-05 19:01:58 +00001942 : MemorySSAWalker(M), Walker(*M, *A, *D), AutoResetWalker(true) {}
George Burgess IVe1100f52016-02-02 22:46:49 +00001943
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001944MemorySSA::CachingWalker::~CachingWalker() {}
George Burgess IVe1100f52016-02-02 22:46:49 +00001945
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001946void MemorySSA::CachingWalker::invalidateInfo(MemoryAccess *MA) {
Daniel Berlind7a7ae02017-04-05 19:01:58 +00001947 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1948 MUD->resetOptimized();
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001949}
1950
George Burgess IVe1100f52016-02-02 22:46:49 +00001951/// \brief Walk the use-def chains starting at \p MA and find
1952/// the MemoryAccess that actually clobbers Loc.
1953///
1954/// \returns our clobbering memory access
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001955MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
1956 MemoryAccess *StartingAccess, UpwardsMemoryQuery &Q) {
George Burgess IV5f308972016-07-19 01:29:15 +00001957 MemoryAccess *New = Walker.findClobber(StartingAccess, Q);
1958#ifdef EXPENSIVE_CHECKS
Daniel Berlind7a7ae02017-04-05 19:01:58 +00001959 MemoryAccess *NewNoCache = Walker.findClobber(StartingAccess, Q);
George Burgess IV5f308972016-07-19 01:29:15 +00001960 assert(NewNoCache == New && "Cache made us hand back a different result?");
1961#endif
1962 if (AutoResetWalker)
1963 resetClobberWalker();
1964 return New;
George Burgess IVe1100f52016-02-02 22:46:49 +00001965}
1966
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001967MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
George Burgess IV013fd732016-10-28 19:22:46 +00001968 MemoryAccess *StartingAccess, const MemoryLocation &Loc) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001969 if (isa<MemoryPhi>(StartingAccess))
1970 return StartingAccess;
1971
1972 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
1973 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
1974 return StartingUseOrDef;
1975
1976 Instruction *I = StartingUseOrDef->getMemoryInst();
1977
1978 // Conservatively, fences are always clobbers, so don't perform the walk if we
1979 // hit a fence.
David Majnemera940f362016-07-15 17:19:24 +00001980 if (!ImmutableCallSite(I) && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00001981 return StartingUseOrDef;
1982
1983 UpwardsMemoryQuery Q;
1984 Q.OriginalAccess = StartingUseOrDef;
1985 Q.StartingLoc = Loc;
George Burgess IV5f308972016-07-19 01:29:15 +00001986 Q.Inst = I;
George Burgess IVe1100f52016-02-02 22:46:49 +00001987 Q.IsCall = false;
George Burgess IVe1100f52016-02-02 22:46:49 +00001988
George Burgess IVe1100f52016-02-02 22:46:49 +00001989 // Unlike the other function, do not walk to the def of a def, because we are
1990 // handed something we already believe is the clobbering access.
1991 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
1992 ? StartingUseOrDef->getDefiningAccess()
1993 : StartingUseOrDef;
1994
1995 MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00001996 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
1997 DEBUG(dbgs() << *StartingUseOrDef << "\n");
1998 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
1999 DEBUG(dbgs() << *Clobber << "\n");
2000 return Clobber;
2001}
2002
2003MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002004MemorySSA::CachingWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
2005 auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
2006 // If this is a MemoryPhi, we can't do anything.
2007 if (!StartingAccess)
2008 return MA;
George Burgess IVe1100f52016-02-02 22:46:49 +00002009
Daniel Berlincd2deac2016-10-20 20:13:45 +00002010 // If this is an already optimized use or def, return the optimized result.
2011 // Note: Currently, we do not store the optimized def result because we'd need
2012 // a separate field, since we can't use it as the defining access.
Daniel Berline33bc312017-04-04 23:43:10 +00002013 if (auto *MUD = dyn_cast<MemoryUseOrDef>(StartingAccess))
2014 if (MUD->isOptimized())
2015 return MUD->getOptimized();
Daniel Berlincd2deac2016-10-20 20:13:45 +00002016
George Burgess IV400ae402016-07-20 19:51:34 +00002017 const Instruction *I = StartingAccess->getMemoryInst();
George Burgess IV5f308972016-07-19 01:29:15 +00002018 UpwardsMemoryQuery Q(I, StartingAccess);
David Majnemera940f362016-07-15 17:19:24 +00002019 // We can't sanely do anything with a fences, they conservatively
George Burgess IVe1100f52016-02-02 22:46:49 +00002020 // clobber all memory, and have no locations to get pointers from to
David Majnemera940f362016-07-15 17:19:24 +00002021 // try to disambiguate.
George Burgess IV5f308972016-07-19 01:29:15 +00002022 if (!Q.IsCall && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002023 return StartingAccess;
2024
George Burgess IV024f3d22016-08-03 19:57:02 +00002025 if (isUseTriviallyOptimizableToLiveOnEntry(*MSSA->AA, I)) {
2026 MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef();
Daniel Berline33bc312017-04-04 23:43:10 +00002027 if (auto *MUD = dyn_cast<MemoryUseOrDef>(StartingAccess))
2028 MUD->setOptimized(LiveOnEntry);
George Burgess IV024f3d22016-08-03 19:57:02 +00002029 return LiveOnEntry;
2030 }
2031
George Burgess IVe1100f52016-02-02 22:46:49 +00002032 // Start with the thing we already think clobbers this location
2033 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
2034
2035 // At this point, DefiningAccess may be the live on entry def.
2036 // If it is, we will not get a better result.
2037 if (MSSA->isLiveOnEntryDef(DefiningAccess))
2038 return DefiningAccess;
2039
2040 MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00002041 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2042 DEBUG(dbgs() << *DefiningAccess << "\n");
2043 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2044 DEBUG(dbgs() << *Result << "\n");
Daniel Berline33bc312017-04-04 23:43:10 +00002045 if (auto *MUD = dyn_cast<MemoryUseOrDef>(StartingAccess))
2046 MUD->setOptimized(Result);
George Burgess IVe1100f52016-02-02 22:46:49 +00002047
2048 return Result;
2049}
2050
George Burgess IVe1100f52016-02-02 22:46:49 +00002051MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002052DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002053 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
2054 return Use->getDefiningAccess();
2055 return MA;
2056}
2057
2058MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
George Burgess IV013fd732016-10-28 19:22:46 +00002059 MemoryAccess *StartingAccess, const MemoryLocation &) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002060 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
2061 return Use->getDefiningAccess();
2062 return StartingAccess;
2063}
George Burgess IV5f308972016-07-19 01:29:15 +00002064} // namespace llvm