blob: c3c966e22ea864fa6ef8f277c38c32a51f41dc2b [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;
47STATISTIC(NumClobberCacheLookups, "Number of Memory SSA version cache lookups");
48STATISTIC(NumClobberCacheHits, "Number of Memory SSA version cache hits");
49STATISTIC(NumClobberCacheInserts, "Number of MemorySSA version cache inserts");
Geoff Berryb96d3b22016-06-01 21:30:40 +000050
Geoff Berryefb0dd12016-06-14 21:19:40 +000051INITIALIZE_PASS_BEGIN(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
Geoff Berryb96d3b22016-06-01 21:30:40 +000052 true)
George Burgess IVe1100f52016-02-02 22:46:49 +000053INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
54INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Geoff Berryefb0dd12016-06-14 21:19:40 +000055INITIALIZE_PASS_END(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false,
56 true)
George Burgess IVe1100f52016-02-02 22:46:49 +000057
Chad Rosier232e29e2016-07-06 21:20:47 +000058INITIALIZE_PASS_BEGIN(MemorySSAPrinterLegacyPass, "print-memoryssa",
59 "Memory SSA Printer", false, false)
60INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
61INITIALIZE_PASS_END(MemorySSAPrinterLegacyPass, "print-memoryssa",
62 "Memory SSA Printer", false, false)
63
Daniel Berlinc43aa5a2016-08-02 16:24:03 +000064static cl::opt<unsigned> MaxCheckLimit(
65 "memssa-check-limit", cl::Hidden, cl::init(100),
66 cl::desc("The maximum number of stores/phis MemorySSA"
67 "will consider trying to walk past (default = 100)"));
68
Chad Rosier232e29e2016-07-06 21:20:47 +000069static cl::opt<bool>
70 VerifyMemorySSA("verify-memoryssa", cl::init(false), cl::Hidden,
71 cl::desc("Verify MemorySSA in legacy printer pass."));
72
George Burgess IVe1100f52016-02-02 22:46:49 +000073namespace llvm {
George Burgess IVe1100f52016-02-02 22:46:49 +000074/// \brief An assembly annotator class to print Memory SSA information in
75/// comments.
76class MemorySSAAnnotatedWriter : public AssemblyAnnotationWriter {
77 friend class MemorySSA;
78 const MemorySSA *MSSA;
79
80public:
81 MemorySSAAnnotatedWriter(const MemorySSA *M) : MSSA(M) {}
82
83 virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
84 formatted_raw_ostream &OS) {
85 if (MemoryAccess *MA = MSSA->getMemoryAccess(BB))
86 OS << "; " << *MA << "\n";
87 }
88
89 virtual void emitInstructionAnnot(const Instruction *I,
90 formatted_raw_ostream &OS) {
91 if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
92 OS << "; " << *MA << "\n";
93 }
94};
George Burgess IV5f308972016-07-19 01:29:15 +000095}
George Burgess IVfd1f2f82016-06-24 21:02:12 +000096
George Burgess IV5f308972016-07-19 01:29:15 +000097namespace {
Daniel Berlindff31de2016-08-02 21:57:52 +000098/// Our current alias analysis API differentiates heavily between calls and
99/// non-calls, and functions called on one usually assert on the other.
100/// This class encapsulates the distinction to simplify other code that wants
101/// "Memory affecting instructions and related data" to use as a key.
102/// For example, this class is used as a densemap key in the use optimizer.
103class MemoryLocOrCall {
104public:
105 MemoryLocOrCall() : IsCall(false) {}
106 MemoryLocOrCall(MemoryUseOrDef *MUD)
107 : MemoryLocOrCall(MUD->getMemoryInst()) {}
108
109 MemoryLocOrCall(Instruction *Inst) {
110 if (ImmutableCallSite(Inst)) {
111 IsCall = true;
112 CS = ImmutableCallSite(Inst);
113 } else {
114 IsCall = false;
115 // There is no such thing as a memorylocation for a fence inst, and it is
116 // unique in that regard.
117 if (!isa<FenceInst>(Inst))
118 Loc = MemoryLocation::get(Inst);
119 }
120 }
121
122 explicit MemoryLocOrCall(const MemoryLocation &Loc)
123 : IsCall(false), Loc(Loc) {}
124
125 bool IsCall;
126 ImmutableCallSite getCS() const {
127 assert(IsCall);
128 return CS;
129 }
130 MemoryLocation getLoc() const {
131 assert(!IsCall);
132 return Loc;
133 }
134
135 bool operator==(const MemoryLocOrCall &Other) const {
136 if (IsCall != Other.IsCall)
137 return false;
138
139 if (IsCall)
140 return CS.getCalledValue() == Other.CS.getCalledValue();
141 return Loc == Other.Loc;
142 }
143
144private:
145 // FIXME: MSVC 2013 does not properly implement C++11 union rules, once we
146 // require newer versions, this should be made an anonymous union again.
147 ImmutableCallSite CS;
148 MemoryLocation Loc;
149};
150}
151
152namespace llvm {
153template <> struct DenseMapInfo<MemoryLocOrCall> {
154 static inline MemoryLocOrCall getEmptyKey() {
155 return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getEmptyKey());
156 }
157 static inline MemoryLocOrCall getTombstoneKey() {
158 return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getTombstoneKey());
159 }
160 static unsigned getHashValue(const MemoryLocOrCall &MLOC) {
161 if (MLOC.IsCall)
162 return hash_combine(MLOC.IsCall,
163 DenseMapInfo<const Value *>::getHashValue(
164 MLOC.getCS().getCalledValue()));
165 return hash_combine(
166 MLOC.IsCall, DenseMapInfo<MemoryLocation>::getHashValue(MLOC.getLoc()));
167 }
168 static bool isEqual(const MemoryLocOrCall &LHS, const MemoryLocOrCall &RHS) {
169 return LHS == RHS;
170 }
171};
172}
George Burgess IV024f3d22016-08-03 19:57:02 +0000173
Daniel Berlindff31de2016-08-02 21:57:52 +0000174namespace {
George Burgess IV5f308972016-07-19 01:29:15 +0000175struct UpwardsMemoryQuery {
176 // True if our original query started off as a call
177 bool IsCall;
178 // The pointer location we started the query with. This will be empty if
179 // IsCall is true.
180 MemoryLocation StartingLoc;
181 // This is the instruction we were querying about.
182 const Instruction *Inst;
183 // The MemoryAccess we actually got called with, used to test local domination
184 const MemoryAccess *OriginalAccess;
185
186 UpwardsMemoryQuery()
187 : IsCall(false), Inst(nullptr), OriginalAccess(nullptr) {}
188
189 UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access)
190 : IsCall(ImmutableCallSite(Inst)), Inst(Inst), OriginalAccess(Access) {
191 if (!IsCall)
192 StartingLoc = MemoryLocation::get(Inst);
193 }
194};
195
Daniel Berlindf101192016-08-03 00:01:46 +0000196static bool lifetimeEndsAt(MemoryDef *MD, const MemoryLocation &Loc,
197 AliasAnalysis &AA) {
198 Instruction *Inst = MD->getMemoryInst();
199 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
200 switch (II->getIntrinsicID()) {
George Burgess IVf7672852016-08-03 19:59:11 +0000201 case Intrinsic::lifetime_start:
202 case Intrinsic::lifetime_end:
203 return AA.isMustAlias(MemoryLocation(II->getArgOperand(1)), Loc);
Daniel Berlindf101192016-08-03 00:01:46 +0000204 default:
205 return false;
206 }
207 }
208 return false;
209}
210
George Burgess IVf7672852016-08-03 19:59:11 +0000211enum class Reorderability { Always, IfNoAlias, Never };
George Burgess IV82e355c2016-08-03 19:39:54 +0000212
213/// This does one-way checks to see if Use could theoretically be hoisted above
214/// MayClobber. This will not check the other way around.
215///
216/// This assumes that, for the purposes of MemorySSA, Use comes directly after
217/// MayClobber, with no potentially clobbering operations in between them.
218/// (Where potentially clobbering ops are memory barriers, aliased stores, etc.)
219static Reorderability getLoadReorderability(const LoadInst *Use,
220 const LoadInst *MayClobber) {
221 bool VolatileUse = Use->isVolatile();
222 bool VolatileClobber = MayClobber->isVolatile();
223 // Volatile operations may never be reordered with other volatile operations.
224 if (VolatileUse && VolatileClobber)
225 return Reorderability::Never;
226
227 // The lang ref allows reordering of volatile and non-volatile operations.
228 // Whether an aliasing nonvolatile load and volatile load can be reordered,
229 // though, is ambiguous. Because it may not be best to exploit this ambiguity,
230 // we only allow volatile/non-volatile reordering if the volatile and
231 // non-volatile operations don't alias.
232 Reorderability Result = VolatileUse || VolatileClobber
233 ? Reorderability::IfNoAlias
234 : Reorderability::Always;
235
236 // If a load is seq_cst, it cannot be moved above other loads. If its ordering
237 // is weaker, it can be moved above other loads. We just need to be sure that
238 // MayClobber isn't an acquire load, because loads can't be moved above
239 // acquire loads.
240 //
241 // Note that this explicitly *does* allow the free reordering of monotonic (or
242 // weaker) loads of the same address.
243 bool SeqCstUse = Use->getOrdering() == AtomicOrdering::SequentiallyConsistent;
244 bool MayClobberIsAcquire = isAtLeastOrStrongerThan(MayClobber->getOrdering(),
245 AtomicOrdering::Acquire);
246 if (SeqCstUse || MayClobberIsAcquire)
247 return Reorderability::Never;
248 return Result;
249}
250
George Burgess IV024f3d22016-08-03 19:57:02 +0000251static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysis &AA,
252 const Instruction *I) {
253 // If the memory can't be changed, then loads of the memory can't be
254 // clobbered.
255 //
256 // FIXME: We should handle invariant groups, as well. It's a bit harder,
257 // because we need to pay close attention to invariant group barriers.
258 return isa<LoadInst>(I) && (I->getMetadata(LLVMContext::MD_invariant_load) ||
259 AA.pointsToConstantMemory(I));
260}
261
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000262static bool instructionClobbersQuery(MemoryDef *MD,
263 const MemoryLocation &UseLoc,
264 const Instruction *UseInst,
George Burgess IV5f308972016-07-19 01:29:15 +0000265 AliasAnalysis &AA) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000266 Instruction *DefInst = MD->getMemoryInst();
267 assert(DefInst && "Defining instruction not actually an instruction");
George Burgess IV5f308972016-07-19 01:29:15 +0000268
Daniel Berlindf101192016-08-03 00:01:46 +0000269 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) {
270 // These intrinsics will show up as affecting memory, but they are just
271 // markers.
272 switch (II->getIntrinsicID()) {
273 case Intrinsic::lifetime_start:
274 case Intrinsic::lifetime_end:
275 case Intrinsic::invariant_start:
276 case Intrinsic::invariant_end:
277 case Intrinsic::assume:
278 return false;
279 default:
280 break;
281 }
282 }
283
Daniel Berlindff31de2016-08-02 21:57:52 +0000284 ImmutableCallSite UseCS(UseInst);
285 if (UseCS) {
286 ModRefInfo I = AA.getModRefInfo(DefInst, UseCS);
287 return I != MRI_NoModRef;
288 }
George Burgess IV82e355c2016-08-03 19:39:54 +0000289
290 if (auto *DefLoad = dyn_cast<LoadInst>(DefInst)) {
291 if (auto *UseLoad = dyn_cast<LoadInst>(UseInst)) {
292 switch (getLoadReorderability(UseLoad, DefLoad)) {
293 case Reorderability::Always:
294 return false;
295 case Reorderability::Never:
296 return true;
297 case Reorderability::IfNoAlias:
298 return !AA.isNoAlias(UseLoc, MemoryLocation::get(DefLoad));
299 }
300 }
301 }
302
Daniel Berlindff31de2016-08-02 21:57:52 +0000303 return AA.getModRefInfo(DefInst, UseLoc) & MRI_Mod;
304}
305
306static bool instructionClobbersQuery(MemoryDef *MD, MemoryUse *MU,
307 const MemoryLocOrCall &UseMLOC,
308 AliasAnalysis &AA) {
309 // FIXME: This is a temporary hack to allow a single instructionClobbersQuery
310 // to exist while MemoryLocOrCall is pushed through places.
311 if (UseMLOC.IsCall)
312 return instructionClobbersQuery(MD, MemoryLocation(), MU->getMemoryInst(),
313 AA);
314 return instructionClobbersQuery(MD, UseMLOC.getLoc(), MU->getMemoryInst(),
315 AA);
George Burgess IV5f308972016-07-19 01:29:15 +0000316}
317
318/// Cache for our caching MemorySSA walker.
319class WalkerCache {
320 DenseMap<ConstMemoryAccessPair, MemoryAccess *> Accesses;
321 DenseMap<const MemoryAccess *, MemoryAccess *> Calls;
322
323public:
324 MemoryAccess *lookup(const MemoryAccess *MA, const MemoryLocation &Loc,
325 bool IsCall) const {
326 ++NumClobberCacheLookups;
327 MemoryAccess *R = IsCall ? Calls.lookup(MA) : Accesses.lookup({MA, Loc});
328 if (R)
329 ++NumClobberCacheHits;
330 return R;
331 }
332
333 bool insert(const MemoryAccess *MA, MemoryAccess *To,
334 const MemoryLocation &Loc, bool IsCall) {
335 // This is fine for Phis, since there are times where we can't optimize
336 // them. Making a def its own clobber is never correct, though.
337 assert((MA != To || isa<MemoryPhi>(MA)) &&
338 "Something can't clobber itself!");
339
340 ++NumClobberCacheInserts;
341 bool Inserted;
342 if (IsCall)
343 Inserted = Calls.insert({MA, To}).second;
344 else
345 Inserted = Accesses.insert({{MA, Loc}, To}).second;
346
347 return Inserted;
348 }
349
350 bool remove(const MemoryAccess *MA, const MemoryLocation &Loc, bool IsCall) {
351 return IsCall ? Calls.erase(MA) : Accesses.erase({MA, Loc});
352 }
353
354 void clear() {
355 Accesses.clear();
356 Calls.clear();
357 }
358
359 bool contains(const MemoryAccess *MA) const {
360 for (auto &P : Accesses)
361 if (P.first.first == MA || P.second == MA)
362 return true;
363 for (auto &P : Calls)
364 if (P.first == MA || P.second == MA)
365 return true;
366 return false;
367 }
368};
369
370/// Walks the defining uses of MemoryDefs. Stops after we hit something that has
371/// no defining use (e.g. a MemoryPhi or liveOnEntry). Note that, when comparing
372/// against a null def_chain_iterator, this will compare equal only after
373/// walking said Phi/liveOnEntry.
374struct def_chain_iterator
375 : public iterator_facade_base<def_chain_iterator, std::forward_iterator_tag,
376 MemoryAccess *> {
377 def_chain_iterator() : MA(nullptr) {}
378 def_chain_iterator(MemoryAccess *MA) : MA(MA) {}
379
380 MemoryAccess *operator*() const { return MA; }
381
382 def_chain_iterator &operator++() {
383 // N.B. liveOnEntry has a null defining access.
384 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
385 MA = MUD->getDefiningAccess();
386 else
387 MA = nullptr;
388 return *this;
389 }
390
391 bool operator==(const def_chain_iterator &O) const { return MA == O.MA; }
392
393private:
394 MemoryAccess *MA;
395};
396
397static iterator_range<def_chain_iterator>
398def_chain(MemoryAccess *MA, MemoryAccess *UpTo = nullptr) {
399#ifdef EXPENSIVE_CHECKS
400 assert((!UpTo || find(def_chain(MA), UpTo) != def_chain_iterator()) &&
401 "UpTo isn't in the def chain!");
402#endif
403 return make_range(def_chain_iterator(MA), def_chain_iterator(UpTo));
404}
405
406/// Verifies that `Start` is clobbered by `ClobberAt`, and that nothing
407/// inbetween `Start` and `ClobberAt` can clobbers `Start`.
408///
409/// This is meant to be as simple and self-contained as possible. Because it
410/// uses no cache, etc., it can be relatively expensive.
411///
412/// \param Start The MemoryAccess that we want to walk from.
413/// \param ClobberAt A clobber for Start.
414/// \param StartLoc The MemoryLocation for Start.
415/// \param MSSA The MemorySSA isntance that Start and ClobberAt belong to.
416/// \param Query The UpwardsMemoryQuery we used for our search.
417/// \param AA The AliasAnalysis we used for our search.
418static void LLVM_ATTRIBUTE_UNUSED
419checkClobberSanity(MemoryAccess *Start, MemoryAccess *ClobberAt,
420 const MemoryLocation &StartLoc, const MemorySSA &MSSA,
421 const UpwardsMemoryQuery &Query, AliasAnalysis &AA) {
422 assert(MSSA.dominates(ClobberAt, Start) && "Clobber doesn't dominate start?");
423
424 if (MSSA.isLiveOnEntryDef(Start)) {
425 assert(MSSA.isLiveOnEntryDef(ClobberAt) &&
426 "liveOnEntry must clobber itself");
427 return;
428 }
429
George Burgess IV5f308972016-07-19 01:29:15 +0000430 bool FoundClobber = false;
431 DenseSet<MemoryAccessPair> VisitedPhis;
432 SmallVector<MemoryAccessPair, 8> Worklist;
433 Worklist.emplace_back(Start, StartLoc);
434 // Walk all paths from Start to ClobberAt, while looking for clobbers. If one
435 // is found, complain.
436 while (!Worklist.empty()) {
437 MemoryAccessPair MAP = Worklist.pop_back_val();
438 // All we care about is that nothing from Start to ClobberAt clobbers Start.
439 // We learn nothing from revisiting nodes.
440 if (!VisitedPhis.insert(MAP).second)
441 continue;
442
443 for (MemoryAccess *MA : def_chain(MAP.first)) {
444 if (MA == ClobberAt) {
445 if (auto *MD = dyn_cast<MemoryDef>(MA)) {
446 // instructionClobbersQuery isn't essentially free, so don't use `|=`,
447 // since it won't let us short-circuit.
448 //
449 // Also, note that this can't be hoisted out of the `Worklist` loop,
450 // since MD may only act as a clobber for 1 of N MemoryLocations.
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000451 FoundClobber =
452 FoundClobber || MSSA.isLiveOnEntryDef(MD) ||
453 instructionClobbersQuery(MD, MAP.second, Query.Inst, AA);
George Burgess IV5f308972016-07-19 01:29:15 +0000454 }
455 break;
456 }
457
458 // We should never hit liveOnEntry, unless it's the clobber.
459 assert(!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?");
460
461 if (auto *MD = dyn_cast<MemoryDef>(MA)) {
462 (void)MD;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000463 assert(!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA) &&
George Burgess IV5f308972016-07-19 01:29:15 +0000464 "Found clobber before reaching ClobberAt!");
465 continue;
466 }
467
468 assert(isa<MemoryPhi>(MA));
469 Worklist.append(upward_defs_begin({MA, MAP.second}), upward_defs_end());
470 }
471 }
472
473 // If ClobberAt is a MemoryPhi, we can assume something above it acted as a
474 // clobber. Otherwise, `ClobberAt` should've acted as a clobber at some point.
475 assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&
476 "ClobberAt never acted as a clobber");
477}
478
479/// Our algorithm for walking (and trying to optimize) clobbers, all wrapped up
480/// in one class.
481class ClobberWalker {
482 /// Save a few bytes by using unsigned instead of size_t.
483 using ListIndex = unsigned;
484
485 /// Represents a span of contiguous MemoryDefs, potentially ending in a
486 /// MemoryPhi.
487 struct DefPath {
488 MemoryLocation Loc;
489 // Note that, because we always walk in reverse, Last will always dominate
490 // First. Also note that First and Last are inclusive.
491 MemoryAccess *First;
492 MemoryAccess *Last;
493 // N.B. Blocker is currently basically unused. The goal is to use it to make
494 // cache invalidation better, but we're not there yet.
495 MemoryAccess *Blocker;
496 Optional<ListIndex> Previous;
497
498 DefPath(const MemoryLocation &Loc, MemoryAccess *First, MemoryAccess *Last,
499 Optional<ListIndex> Previous)
500 : Loc(Loc), First(First), Last(Last), Previous(Previous) {}
501
502 DefPath(const MemoryLocation &Loc, MemoryAccess *Init,
503 Optional<ListIndex> Previous)
504 : DefPath(Loc, Init, Init, Previous) {}
505 };
506
507 const MemorySSA &MSSA;
508 AliasAnalysis &AA;
509 DominatorTree &DT;
510 WalkerCache &WC;
511 UpwardsMemoryQuery *Query;
512 bool UseCache;
513
514 // Phi optimization bookkeeping
515 SmallVector<DefPath, 32> Paths;
516 DenseSet<ConstMemoryAccessPair> VisitedPhis;
517 DenseMap<const BasicBlock *, MemoryAccess *> WalkTargetCache;
518
519 void setUseCache(bool Use) { UseCache = Use; }
520 bool shouldIgnoreCache() const {
521 // UseCache will only be false when we're debugging, or when expensive
522 // checks are enabled. In either case, we don't care deeply about speed.
523 return LLVM_UNLIKELY(!UseCache);
524 }
525
526 void addCacheEntry(const MemoryAccess *What, MemoryAccess *To,
527 const MemoryLocation &Loc) const {
Daniel Berlin5c46b942016-07-19 22:49:43 +0000528// EXPENSIVE_CHECKS because most of these queries are redundant.
George Burgess IV5f308972016-07-19 01:29:15 +0000529#ifdef EXPENSIVE_CHECKS
530 assert(MSSA.dominates(To, What));
531#endif
532 if (shouldIgnoreCache())
533 return;
534 WC.insert(What, To, Loc, Query->IsCall);
535 }
536
537 MemoryAccess *lookupCache(const MemoryAccess *MA, const MemoryLocation &Loc) {
538 return shouldIgnoreCache() ? nullptr : WC.lookup(MA, Loc, Query->IsCall);
539 }
540
541 void cacheDefPath(const DefPath &DN, MemoryAccess *Target) const {
542 if (shouldIgnoreCache())
543 return;
544
545 for (MemoryAccess *MA : def_chain(DN.First, DN.Last))
546 addCacheEntry(MA, Target, DN.Loc);
547
548 // DefPaths only express the path we walked. So, DN.Last could either be a
549 // thing we want to cache, or not.
550 if (DN.Last != Target)
551 addCacheEntry(DN.Last, Target, DN.Loc);
552 }
553
554 /// Find the nearest def or phi that `From` can legally be optimized to.
555 ///
556 /// FIXME: Deduplicate this with MSSA::findDominatingDef. Ideally, MSSA should
557 /// keep track of this information for us, and allow us O(1) lookups of this
558 /// info.
559 MemoryAccess *getWalkTarget(const MemoryPhi *From) {
George Burgess IV5f308972016-07-19 01:29:15 +0000560 assert(From->getNumOperands() && "Phi with no operands?");
561
562 BasicBlock *BB = From->getBlock();
563 auto At = WalkTargetCache.find(BB);
564 if (At != WalkTargetCache.end())
565 return At->second;
566
567 SmallVector<const BasicBlock *, 8> ToCache;
568 ToCache.push_back(BB);
569
570 MemoryAccess *Result = MSSA.getLiveOnEntryDef();
571 DomTreeNode *Node = DT.getNode(BB);
572 while ((Node = Node->getIDom())) {
573 auto At = WalkTargetCache.find(BB);
574 if (At != WalkTargetCache.end()) {
575 Result = At->second;
576 break;
577 }
578
579 auto *Accesses = MSSA.getBlockAccesses(Node->getBlock());
580 if (Accesses) {
581 auto Iter = find_if(reverse(*Accesses), [](const MemoryAccess &MA) {
582 return !isa<MemoryUse>(MA);
583 });
584 if (Iter != Accesses->rend()) {
585 Result = const_cast<MemoryAccess *>(&*Iter);
586 break;
587 }
588 }
589
590 ToCache.push_back(Node->getBlock());
591 }
592
593 for (const BasicBlock *BB : ToCache)
594 WalkTargetCache.insert({BB, Result});
595 return Result;
596 }
597
598 /// Result of calling walkToPhiOrClobber.
599 struct UpwardsWalkResult {
600 /// The "Result" of the walk. Either a clobber, the last thing we walked, or
601 /// both.
602 MemoryAccess *Result;
603 bool IsKnownClobber;
604 bool FromCache;
605 };
606
607 /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last.
608 /// This will update Desc.Last as it walks. It will (optionally) also stop at
609 /// StopAt.
610 ///
611 /// This does not test for whether StopAt is a clobber
612 UpwardsWalkResult walkToPhiOrClobber(DefPath &Desc,
613 MemoryAccess *StopAt = nullptr) {
614 assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");
615
616 for (MemoryAccess *Current : def_chain(Desc.Last)) {
617 Desc.Last = Current;
618 if (Current == StopAt)
619 return {Current, false, false};
620
621 if (auto *MD = dyn_cast<MemoryDef>(Current))
622 if (MSSA.isLiveOnEntryDef(MD) ||
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000623 instructionClobbersQuery(MD, Desc.Loc, Query->Inst, AA))
George Burgess IV5f308972016-07-19 01:29:15 +0000624 return {MD, true, false};
625
626 // Cache checks must be done last, because if Current is a clobber, the
627 // cache will contain the clobber for Current.
628 if (MemoryAccess *MA = lookupCache(Current, Desc.Loc))
629 return {MA, true, true};
630 }
631
632 assert(isa<MemoryPhi>(Desc.Last) &&
633 "Ended at a non-clobber that's not a phi?");
634 return {Desc.Last, false, false};
635 }
636
637 void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches,
638 ListIndex PriorNode) {
639 auto UpwardDefs = make_range(upward_defs_begin({Phi, Paths[PriorNode].Loc}),
640 upward_defs_end());
641 for (const MemoryAccessPair &P : UpwardDefs) {
642 PausedSearches.push_back(Paths.size());
643 Paths.emplace_back(P.second, P.first, PriorNode);
644 }
645 }
646
647 /// Represents a search that terminated after finding a clobber. This clobber
648 /// may or may not be present in the path of defs from LastNode..SearchStart,
649 /// since it may have been retrieved from cache.
650 struct TerminatedPath {
651 MemoryAccess *Clobber;
652 ListIndex LastNode;
653 };
654
655 /// Get an access that keeps us from optimizing to the given phi.
656 ///
657 /// PausedSearches is an array of indices into the Paths array. Its incoming
658 /// value is the indices of searches that stopped at the last phi optimization
659 /// target. It's left in an unspecified state.
660 ///
661 /// If this returns None, NewPaused is a vector of searches that terminated
662 /// at StopWhere. Otherwise, NewPaused is left in an unspecified state.
George Burgess IV14633b52016-08-03 01:22:19 +0000663 Optional<TerminatedPath>
George Burgess IV5f308972016-07-19 01:29:15 +0000664 getBlockingAccess(MemoryAccess *StopWhere,
665 SmallVectorImpl<ListIndex> &PausedSearches,
666 SmallVectorImpl<ListIndex> &NewPaused,
667 SmallVectorImpl<TerminatedPath> &Terminated) {
668 assert(!PausedSearches.empty() && "No searches to continue?");
669
670 // BFS vs DFS really doesn't make a difference here, so just do a DFS with
671 // PausedSearches as our stack.
672 while (!PausedSearches.empty()) {
673 ListIndex PathIndex = PausedSearches.pop_back_val();
674 DefPath &Node = Paths[PathIndex];
675
676 // If we've already visited this path with this MemoryLocation, we don't
677 // need to do so again.
678 //
679 // NOTE: That we just drop these paths on the ground makes caching
680 // behavior sporadic. e.g. given a diamond:
681 // A
682 // B C
683 // D
684 //
685 // ...If we walk D, B, A, C, we'll only cache the result of phi
686 // optimization for A, B, and D; C will be skipped because it dies here.
687 // This arguably isn't the worst thing ever, since:
688 // - We generally query things in a top-down order, so if we got below D
689 // without needing cache entries for {C, MemLoc}, then chances are
690 // that those cache entries would end up ultimately unused.
691 // - We still cache things for A, so C only needs to walk up a bit.
692 // If this behavior becomes problematic, we can fix without a ton of extra
693 // work.
694 if (!VisitedPhis.insert({Node.Last, Node.Loc}).second)
695 continue;
696
697 UpwardsWalkResult Res = walkToPhiOrClobber(Node, /*StopAt=*/StopWhere);
698 if (Res.IsKnownClobber) {
699 assert(Res.Result != StopWhere || Res.FromCache);
700 // If this wasn't a cache hit, we hit a clobber when walking. That's a
701 // failure.
George Burgess IV14633b52016-08-03 01:22:19 +0000702 TerminatedPath Term{Res.Result, PathIndex};
George Burgess IV5f308972016-07-19 01:29:15 +0000703 if (!Res.FromCache || !MSSA.dominates(Res.Result, StopWhere))
George Burgess IV14633b52016-08-03 01:22:19 +0000704 return Term;
George Burgess IV5f308972016-07-19 01:29:15 +0000705
706 // Otherwise, it's a valid thing to potentially optimize to.
George Burgess IV14633b52016-08-03 01:22:19 +0000707 Terminated.push_back(Term);
George Burgess IV5f308972016-07-19 01:29:15 +0000708 continue;
709 }
710
711 if (Res.Result == StopWhere) {
712 // We've hit our target. Save this path off for if we want to continue
713 // walking.
714 NewPaused.push_back(PathIndex);
715 continue;
716 }
717
718 assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");
719 addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
720 }
721
722 return None;
723 }
724
725 template <typename T, typename Walker>
726 struct generic_def_path_iterator
727 : public iterator_facade_base<generic_def_path_iterator<T, Walker>,
728 std::forward_iterator_tag, T *> {
729 generic_def_path_iterator() : W(nullptr), N(None) {}
730 generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}
731
732 T &operator*() const { return curNode(); }
733
734 generic_def_path_iterator &operator++() {
735 N = curNode().Previous;
736 return *this;
737 }
738
739 bool operator==(const generic_def_path_iterator &O) const {
740 if (N.hasValue() != O.N.hasValue())
741 return false;
742 return !N.hasValue() || *N == *O.N;
743 }
744
745 private:
746 T &curNode() const { return W->Paths[*N]; }
747
748 Walker *W;
749 Optional<ListIndex> N;
750 };
751
752 using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
753 using const_def_path_iterator =
754 generic_def_path_iterator<const DefPath, const ClobberWalker>;
755
756 iterator_range<def_path_iterator> def_path(ListIndex From) {
757 return make_range(def_path_iterator(this, From), def_path_iterator());
758 }
759
760 iterator_range<const_def_path_iterator> const_def_path(ListIndex From) const {
761 return make_range(const_def_path_iterator(this, From),
762 const_def_path_iterator());
763 }
764
765 struct OptznResult {
766 /// The path that contains our result.
767 TerminatedPath PrimaryClobber;
768 /// The paths that we can legally cache back from, but that aren't
769 /// necessarily the result of the Phi optimization.
770 SmallVector<TerminatedPath, 4> OtherClobbers;
771 };
772
773 ListIndex defPathIndex(const DefPath &N) const {
774 // The assert looks nicer if we don't need to do &N
775 const DefPath *NP = &N;
776 assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
777 "Out of bounds DefPath!");
778 return NP - &Paths.front();
779 }
780
781 /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths
782 /// that act as legal clobbers. Note that this won't return *all* clobbers.
783 ///
784 /// Phi optimization algorithm tl;dr:
785 /// - Find the earliest def/phi, A, we can optimize to
786 /// - Find if all paths from the starting memory access ultimately reach A
787 /// - If not, optimization isn't possible.
788 /// - Otherwise, walk from A to another clobber or phi, A'.
789 /// - If A' is a def, we're done.
790 /// - If A' is a phi, try to optimize it.
791 ///
792 /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path
793 /// terminates when a MemoryAccess that clobbers said MemoryLocation is found.
794 OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start,
795 const MemoryLocation &Loc) {
796 assert(Paths.empty() && VisitedPhis.empty() &&
797 "Reset the optimization state.");
798
799 Paths.emplace_back(Loc, Start, Phi, None);
800 // Stores how many "valid" optimization nodes we had prior to calling
801 // addSearches/getBlockingAccess. Necessary for caching if we had a blocker.
802 auto PriorPathsSize = Paths.size();
803
804 SmallVector<ListIndex, 16> PausedSearches;
805 SmallVector<ListIndex, 8> NewPaused;
806 SmallVector<TerminatedPath, 4> TerminatedPaths;
807
808 addSearches(Phi, PausedSearches, 0);
809
810 // Moves the TerminatedPath with the "most dominated" Clobber to the end of
811 // Paths.
812 auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
813 assert(!Paths.empty() && "Need a path to move");
George Burgess IV5f308972016-07-19 01:29:15 +0000814 auto Dom = Paths.begin();
815 for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I)
816 if (!MSSA.dominates(I->Clobber, Dom->Clobber))
817 Dom = I;
818 auto Last = Paths.end() - 1;
819 if (Last != Dom)
820 std::iter_swap(Last, Dom);
821 };
822
823 MemoryPhi *Current = Phi;
824 while (1) {
825 assert(!MSSA.isLiveOnEntryDef(Current) &&
826 "liveOnEntry wasn't treated as a clobber?");
827
828 MemoryAccess *Target = getWalkTarget(Current);
829 // If a TerminatedPath doesn't dominate Target, then it wasn't a legal
830 // optimization for the prior phi.
831 assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {
832 return MSSA.dominates(P.Clobber, Target);
833 }));
834
835 // FIXME: This is broken, because the Blocker may be reported to be
836 // liveOnEntry, and we'll happily wait for that to disappear (read: never)
837 // For the moment, this is fine, since we do basically nothing with
838 // blocker info.
George Burgess IV14633b52016-08-03 01:22:19 +0000839 if (Optional<TerminatedPath> Blocker = getBlockingAccess(
George Burgess IV5f308972016-07-19 01:29:15 +0000840 Target, PausedSearches, NewPaused, TerminatedPaths)) {
George Burgess IV5f308972016-07-19 01:29:15 +0000841 // Cache our work on the blocking node, since we know that's correct.
George Burgess IV14633b52016-08-03 01:22:19 +0000842 cacheDefPath(Paths[Blocker->LastNode], Blocker->Clobber);
George Burgess IV5f308972016-07-19 01:29:15 +0000843
844 // Find the node we started at. We can't search based on N->Last, since
845 // we may have gone around a loop with a different MemoryLocation.
George Burgess IV14633b52016-08-03 01:22:19 +0000846 auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) {
George Burgess IV5f308972016-07-19 01:29:15 +0000847 return defPathIndex(N) < PriorPathsSize;
848 });
849 assert(Iter != def_path_iterator());
850
851 DefPath &CurNode = *Iter;
852 assert(CurNode.Last == Current);
George Burgess IV14633b52016-08-03 01:22:19 +0000853 CurNode.Blocker = Blocker->Clobber;
George Burgess IV5f308972016-07-19 01:29:15 +0000854
855 // Two things:
856 // A. We can't reliably cache all of NewPaused back. Consider a case
857 // where we have two paths in NewPaused; one of which can't optimize
858 // above this phi, whereas the other can. If we cache the second path
859 // back, we'll end up with suboptimal cache entries. We can handle
860 // cases like this a bit better when we either try to find all
861 // clobbers that block phi optimization, or when our cache starts
862 // supporting unfinished searches.
863 // B. We can't reliably cache TerminatedPaths back here without doing
864 // extra checks; consider a case like:
865 // T
866 // / \
867 // D C
868 // \ /
869 // S
870 // Where T is our target, C is a node with a clobber on it, D is a
871 // diamond (with a clobber *only* on the left or right node, N), and
872 // S is our start. Say we walk to D, through the node opposite N
873 // (read: ignoring the clobber), and see a cache entry in the top
874 // node of D. That cache entry gets put into TerminatedPaths. We then
875 // walk up to C (N is later in our worklist), find the clobber, and
876 // quit. If we append TerminatedPaths to OtherClobbers, we'll cache
877 // the bottom part of D to the cached clobber, ignoring the clobber
878 // in N. Again, this problem goes away if we start tracking all
879 // blockers for a given phi optimization.
880 TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
881 return {Result, {}};
882 }
883
884 // If there's nothing left to search, then all paths led to valid clobbers
885 // that we got from our cache; pick the nearest to the start, and allow
886 // the rest to be cached back.
887 if (NewPaused.empty()) {
888 MoveDominatedPathToEnd(TerminatedPaths);
889 TerminatedPath Result = TerminatedPaths.pop_back_val();
890 return {Result, std::move(TerminatedPaths)};
891 }
892
893 MemoryAccess *DefChainEnd = nullptr;
894 SmallVector<TerminatedPath, 4> Clobbers;
895 for (ListIndex Paused : NewPaused) {
896 UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
897 if (WR.IsKnownClobber)
898 Clobbers.push_back({WR.Result, Paused});
899 else
900 // Micro-opt: If we hit the end of the chain, save it.
901 DefChainEnd = WR.Result;
902 }
903
904 if (!TerminatedPaths.empty()) {
905 // If we couldn't find the dominating phi/liveOnEntry in the above loop,
906 // do it now.
907 if (!DefChainEnd)
908 for (MemoryAccess *MA : def_chain(Target))
909 DefChainEnd = MA;
910
911 // If any of the terminated paths don't dominate the phi we'll try to
912 // optimize, we need to figure out what they are and quit.
913 const BasicBlock *ChainBB = DefChainEnd->getBlock();
914 for (const TerminatedPath &TP : TerminatedPaths) {
915 // Because we know that DefChainEnd is as "high" as we can go, we
916 // don't need local dominance checks; BB dominance is sufficient.
917 if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
918 Clobbers.push_back(TP);
919 }
920 }
921
922 // If we have clobbers in the def chain, find the one closest to Current
923 // and quit.
924 if (!Clobbers.empty()) {
925 MoveDominatedPathToEnd(Clobbers);
926 TerminatedPath Result = Clobbers.pop_back_val();
927 return {Result, std::move(Clobbers)};
928 }
929
930 assert(all_of(NewPaused,
931 [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
932
933 // Because liveOnEntry is a clobber, this must be a phi.
934 auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
935
936 PriorPathsSize = Paths.size();
937 PausedSearches.clear();
938 for (ListIndex I : NewPaused)
939 addSearches(DefChainPhi, PausedSearches, I);
940 NewPaused.clear();
941
942 Current = DefChainPhi;
943 }
944 }
945
946 /// Caches everything in an OptznResult.
947 void cacheOptResult(const OptznResult &R) {
948 if (R.OtherClobbers.empty()) {
949 // If we're not going to be caching OtherClobbers, don't bother with
950 // marking visited/etc.
951 for (const DefPath &N : const_def_path(R.PrimaryClobber.LastNode))
952 cacheDefPath(N, R.PrimaryClobber.Clobber);
953 return;
954 }
955
956 // PrimaryClobber is our answer. If we can cache anything back, we need to
957 // stop caching when we visit PrimaryClobber.
958 SmallBitVector Visited(Paths.size());
959 for (const DefPath &N : const_def_path(R.PrimaryClobber.LastNode)) {
960 Visited[defPathIndex(N)] = true;
961 cacheDefPath(N, R.PrimaryClobber.Clobber);
962 }
963
964 for (const TerminatedPath &P : R.OtherClobbers) {
965 for (const DefPath &N : const_def_path(P.LastNode)) {
966 ListIndex NIndex = defPathIndex(N);
967 if (Visited[NIndex])
968 break;
969 Visited[NIndex] = true;
970 cacheDefPath(N, P.Clobber);
971 }
972 }
973 }
974
975 void verifyOptResult(const OptznResult &R) const {
976 assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
977 return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
978 }));
979 }
980
981 void resetPhiOptznState() {
982 Paths.clear();
983 VisitedPhis.clear();
984 }
985
986public:
987 ClobberWalker(const MemorySSA &MSSA, AliasAnalysis &AA, DominatorTree &DT,
988 WalkerCache &WC)
989 : MSSA(MSSA), AA(AA), DT(DT), WC(WC), UseCache(true) {}
990
991 void reset() { WalkTargetCache.clear(); }
992
993 /// Finds the nearest clobber for the given query, optimizing phis if
994 /// possible.
995 MemoryAccess *findClobber(MemoryAccess *Start, UpwardsMemoryQuery &Q,
996 bool UseWalkerCache = true) {
997 setUseCache(UseWalkerCache);
998 Query = &Q;
999
1000 MemoryAccess *Current = Start;
1001 // This walker pretends uses don't exist. If we're handed one, silently grab
1002 // its def. (This has the nice side-effect of ensuring we never cache uses)
1003 if (auto *MU = dyn_cast<MemoryUse>(Start))
1004 Current = MU->getDefiningAccess();
1005
1006 DefPath FirstDesc(Q.StartingLoc, Current, Current, None);
1007 // Fast path for the overly-common case (no crazy phi optimization
1008 // necessary)
1009 UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
George Burgess IV93ea19b2016-07-24 07:03:49 +00001010 MemoryAccess *Result;
George Burgess IV5f308972016-07-19 01:29:15 +00001011 if (WalkResult.IsKnownClobber) {
1012 cacheDefPath(FirstDesc, WalkResult.Result);
George Burgess IV93ea19b2016-07-24 07:03:49 +00001013 Result = WalkResult.Result;
1014 } else {
1015 OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
1016 Current, Q.StartingLoc);
1017 verifyOptResult(OptRes);
1018 cacheOptResult(OptRes);
1019 resetPhiOptznState();
1020 Result = OptRes.PrimaryClobber.Clobber;
George Burgess IV5f308972016-07-19 01:29:15 +00001021 }
1022
George Burgess IV5f308972016-07-19 01:29:15 +00001023#ifdef EXPENSIVE_CHECKS
George Burgess IV93ea19b2016-07-24 07:03:49 +00001024 checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, AA);
George Burgess IV5f308972016-07-19 01:29:15 +00001025#endif
George Burgess IV93ea19b2016-07-24 07:03:49 +00001026 return Result;
George Burgess IV5f308972016-07-19 01:29:15 +00001027 }
1028};
1029
1030struct RenamePassData {
1031 DomTreeNode *DTN;
1032 DomTreeNode::const_iterator ChildIt;
1033 MemoryAccess *IncomingVal;
1034
1035 RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
1036 MemoryAccess *M)
1037 : DTN(D), ChildIt(It), IncomingVal(M) {}
1038 void swap(RenamePassData &RHS) {
1039 std::swap(DTN, RHS.DTN);
1040 std::swap(ChildIt, RHS.ChildIt);
1041 std::swap(IncomingVal, RHS.IncomingVal);
1042 }
1043};
1044} // anonymous namespace
1045
1046namespace llvm {
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001047/// \brief A MemorySSAWalker that does AA walks and caching of lookups to
1048/// disambiguate accesses.
1049///
1050/// FIXME: The current implementation of this can take quadratic space in rare
1051/// cases. This can be fixed, but it is something to note until it is fixed.
1052///
1053/// In order to trigger this behavior, you need to store to N distinct locations
1054/// (that AA can prove don't alias), perform M stores to other memory
1055/// locations that AA can prove don't alias any of the initial N locations, and
1056/// then load from all of the N locations. In this case, we insert M cache
1057/// entries for each of the N loads.
1058///
1059/// For example:
1060/// define i32 @foo() {
1061/// %a = alloca i32, align 4
1062/// %b = alloca i32, align 4
1063/// store i32 0, i32* %a, align 4
1064/// store i32 0, i32* %b, align 4
1065///
1066/// ; Insert M stores to other memory that doesn't alias %a or %b here
1067///
1068/// %c = load i32, i32* %a, align 4 ; Caches M entries in
1069/// ; CachedUpwardsClobberingAccess for the
1070/// ; MemoryLocation %a
1071/// %d = load i32, i32* %b, align 4 ; Caches M entries in
1072/// ; CachedUpwardsClobberingAccess for the
1073/// ; MemoryLocation %b
1074///
1075/// ; For completeness' sake, loading %a or %b again would not cache *another*
1076/// ; M entries.
1077/// %r = add i32 %c, %d
1078/// ret i32 %r
1079/// }
1080class MemorySSA::CachingWalker final : public MemorySSAWalker {
George Burgess IV5f308972016-07-19 01:29:15 +00001081 WalkerCache Cache;
1082 ClobberWalker Walker;
1083 bool AutoResetWalker;
1084
1085 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *, UpwardsMemoryQuery &);
1086 void verifyRemoved(MemoryAccess *);
1087
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001088public:
1089 CachingWalker(MemorySSA *, AliasAnalysis *, DominatorTree *);
1090 ~CachingWalker() override;
1091
George Burgess IV400ae402016-07-20 19:51:34 +00001092 using MemorySSAWalker::getClobberingMemoryAccess;
1093 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) override;
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001094 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
1095 MemoryLocation &) override;
1096 void invalidateInfo(MemoryAccess *) override;
1097
George Burgess IV5f308972016-07-19 01:29:15 +00001098 /// Whether we call resetClobberWalker() after each time we *actually* walk to
1099 /// answer a clobber query.
1100 void setAutoResetWalker(bool AutoReset) { AutoResetWalker = AutoReset; }
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001101
George Burgess IV5f308972016-07-19 01:29:15 +00001102 /// Drop the walker's persistent data structures. At the moment, this means
1103 /// "drop the walker's cache of BasicBlocks ->
1104 /// earliest-MemoryAccess-we-can-optimize-to". This is necessary if we're
1105 /// going to have DT updates, if we remove MemoryAccesses, etc.
1106 void resetClobberWalker() { Walker.reset(); }
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001107};
George Burgess IVe1100f52016-02-02 22:46:49 +00001108
George Burgess IVe1100f52016-02-02 22:46:49 +00001109/// \brief Rename a single basic block into MemorySSA form.
1110/// Uses the standard SSA renaming algorithm.
1111/// \returns The new incoming value.
1112MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB,
1113 MemoryAccess *IncomingVal) {
1114 auto It = PerBlockAccesses.find(BB);
1115 // Skip most processing if the list is empty.
1116 if (It != PerBlockAccesses.end()) {
Daniel Berlinada263d2016-06-20 20:21:33 +00001117 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001118 for (MemoryAccess &L : *Accesses) {
1119 switch (L.getValueID()) {
1120 case Value::MemoryUseVal:
1121 cast<MemoryUse>(&L)->setDefiningAccess(IncomingVal);
1122 break;
1123 case Value::MemoryDefVal:
1124 // We can't legally optimize defs, because we only allow single
1125 // memory phis/uses on operations, and if we optimize these, we can
1126 // end up with multiple reaching defs. Uses do not have this
1127 // problem, since they do not produce a value
1128 cast<MemoryDef>(&L)->setDefiningAccess(IncomingVal);
1129 IncomingVal = &L;
1130 break;
1131 case Value::MemoryPhiVal:
1132 IncomingVal = &L;
1133 break;
1134 }
1135 }
1136 }
1137
1138 // Pass through values to our successors
1139 for (const BasicBlock *S : successors(BB)) {
1140 auto It = PerBlockAccesses.find(S);
1141 // Rename the phi nodes in our successor block
1142 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1143 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +00001144 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001145 auto *Phi = cast<MemoryPhi>(&Accesses->front());
George Burgess IVe1100f52016-02-02 22:46:49 +00001146 Phi->addIncoming(IncomingVal, BB);
1147 }
1148
1149 return IncomingVal;
1150}
1151
1152/// \brief This is the standard SSA renaming algorithm.
1153///
1154/// We walk the dominator tree in preorder, renaming accesses, and then filling
1155/// in phi nodes in our successors.
1156void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
1157 SmallPtrSet<BasicBlock *, 16> &Visited) {
1158 SmallVector<RenamePassData, 32> WorkStack;
1159 IncomingVal = renameBlock(Root->getBlock(), IncomingVal);
1160 WorkStack.push_back({Root, Root->begin(), IncomingVal});
1161 Visited.insert(Root->getBlock());
1162
1163 while (!WorkStack.empty()) {
1164 DomTreeNode *Node = WorkStack.back().DTN;
1165 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
1166 IncomingVal = WorkStack.back().IncomingVal;
1167
1168 if (ChildIt == Node->end()) {
1169 WorkStack.pop_back();
1170 } else {
1171 DomTreeNode *Child = *ChildIt;
1172 ++WorkStack.back().ChildIt;
1173 BasicBlock *BB = Child->getBlock();
1174 Visited.insert(BB);
1175 IncomingVal = renameBlock(BB, IncomingVal);
1176 WorkStack.push_back({Child, Child->begin(), IncomingVal});
1177 }
1178 }
1179}
1180
1181/// \brief Compute dominator levels, used by the phi insertion algorithm above.
1182void MemorySSA::computeDomLevels(DenseMap<DomTreeNode *, unsigned> &DomLevels) {
1183 for (auto DFI = df_begin(DT->getRootNode()), DFE = df_end(DT->getRootNode());
1184 DFI != DFE; ++DFI)
1185 DomLevels[*DFI] = DFI.getPathLength() - 1;
1186}
1187
George Burgess IVa362b092016-07-06 00:28:43 +00001188/// \brief This handles unreachable block accesses by deleting phi nodes in
George Burgess IVe1100f52016-02-02 22:46:49 +00001189/// unreachable blocks, and marking all other unreachable MemoryAccess's as
1190/// being uses of the live on entry definition.
1191void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
1192 assert(!DT->isReachableFromEntry(BB) &&
1193 "Reachable block found while handling unreachable blocks");
1194
Daniel Berlinfc7e6512016-07-06 05:32:05 +00001195 // Make sure phi nodes in our reachable successors end up with a
1196 // LiveOnEntryDef for our incoming edge, even though our block is forward
1197 // unreachable. We could just disconnect these blocks from the CFG fully,
1198 // but we do not right now.
1199 for (const BasicBlock *S : successors(BB)) {
1200 if (!DT->isReachableFromEntry(S))
1201 continue;
1202 auto It = PerBlockAccesses.find(S);
1203 // Rename the phi nodes in our successor block
1204 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1205 continue;
1206 AccessList *Accesses = It->second.get();
1207 auto *Phi = cast<MemoryPhi>(&Accesses->front());
1208 Phi->addIncoming(LiveOnEntryDef.get(), BB);
1209 }
1210
George Burgess IVe1100f52016-02-02 22:46:49 +00001211 auto It = PerBlockAccesses.find(BB);
1212 if (It == PerBlockAccesses.end())
1213 return;
1214
1215 auto &Accesses = It->second;
1216 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1217 auto Next = std::next(AI);
1218 // If we have a phi, just remove it. We are going to replace all
1219 // users with live on entry.
1220 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1221 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1222 else
1223 Accesses->erase(AI);
1224 AI = Next;
1225 }
1226}
1227
Geoff Berryb96d3b22016-06-01 21:30:40 +00001228MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
1229 : AA(AA), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
1230 NextID(0) {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001231 buildMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001232}
1233
1234MemorySSA::MemorySSA(MemorySSA &&MSSA)
1235 : AA(MSSA.AA), DT(MSSA.DT), F(MSSA.F),
1236 ValueToMemoryAccess(std::move(MSSA.ValueToMemoryAccess)),
1237 PerBlockAccesses(std::move(MSSA.PerBlockAccesses)),
1238 LiveOnEntryDef(std::move(MSSA.LiveOnEntryDef)),
George Burgess IV363da6f2016-08-03 21:07:52 +00001239 BlockNumberingValid(std::move(MSSA.BlockNumberingValid)),
1240 BlockNumbering(std::move(MSSA.BlockNumbering)),
Geoff Berryb96d3b22016-06-01 21:30:40 +00001241 Walker(std::move(MSSA.Walker)), NextID(MSSA.NextID) {
1242 // Update the Walker MSSA pointer so it doesn't point to the moved-from MSSA
1243 // object any more.
1244 Walker->MSSA = this;
1245}
George Burgess IVe1100f52016-02-02 22:46:49 +00001246
1247MemorySSA::~MemorySSA() {
1248 // Drop all our references
1249 for (const auto &Pair : PerBlockAccesses)
1250 for (MemoryAccess &MA : *Pair.second)
1251 MA.dropAllReferences();
1252}
1253
Daniel Berlin14300262016-06-21 18:39:20 +00001254MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001255 auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
1256
1257 if (Res.second)
Daniel Berlinada263d2016-06-20 20:21:33 +00001258 Res.first->second = make_unique<AccessList>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001259 return Res.first->second.get();
1260}
1261
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001262/// This class is a batch walker of all MemoryUse's in the program, and points
1263/// their defining access at the thing that actually clobbers them. Because it
1264/// is a batch walker that touches everything, it does not operate like the
1265/// other walkers. This walker is basically performing a top-down SSA renaming
1266/// pass, where the version stack is used as the cache. This enables it to be
1267/// significantly more time and memory efficient than using the regular walker,
1268/// which is walking bottom-up.
1269class MemorySSA::OptimizeUses {
1270public:
1271 OptimizeUses(MemorySSA *MSSA, MemorySSAWalker *Walker, AliasAnalysis *AA,
1272 DominatorTree *DT)
1273 : MSSA(MSSA), Walker(Walker), AA(AA), DT(DT) {
1274 Walker = MSSA->getWalker();
1275 }
1276
1277 void optimizeUses();
1278
1279private:
1280 /// This represents where a given memorylocation is in the stack.
1281 struct MemlocStackInfo {
1282 // This essentially is keeping track of versions of the stack. Whenever
1283 // the stack changes due to pushes or pops, these versions increase.
1284 unsigned long StackEpoch;
1285 unsigned long PopEpoch;
1286 // This is the lower bound of places on the stack to check. It is equal to
1287 // the place the last stack walk ended.
1288 // Note: Correctness depends on this being initialized to 0, which densemap
1289 // does
1290 unsigned long LowerBound;
1291 // This is where the last walk for this memory location ended.
1292 unsigned long LastKill;
1293 bool LastKillValid;
1294 };
1295 void optimizeUsesInBlock(const BasicBlock *, unsigned long &, unsigned long &,
1296 SmallVectorImpl<MemoryAccess *> &,
1297 DenseMap<MemoryLocOrCall, MemlocStackInfo> &);
1298 MemorySSA *MSSA;
1299 MemorySSAWalker *Walker;
1300 AliasAnalysis *AA;
1301 DominatorTree *DT;
1302};
1303
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001304/// Optimize the uses in a given block This is basically the SSA renaming
1305/// algorithm, with one caveat: We are able to use a single stack for all
1306/// MemoryUses. This is because the set of *possible* reaching MemoryDefs is
1307/// the same for every MemoryUse. The *actual* clobbering MemoryDef is just
1308/// going to be some position in that stack of possible ones.
1309///
1310/// We track the stack positions that each MemoryLocation needs
1311/// to check, and last ended at. This is because we only want to check the
1312/// things that changed since last time. The same MemoryLocation should
1313/// get clobbered by the same store (getModRefInfo does not use invariantness or
1314/// things like this, and if they start, we can modify MemoryLocOrCall to
1315/// include relevant data)
1316void MemorySSA::OptimizeUses::optimizeUsesInBlock(
1317 const BasicBlock *BB, unsigned long &StackEpoch, unsigned long &PopEpoch,
1318 SmallVectorImpl<MemoryAccess *> &VersionStack,
1319 DenseMap<MemoryLocOrCall, MemlocStackInfo> &LocStackInfo) {
1320
1321 /// If no accesses, nothing to do.
1322 MemorySSA::AccessList *Accesses = MSSA->getWritableBlockAccesses(BB);
1323 if (Accesses == nullptr)
1324 return;
1325
1326 // Pop everything that doesn't dominate the current block off the stack,
1327 // increment the PopEpoch to account for this.
1328 while (!VersionStack.empty()) {
1329 BasicBlock *BackBlock = VersionStack.back()->getBlock();
1330 if (DT->dominates(BackBlock, BB))
1331 break;
1332 while (VersionStack.back()->getBlock() == BackBlock)
1333 VersionStack.pop_back();
1334 ++PopEpoch;
1335 }
1336
1337 for (MemoryAccess &MA : *Accesses) {
1338 auto *MU = dyn_cast<MemoryUse>(&MA);
1339 if (!MU) {
1340 VersionStack.push_back(&MA);
1341 ++StackEpoch;
1342 continue;
1343 }
1344
George Burgess IV024f3d22016-08-03 19:57:02 +00001345 if (isUseTriviallyOptimizableToLiveOnEntry(*AA, MU->getMemoryInst())) {
1346 MU->setDefiningAccess(MSSA->getLiveOnEntryDef());
1347 continue;
1348 }
1349
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001350 MemoryLocOrCall UseMLOC(MU);
1351 auto &LocInfo = LocStackInfo[UseMLOC];
Daniel Berlin26fcea92016-08-02 20:02:21 +00001352 // If the pop epoch changed, it means we've removed stuff from top of
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001353 // stack due to changing blocks. We may have to reset the lower bound or
1354 // last kill info.
1355 if (LocInfo.PopEpoch != PopEpoch) {
1356 LocInfo.PopEpoch = PopEpoch;
1357 LocInfo.StackEpoch = StackEpoch;
1358 // If the lower bound was in the info we popped, we have to reset it.
1359 if (LocInfo.LowerBound >= VersionStack.size()) {
1360 // Reset the lower bound of things to check.
1361 // TODO: Some day we should be able to reset to last kill, rather than
1362 // 0.
1363
1364 LocInfo.LowerBound = 0;
1365 LocInfo.LastKillValid = false;
1366 }
1367 } else if (LocInfo.StackEpoch != StackEpoch) {
1368 // If all that has changed is the StackEpoch, we only have to check the
1369 // new things on the stack, because we've checked everything before. In
1370 // this case, the lower bound of things to check remains the same.
1371 LocInfo.PopEpoch = PopEpoch;
1372 LocInfo.StackEpoch = StackEpoch;
1373 }
1374 if (!LocInfo.LastKillValid) {
1375 LocInfo.LastKill = VersionStack.size() - 1;
1376 LocInfo.LastKillValid = true;
1377 }
1378
1379 // At this point, we should have corrected last kill and LowerBound to be
1380 // in bounds.
1381 assert(LocInfo.LowerBound < VersionStack.size() &&
1382 "Lower bound out of range");
1383 assert(LocInfo.LastKill < VersionStack.size() &&
1384 "Last kill info out of range");
1385 // In any case, the new upper bound is the top of the stack.
1386 unsigned long UpperBound = VersionStack.size() - 1;
1387
1388 if (UpperBound - LocInfo.LowerBound > MaxCheckLimit) {
Daniel Berlin26fcea92016-08-02 20:02:21 +00001389 DEBUG(dbgs() << "MemorySSA skipping optimization of " << *MU << " ("
1390 << *(MU->getMemoryInst()) << ")"
1391 << " because there are " << UpperBound - LocInfo.LowerBound
1392 << " stores to disambiguate\n");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001393 // Because we did not walk, LastKill is no longer valid, as this may
1394 // have been a kill.
1395 LocInfo.LastKillValid = false;
1396 continue;
1397 }
1398 bool FoundClobberResult = false;
1399 while (UpperBound > LocInfo.LowerBound) {
1400 if (isa<MemoryPhi>(VersionStack[UpperBound])) {
1401 // For phis, use the walker, see where we ended up, go there
1402 Instruction *UseInst = MU->getMemoryInst();
1403 MemoryAccess *Result = Walker->getClobberingMemoryAccess(UseInst);
1404 // We are guaranteed to find it or something is wrong
1405 while (VersionStack[UpperBound] != Result) {
1406 assert(UpperBound != 0);
1407 --UpperBound;
1408 }
1409 FoundClobberResult = true;
1410 break;
1411 }
1412
1413 MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]);
Daniel Berlindf101192016-08-03 00:01:46 +00001414 // If the lifetime of the pointer ends at this instruction, it's live on
1415 // entry.
1416 if (!UseMLOC.IsCall && lifetimeEndsAt(MD, UseMLOC.getLoc(), *AA)) {
1417 // Reset UpperBound to liveOnEntryDef's place in the stack
1418 UpperBound = 0;
1419 FoundClobberResult = true;
1420 break;
1421 }
Daniel Berlindff31de2016-08-02 21:57:52 +00001422 if (instructionClobbersQuery(MD, MU, UseMLOC, *AA)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001423 FoundClobberResult = true;
1424 break;
1425 }
1426 --UpperBound;
1427 }
1428 // At the end of this loop, UpperBound is either a clobber, or lower bound
1429 // PHI walking may cause it to be < LowerBound, and in fact, < LastKill.
1430 if (FoundClobberResult || UpperBound < LocInfo.LastKill) {
1431 MU->setDefiningAccess(VersionStack[UpperBound]);
1432 // We were last killed now by where we got to
1433 LocInfo.LastKill = UpperBound;
1434 } else {
1435 // Otherwise, we checked all the new ones, and now we know we can get to
1436 // LastKill.
1437 MU->setDefiningAccess(VersionStack[LocInfo.LastKill]);
1438 }
1439 LocInfo.LowerBound = VersionStack.size() - 1;
1440 }
1441}
1442
1443/// Optimize uses to point to their actual clobbering definitions.
1444void MemorySSA::OptimizeUses::optimizeUses() {
1445
1446 // We perform a non-recursive top-down dominator tree walk
1447 struct StackInfo {
1448 const DomTreeNode *Node;
1449 DomTreeNode::const_iterator Iter;
1450 };
1451
1452 SmallVector<MemoryAccess *, 16> VersionStack;
1453 SmallVector<StackInfo, 16> DomTreeWorklist;
1454 DenseMap<MemoryLocOrCall, MemlocStackInfo> LocStackInfo;
1455 DomTreeWorklist.push_back({DT->getRootNode(), DT->getRootNode()->begin()});
1456 // Bottom of the version stack is always live on entry.
1457 VersionStack.push_back(MSSA->getLiveOnEntryDef());
1458
1459 unsigned long StackEpoch = 1;
1460 unsigned long PopEpoch = 1;
1461 while (!DomTreeWorklist.empty()) {
1462 const auto *DomNode = DomTreeWorklist.back().Node;
1463 const auto DomIter = DomTreeWorklist.back().Iter;
1464 BasicBlock *BB = DomNode->getBlock();
1465 optimizeUsesInBlock(BB, StackEpoch, PopEpoch, VersionStack, LocStackInfo);
1466 if (DomIter == DomNode->end()) {
1467 // Hit the end, pop the worklist
1468 DomTreeWorklist.pop_back();
1469 continue;
1470 }
1471 // Move the iterator to the next child for the next time we get to process
1472 // children
1473 ++DomTreeWorklist.back().Iter;
1474
1475 // Now visit the next child
1476 DomTreeWorklist.push_back({*DomIter, (*DomIter)->begin()});
1477 }
1478}
1479
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001480void MemorySSA::buildMemorySSA() {
George Burgess IVe1100f52016-02-02 22:46:49 +00001481 // We create an access to represent "live on entry", for things like
1482 // arguments or users of globals, where the memory they use is defined before
1483 // the beginning of the function. We do not actually insert it into the IR.
1484 // We do not define a live on exit for the immediate uses, and thus our
1485 // semantics do *not* imply that something with no immediate uses can simply
1486 // be removed.
1487 BasicBlock &StartingPoint = F.getEntryBlock();
1488 LiveOnEntryDef = make_unique<MemoryDef>(F.getContext(), nullptr, nullptr,
1489 &StartingPoint, NextID++);
1490
1491 // We maintain lists of memory accesses per-block, trading memory for time. We
1492 // could just look up the memory access for every possible instruction in the
1493 // stream.
1494 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001495 SmallPtrSet<BasicBlock *, 32> DefUseBlocks;
George Burgess IVe1100f52016-02-02 22:46:49 +00001496 // Go through each block, figure out where defs occur, and chain together all
1497 // the accesses.
1498 for (BasicBlock &B : F) {
Daniel Berlin7898ca62016-02-07 01:52:15 +00001499 bool InsertIntoDef = false;
Daniel Berlinada263d2016-06-20 20:21:33 +00001500 AccessList *Accesses = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +00001501 for (Instruction &I : B) {
Peter Collingbourneffecb142016-05-26 01:19:17 +00001502 MemoryUseOrDef *MUD = createNewAccess(&I);
George Burgess IVb42b7622016-03-11 19:34:03 +00001503 if (!MUD)
George Burgess IVe1100f52016-02-02 22:46:49 +00001504 continue;
George Burgess IV3887a412016-03-21 21:25:39 +00001505 InsertIntoDef |= isa<MemoryDef>(MUD);
Daniel Berlin1b51a292016-02-07 01:52:19 +00001506
George Burgess IVe1100f52016-02-02 22:46:49 +00001507 if (!Accesses)
1508 Accesses = getOrCreateAccessList(&B);
George Burgess IVb42b7622016-03-11 19:34:03 +00001509 Accesses->push_back(MUD);
George Burgess IVe1100f52016-02-02 22:46:49 +00001510 }
Daniel Berlin7898ca62016-02-07 01:52:15 +00001511 if (InsertIntoDef)
1512 DefiningBlocks.insert(&B);
George Burgess IV3887a412016-03-21 21:25:39 +00001513 if (Accesses)
Daniel Berlin1b51a292016-02-07 01:52:19 +00001514 DefUseBlocks.insert(&B);
1515 }
1516
1517 // Compute live-in.
1518 // Live in is normally defined as "all the blocks on the path from each def to
1519 // each of it's uses".
1520 // MemoryDef's are implicit uses of previous state, so they are also uses.
1521 // This means we don't really have def-only instructions. The only
1522 // MemoryDef's that are not really uses are those that are of the LiveOnEntry
1523 // variable (because LiveOnEntry can reach anywhere, and every def is a
1524 // must-kill of LiveOnEntry).
1525 // In theory, you could precisely compute live-in by using alias-analysis to
1526 // disambiguate defs and uses to see which really pair up with which.
1527 // In practice, this would be really expensive and difficult. So we simply
1528 // assume all defs are also uses that need to be kept live.
1529 // Because of this, the end result of this live-in computation will be "the
1530 // entire set of basic blocks that reach any use".
1531
1532 SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
1533 SmallVector<BasicBlock *, 64> LiveInBlockWorklist(DefUseBlocks.begin(),
1534 DefUseBlocks.end());
1535 // Now that we have a set of blocks where a value is live-in, recursively add
1536 // predecessors until we find the full region the value is live.
1537 while (!LiveInBlockWorklist.empty()) {
1538 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
1539
1540 // The block really is live in here, insert it into the set. If already in
1541 // the set, then it has already been processed.
1542 if (!LiveInBlocks.insert(BB).second)
1543 continue;
1544
1545 // Since the value is live into BB, it is either defined in a predecessor or
1546 // live into it to.
1547 LiveInBlockWorklist.append(pred_begin(BB), pred_end(BB));
George Burgess IVe1100f52016-02-02 22:46:49 +00001548 }
1549
1550 // Determine where our MemoryPhi's should go
Daniel Berlin77fa84e2016-04-19 06:13:28 +00001551 ForwardIDFCalculator IDFs(*DT);
George Burgess IVe1100f52016-02-02 22:46:49 +00001552 IDFs.setDefiningBlocks(DefiningBlocks);
Daniel Berlin1b51a292016-02-07 01:52:19 +00001553 IDFs.setLiveInBlocks(LiveInBlocks);
George Burgess IVe1100f52016-02-02 22:46:49 +00001554 SmallVector<BasicBlock *, 32> IDFBlocks;
1555 IDFs.calculate(IDFBlocks);
1556
1557 // Now place MemoryPhi nodes.
1558 for (auto &BB : IDFBlocks) {
1559 // Insert phi node
Daniel Berlinada263d2016-06-20 20:21:33 +00001560 AccessList *Accesses = getOrCreateAccessList(BB);
Daniel Berlin14300262016-06-21 18:39:20 +00001561 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlin5130cc82016-07-31 21:08:20 +00001562 ValueToMemoryAccess[BB] = Phi;
George Burgess IVe1100f52016-02-02 22:46:49 +00001563 // Phi's always are placed at the front of the block.
1564 Accesses->push_front(Phi);
1565 }
1566
1567 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
1568 // filled in with all blocks.
1569 SmallPtrSet<BasicBlock *, 16> Visited;
1570 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1571
George Burgess IV5f308972016-07-19 01:29:15 +00001572 CachingWalker *Walker = getWalkerImpl();
1573
1574 // We're doing a batch of updates; don't drop useful caches between them.
1575 Walker->setAutoResetWalker(false);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001576 OptimizeUses(this, Walker, AA, DT).optimizeUses();
George Burgess IV5f308972016-07-19 01:29:15 +00001577 Walker->setAutoResetWalker(true);
1578 Walker->resetClobberWalker();
1579
George Burgess IVe1100f52016-02-02 22:46:49 +00001580 // Mark the uses in unreachable blocks as live on entry, so that they go
1581 // somewhere.
1582 for (auto &BB : F)
1583 if (!Visited.count(&BB))
1584 markUnreachableAsLiveOnEntry(&BB);
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001585}
George Burgess IVe1100f52016-02-02 22:46:49 +00001586
George Burgess IV5f308972016-07-19 01:29:15 +00001587MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
1588
1589MemorySSA::CachingWalker *MemorySSA::getWalkerImpl() {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001590 if (Walker)
1591 return Walker.get();
1592
1593 Walker = make_unique<CachingWalker>(this, AA, DT);
Geoff Berryb96d3b22016-06-01 21:30:40 +00001594 return Walker.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001595}
1596
Daniel Berlin14300262016-06-21 18:39:20 +00001597MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
1598 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
1599 AccessList *Accesses = getOrCreateAccessList(BB);
1600 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlin5130cc82016-07-31 21:08:20 +00001601 ValueToMemoryAccess[BB] = Phi;
Daniel Berlin14300262016-06-21 18:39:20 +00001602 // Phi's always are placed at the front of the block.
1603 Accesses->push_front(Phi);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001604 BlockNumberingValid.erase(BB);
Daniel Berlin14300262016-06-21 18:39:20 +00001605 return Phi;
1606}
1607
1608MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
1609 MemoryAccess *Definition) {
1610 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
1611 MemoryUseOrDef *NewAccess = createNewAccess(I);
1612 assert(
1613 NewAccess != nullptr &&
1614 "Tried to create a memory access for a non-memory touching instruction");
1615 NewAccess->setDefiningAccess(Definition);
1616 return NewAccess;
1617}
1618
1619MemoryAccess *MemorySSA::createMemoryAccessInBB(Instruction *I,
1620 MemoryAccess *Definition,
1621 const BasicBlock *BB,
1622 InsertionPlace Point) {
1623 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1624 auto *Accesses = getOrCreateAccessList(BB);
1625 if (Point == Beginning) {
1626 // It goes after any phi nodes
1627 auto AI = std::find_if(
1628 Accesses->begin(), Accesses->end(),
1629 [](const MemoryAccess &MA) { return !isa<MemoryPhi>(MA); });
1630
1631 Accesses->insert(AI, NewAccess);
1632 } else {
1633 Accesses->push_back(NewAccess);
1634 }
Daniel Berlin5c46b942016-07-19 22:49:43 +00001635 BlockNumberingValid.erase(BB);
Daniel Berlin14300262016-06-21 18:39:20 +00001636 return NewAccess;
1637}
1638MemoryAccess *MemorySSA::createMemoryAccessBefore(Instruction *I,
1639 MemoryAccess *Definition,
1640 MemoryAccess *InsertPt) {
1641 assert(I->getParent() == InsertPt->getBlock() &&
1642 "New and old access must be in the same block");
1643 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1644 auto *Accesses = getOrCreateAccessList(InsertPt->getBlock());
1645 Accesses->insert(AccessList::iterator(InsertPt), NewAccess);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001646 BlockNumberingValid.erase(InsertPt->getBlock());
Daniel Berlin14300262016-06-21 18:39:20 +00001647 return NewAccess;
1648}
1649
1650MemoryAccess *MemorySSA::createMemoryAccessAfter(Instruction *I,
1651 MemoryAccess *Definition,
1652 MemoryAccess *InsertPt) {
1653 assert(I->getParent() == InsertPt->getBlock() &&
1654 "New and old access must be in the same block");
1655 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1656 auto *Accesses = getOrCreateAccessList(InsertPt->getBlock());
1657 Accesses->insertAfter(AccessList::iterator(InsertPt), NewAccess);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001658 BlockNumberingValid.erase(InsertPt->getBlock());
Daniel Berlin14300262016-06-21 18:39:20 +00001659 return NewAccess;
1660}
1661
George Burgess IVe1100f52016-02-02 22:46:49 +00001662/// \brief Helper function to create new memory accesses
Peter Collingbourneffecb142016-05-26 01:19:17 +00001663MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I) {
Peter Collingbourneb9aa1f42016-05-26 04:58:46 +00001664 // The assume intrinsic has a control dependency which we model by claiming
1665 // that it writes arbitrarily. Ignore that fake memory dependency here.
1666 // FIXME: Replace this special casing with a more accurate modelling of
1667 // assume's control dependency.
1668 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1669 if (II->getIntrinsicID() == Intrinsic::assume)
1670 return nullptr;
1671
George Burgess IVe1100f52016-02-02 22:46:49 +00001672 // Find out what affect this instruction has on memory.
1673 ModRefInfo ModRef = AA->getModRefInfo(I);
1674 bool Def = bool(ModRef & MRI_Mod);
1675 bool Use = bool(ModRef & MRI_Ref);
1676
1677 // It's possible for an instruction to not modify memory at all. During
1678 // construction, we ignore them.
Peter Collingbourneffecb142016-05-26 01:19:17 +00001679 if (!Def && !Use)
George Burgess IVe1100f52016-02-02 22:46:49 +00001680 return nullptr;
1681
1682 assert((Def || Use) &&
1683 "Trying to create a memory access with a non-memory instruction");
1684
George Burgess IVb42b7622016-03-11 19:34:03 +00001685 MemoryUseOrDef *MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001686 if (Def)
George Burgess IVb42b7622016-03-11 19:34:03 +00001687 MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
George Burgess IVe1100f52016-02-02 22:46:49 +00001688 else
George Burgess IVb42b7622016-03-11 19:34:03 +00001689 MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
Daniel Berlin5130cc82016-07-31 21:08:20 +00001690 ValueToMemoryAccess[I] = MUD;
George Burgess IVb42b7622016-03-11 19:34:03 +00001691 return MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001692}
1693
1694MemoryAccess *MemorySSA::findDominatingDef(BasicBlock *UseBlock,
1695 enum InsertionPlace Where) {
1696 // Handle the initial case
1697 if (Where == Beginning)
1698 // The only thing that could define us at the beginning is a phi node
1699 if (MemoryPhi *Phi = getMemoryAccess(UseBlock))
1700 return Phi;
1701
1702 DomTreeNode *CurrNode = DT->getNode(UseBlock);
1703 // Need to be defined by our dominator
1704 if (Where == Beginning)
1705 CurrNode = CurrNode->getIDom();
1706 Where = End;
1707 while (CurrNode) {
1708 auto It = PerBlockAccesses.find(CurrNode->getBlock());
1709 if (It != PerBlockAccesses.end()) {
1710 auto &Accesses = It->second;
David Majnemerd7708772016-06-24 04:05:21 +00001711 for (MemoryAccess &RA : reverse(*Accesses)) {
1712 if (isa<MemoryDef>(RA) || isa<MemoryPhi>(RA))
1713 return &RA;
George Burgess IVe1100f52016-02-02 22:46:49 +00001714 }
1715 }
1716 CurrNode = CurrNode->getIDom();
1717 }
1718 return LiveOnEntryDef.get();
1719}
1720
1721/// \brief Returns true if \p Replacer dominates \p Replacee .
1722bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
1723 const MemoryAccess *Replacee) const {
1724 if (isa<MemoryUseOrDef>(Replacee))
1725 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
1726 const auto *MP = cast<MemoryPhi>(Replacee);
1727 // For a phi node, the use occurs in the predecessor block of the phi node.
1728 // Since we may occur multiple times in the phi node, we have to check each
1729 // operand to ensure Replacer dominates each operand where Replacee occurs.
1730 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +00001731 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +00001732 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
1733 return false;
1734 }
1735 return true;
1736}
1737
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001738/// \brief If all arguments of a MemoryPHI are defined by the same incoming
1739/// argument, return that argument.
1740static MemoryAccess *onlySingleValue(MemoryPhi *MP) {
1741 MemoryAccess *MA = nullptr;
1742
1743 for (auto &Arg : MP->operands()) {
1744 if (!MA)
1745 MA = cast<MemoryAccess>(Arg);
1746 else if (MA != Arg)
1747 return nullptr;
1748 }
1749 return MA;
1750}
1751
1752/// \brief Properly remove \p MA from all of MemorySSA's lookup tables.
1753///
1754/// Because of the way the intrusive list and use lists work, it is important to
1755/// do removal in the right order.
1756void MemorySSA::removeFromLookups(MemoryAccess *MA) {
1757 assert(MA->use_empty() &&
1758 "Trying to remove memory access that still has uses");
Daniel Berlin5c46b942016-07-19 22:49:43 +00001759 BlockNumbering.erase(MA);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001760 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA))
1761 MUD->setDefiningAccess(nullptr);
1762 // Invalidate our walker's cache if necessary
1763 if (!isa<MemoryUse>(MA))
1764 Walker->invalidateInfo(MA);
1765 // The call below to erase will destroy MA, so we can't change the order we
1766 // are doing things here
1767 Value *MemoryInst;
1768 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
1769 MemoryInst = MUD->getMemoryInst();
1770 } else {
1771 MemoryInst = MA->getBlock();
1772 }
Daniel Berlin5130cc82016-07-31 21:08:20 +00001773 auto VMA = ValueToMemoryAccess.find(MemoryInst);
1774 if (VMA->second == MA)
1775 ValueToMemoryAccess.erase(VMA);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001776
George Burgess IVe0e6e482016-03-02 02:35:04 +00001777 auto AccessIt = PerBlockAccesses.find(MA->getBlock());
Daniel Berlinada263d2016-06-20 20:21:33 +00001778 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001779 Accesses->erase(MA);
George Burgess IVe0e6e482016-03-02 02:35:04 +00001780 if (Accesses->empty())
1781 PerBlockAccesses.erase(AccessIt);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001782}
1783
1784void MemorySSA::removeMemoryAccess(MemoryAccess *MA) {
1785 assert(!isLiveOnEntryDef(MA) && "Trying to remove the live on entry def");
1786 // We can only delete phi nodes if they have no uses, or we can replace all
1787 // uses with a single definition.
1788 MemoryAccess *NewDefTarget = nullptr;
1789 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(MA)) {
1790 // Note that it is sufficient to know that all edges of the phi node have
1791 // the same argument. If they do, by the definition of dominance frontiers
1792 // (which we used to place this phi), that argument must dominate this phi,
1793 // and thus, must dominate the phi's uses, and so we will not hit the assert
1794 // below.
1795 NewDefTarget = onlySingleValue(MP);
1796 assert((NewDefTarget || MP->use_empty()) &&
1797 "We can't delete this memory phi");
1798 } else {
1799 NewDefTarget = cast<MemoryUseOrDef>(MA)->getDefiningAccess();
1800 }
1801
1802 // Re-point the uses at our defining access
1803 if (!MA->use_empty())
1804 MA->replaceAllUsesWith(NewDefTarget);
1805
1806 // The call below to erase will destroy MA, so we can't change the order we
1807 // are doing things here
1808 removeFromLookups(MA);
1809}
1810
George Burgess IVe1100f52016-02-02 22:46:49 +00001811void MemorySSA::print(raw_ostream &OS) const {
1812 MemorySSAAnnotatedWriter Writer(this);
1813 F.print(OS, &Writer);
1814}
1815
1816void MemorySSA::dump() const {
1817 MemorySSAAnnotatedWriter Writer(this);
1818 F.print(dbgs(), &Writer);
1819}
1820
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001821void MemorySSA::verifyMemorySSA() const {
1822 verifyDefUses(F);
1823 verifyDomination(F);
Daniel Berlin14300262016-06-21 18:39:20 +00001824 verifyOrdering(F);
1825}
1826
1827/// \brief Verify that the order and existence of MemoryAccesses matches the
1828/// order and existence of memory affecting instructions.
1829void MemorySSA::verifyOrdering(Function &F) const {
1830 // Walk all the blocks, comparing what the lookups think and what the access
1831 // lists think, as well as the order in the blocks vs the order in the access
1832 // lists.
1833 SmallVector<MemoryAccess *, 32> ActualAccesses;
1834 for (BasicBlock &B : F) {
1835 const AccessList *AL = getBlockAccesses(&B);
1836 MemoryAccess *Phi = getMemoryAccess(&B);
1837 if (Phi)
1838 ActualAccesses.push_back(Phi);
1839 for (Instruction &I : B) {
1840 MemoryAccess *MA = getMemoryAccess(&I);
1841 assert((!MA || AL) && "We have memory affecting instructions "
1842 "in this block but they are not in the "
1843 "access list");
1844 if (MA)
1845 ActualAccesses.push_back(MA);
1846 }
1847 // Either we hit the assert, really have no accesses, or we have both
1848 // accesses and an access list
1849 if (!AL)
1850 continue;
1851 assert(AL->size() == ActualAccesses.size() &&
1852 "We don't have the same number of accesses in the block as on the "
1853 "access list");
1854 auto ALI = AL->begin();
1855 auto AAI = ActualAccesses.begin();
1856 while (ALI != AL->end() && AAI != ActualAccesses.end()) {
1857 assert(&*ALI == *AAI && "Not the same accesses in the same order");
1858 ++ALI;
1859 ++AAI;
1860 }
1861 ActualAccesses.clear();
1862 }
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001863}
1864
George Burgess IVe1100f52016-02-02 22:46:49 +00001865/// \brief Verify the domination properties of MemorySSA by checking that each
1866/// definition dominates all of its uses.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001867void MemorySSA::verifyDomination(Function &F) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001868#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001869 for (BasicBlock &B : F) {
1870 // Phi nodes are attached to basic blocks
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001871 if (MemoryPhi *MP = getMemoryAccess(&B))
1872 for (const Use &U : MP->uses())
1873 assert(dominates(MP, U) && "Memory PHI does not dominate it's uses");
Daniel Berlin7af95872016-08-05 21:47:20 +00001874
George Burgess IVe1100f52016-02-02 22:46:49 +00001875 for (Instruction &I : B) {
1876 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
1877 if (!MD)
1878 continue;
1879
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001880 for (const Use &U : MD->uses())
1881 assert(dominates(MD, U) && "Memory Def does not dominate it's uses");
George Burgess IVe1100f52016-02-02 22:46:49 +00001882 }
1883 }
Daniel Berlin7af95872016-08-05 21:47:20 +00001884#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001885}
1886
1887/// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use
1888/// appears in the use list of \p Def.
Daniel Berlin7af95872016-08-05 21:47:20 +00001889
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001890void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001891#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001892 // The live on entry use may cause us to get a NULL def here
Daniel Berlin7af95872016-08-05 21:47:20 +00001893 if (!Def)
1894 assert(isLiveOnEntryDef(Use) &&
1895 "Null def but use not point to live on entry def");
1896 else
1897 assert(find(Def->users(), Use) != Def->user_end() &&
1898 "Did not find use in def's use list");
1899#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001900}
1901
1902/// \brief Verify the immediate use information, by walking all the memory
1903/// accesses and verifying that, for each use, it appears in the
1904/// appropriate def's use list
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001905void MemorySSA::verifyDefUses(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001906 for (BasicBlock &B : F) {
1907 // Phi nodes are attached to basic blocks
Daniel Berlin14300262016-06-21 18:39:20 +00001908 if (MemoryPhi *Phi = getMemoryAccess(&B)) {
David Majnemer580e7542016-06-25 00:04:06 +00001909 assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
1910 pred_begin(&B), pred_end(&B))) &&
Daniel Berlin14300262016-06-21 18:39:20 +00001911 "Incomplete MemoryPhi Node");
George Burgess IVe1100f52016-02-02 22:46:49 +00001912 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
1913 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
Daniel Berlin14300262016-06-21 18:39:20 +00001914 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001915
1916 for (Instruction &I : B) {
1917 if (MemoryAccess *MA = getMemoryAccess(&I)) {
1918 assert(isa<MemoryUseOrDef>(MA) &&
1919 "Found a phi node not attached to a bb");
1920 verifyUseInDefs(cast<MemoryUseOrDef>(MA)->getDefiningAccess(), MA);
1921 }
1922 }
1923 }
1924}
1925
1926MemoryAccess *MemorySSA::getMemoryAccess(const Value *I) const {
Daniel Berlinf6c9ae92016-02-10 17:41:25 +00001927 return ValueToMemoryAccess.lookup(I);
George Burgess IVe1100f52016-02-02 22:46:49 +00001928}
1929
1930MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const {
1931 return cast_or_null<MemoryPhi>(getMemoryAccess((const Value *)BB));
1932}
1933
Daniel Berlin5c46b942016-07-19 22:49:43 +00001934/// Perform a local numbering on blocks so that instruction ordering can be
1935/// determined in constant time.
1936/// TODO: We currently just number in order. If we numbered by N, we could
1937/// allow at least N-1 sequences of insertBefore or insertAfter (and at least
1938/// log2(N) sequences of mixed before and after) without needing to invalidate
1939/// the numbering.
1940void MemorySSA::renumberBlock(const BasicBlock *B) const {
1941 // The pre-increment ensures the numbers really start at 1.
1942 unsigned long CurrentNumber = 0;
1943 const AccessList *AL = getBlockAccesses(B);
1944 assert(AL != nullptr && "Asking to renumber an empty block");
1945 for (const auto &I : *AL)
1946 BlockNumbering[&I] = ++CurrentNumber;
1947 BlockNumberingValid.insert(B);
1948}
1949
George Burgess IVe1100f52016-02-02 22:46:49 +00001950/// \brief Determine, for two memory accesses in the same block,
1951/// whether \p Dominator dominates \p Dominatee.
1952/// \returns True if \p Dominator dominates \p Dominatee.
1953bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
1954 const MemoryAccess *Dominatee) const {
Sebastian Pope1f60b12016-06-10 21:36:41 +00001955
Daniel Berlin5c46b942016-07-19 22:49:43 +00001956 const BasicBlock *DominatorBlock = Dominator->getBlock();
Daniel Berlin5c46b942016-07-19 22:49:43 +00001957
Daniel Berlin19860302016-07-19 23:08:08 +00001958 assert((DominatorBlock == Dominatee->getBlock()) &&
Daniel Berlin5c46b942016-07-19 22:49:43 +00001959 "Asking for local domination when accesses are in different blocks!");
Sebastian Pope1f60b12016-06-10 21:36:41 +00001960 // A node dominates itself.
1961 if (Dominatee == Dominator)
1962 return true;
1963
1964 // When Dominatee is defined on function entry, it is not dominated by another
1965 // memory access.
1966 if (isLiveOnEntryDef(Dominatee))
1967 return false;
1968
1969 // When Dominator is defined on function entry, it dominates the other memory
1970 // access.
1971 if (isLiveOnEntryDef(Dominator))
1972 return true;
1973
Daniel Berlin5c46b942016-07-19 22:49:43 +00001974 if (!BlockNumberingValid.count(DominatorBlock))
1975 renumberBlock(DominatorBlock);
George Burgess IVe1100f52016-02-02 22:46:49 +00001976
Daniel Berlin5c46b942016-07-19 22:49:43 +00001977 unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
1978 // All numbers start with 1
1979 assert(DominatorNum != 0 && "Block was not numbered properly");
1980 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
1981 assert(DominateeNum != 0 && "Block was not numbered properly");
1982 return DominatorNum < DominateeNum;
George Burgess IVe1100f52016-02-02 22:46:49 +00001983}
1984
George Burgess IV5f308972016-07-19 01:29:15 +00001985bool MemorySSA::dominates(const MemoryAccess *Dominator,
1986 const MemoryAccess *Dominatee) const {
1987 if (Dominator == Dominatee)
1988 return true;
1989
1990 if (isLiveOnEntryDef(Dominatee))
1991 return false;
1992
1993 if (Dominator->getBlock() != Dominatee->getBlock())
1994 return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
1995 return locallyDominates(Dominator, Dominatee);
1996}
1997
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001998bool MemorySSA::dominates(const MemoryAccess *Dominator,
1999 const Use &Dominatee) const {
2000 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Dominatee.getUser())) {
2001 BasicBlock *UseBB = MP->getIncomingBlock(Dominatee);
2002 // The def must dominate the incoming block of the phi.
2003 if (UseBB != Dominator->getBlock())
2004 return DT->dominates(Dominator->getBlock(), UseBB);
2005 // If the UseBB and the DefBB are the same, compare locally.
2006 return locallyDominates(Dominator, cast<MemoryAccess>(Dominatee));
2007 }
2008 // If it's not a PHI node use, the normal dominates can already handle it.
2009 return dominates(Dominator, cast<MemoryAccess>(Dominatee.getUser()));
2010}
2011
George Burgess IVe1100f52016-02-02 22:46:49 +00002012const static char LiveOnEntryStr[] = "liveOnEntry";
2013
2014void MemoryDef::print(raw_ostream &OS) const {
2015 MemoryAccess *UO = getDefiningAccess();
2016
2017 OS << getID() << " = MemoryDef(";
2018 if (UO && UO->getID())
2019 OS << UO->getID();
2020 else
2021 OS << LiveOnEntryStr;
2022 OS << ')';
2023}
2024
2025void MemoryPhi::print(raw_ostream &OS) const {
2026 bool First = true;
2027 OS << getID() << " = MemoryPhi(";
2028 for (const auto &Op : operands()) {
2029 BasicBlock *BB = getIncomingBlock(Op);
2030 MemoryAccess *MA = cast<MemoryAccess>(Op);
2031 if (!First)
2032 OS << ',';
2033 else
2034 First = false;
2035
2036 OS << '{';
2037 if (BB->hasName())
2038 OS << BB->getName();
2039 else
2040 BB->printAsOperand(OS, false);
2041 OS << ',';
2042 if (unsigned ID = MA->getID())
2043 OS << ID;
2044 else
2045 OS << LiveOnEntryStr;
2046 OS << '}';
2047 }
2048 OS << ')';
2049}
2050
2051MemoryAccess::~MemoryAccess() {}
2052
2053void MemoryUse::print(raw_ostream &OS) const {
2054 MemoryAccess *UO = getDefiningAccess();
2055 OS << "MemoryUse(";
2056 if (UO && UO->getID())
2057 OS << UO->getID();
2058 else
2059 OS << LiveOnEntryStr;
2060 OS << ')';
2061}
2062
2063void MemoryAccess::dump() const {
2064 print(dbgs());
2065 dbgs() << "\n";
2066}
2067
Chad Rosier232e29e2016-07-06 21:20:47 +00002068char MemorySSAPrinterLegacyPass::ID = 0;
2069
2070MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) {
2071 initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
2072}
2073
2074void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
2075 AU.setPreservesAll();
2076 AU.addRequired<MemorySSAWrapperPass>();
2077 AU.addPreserved<MemorySSAWrapperPass>();
2078}
2079
2080bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) {
2081 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
2082 MSSA.print(dbgs());
2083 if (VerifyMemorySSA)
2084 MSSA.verifyMemorySSA();
2085 return false;
2086}
2087
Geoff Berryb96d3b22016-06-01 21:30:40 +00002088char MemorySSAAnalysis::PassID;
George Burgess IVe1100f52016-02-02 22:46:49 +00002089
Geoff Berryb96d3b22016-06-01 21:30:40 +00002090MemorySSA MemorySSAAnalysis::run(Function &F, AnalysisManager<Function> &AM) {
2091 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2092 auto &AA = AM.getResult<AAManager>(F);
2093 return MemorySSA(F, &AA, &DT);
George Burgess IVe1100f52016-02-02 22:46:49 +00002094}
2095
Geoff Berryb96d3b22016-06-01 21:30:40 +00002096PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
2097 FunctionAnalysisManager &AM) {
2098 OS << "MemorySSA for function: " << F.getName() << "\n";
2099 AM.getResult<MemorySSAAnalysis>(F).print(OS);
2100
2101 return PreservedAnalyses::all();
George Burgess IVe1100f52016-02-02 22:46:49 +00002102}
2103
Geoff Berryb96d3b22016-06-01 21:30:40 +00002104PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
2105 FunctionAnalysisManager &AM) {
2106 AM.getResult<MemorySSAAnalysis>(F).verifyMemorySSA();
2107
2108 return PreservedAnalyses::all();
2109}
2110
2111char MemorySSAWrapperPass::ID = 0;
2112
2113MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
2114 initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
2115}
2116
2117void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
2118
2119void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00002120 AU.setPreservesAll();
Geoff Berryb96d3b22016-06-01 21:30:40 +00002121 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
2122 AU.addRequiredTransitive<AAResultsWrapperPass>();
George Burgess IVe1100f52016-02-02 22:46:49 +00002123}
2124
Geoff Berryb96d3b22016-06-01 21:30:40 +00002125bool MemorySSAWrapperPass::runOnFunction(Function &F) {
2126 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2127 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2128 MSSA.reset(new MemorySSA(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00002129 return false;
2130}
2131
Geoff Berryb96d3b22016-06-01 21:30:40 +00002132void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); }
George Burgess IVe1100f52016-02-02 22:46:49 +00002133
Geoff Berryb96d3b22016-06-01 21:30:40 +00002134void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00002135 MSSA->print(OS);
2136}
2137
George Burgess IVe1100f52016-02-02 22:46:49 +00002138MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
2139
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002140MemorySSA::CachingWalker::CachingWalker(MemorySSA *M, AliasAnalysis *A,
2141 DominatorTree *D)
Daniel Berlin5c46b942016-07-19 22:49:43 +00002142 : MemorySSAWalker(M), Walker(*M, *A, *D, Cache), AutoResetWalker(true) {}
George Burgess IVe1100f52016-02-02 22:46:49 +00002143
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002144MemorySSA::CachingWalker::~CachingWalker() {}
George Burgess IVe1100f52016-02-02 22:46:49 +00002145
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002146void MemorySSA::CachingWalker::invalidateInfo(MemoryAccess *MA) {
Daniel Berlin83fc77b2016-03-01 18:46:54 +00002147 // TODO: We can do much better cache invalidation with differently stored
2148 // caches. For now, for MemoryUses, we simply remove them
2149 // from the cache, and kill the entire call/non-call cache for everything
2150 // else. The problem is for phis or defs, currently we'd need to follow use
2151 // chains down and invalidate anything below us in the chain that currently
2152 // terminates at this access.
2153
2154 // See if this is a MemoryUse, if so, just remove the cached info. MemoryUse
2155 // is by definition never a barrier, so nothing in the cache could point to
2156 // this use. In that case, we only need invalidate the info for the use
2157 // itself.
2158
2159 if (MemoryUse *MU = dyn_cast<MemoryUse>(MA)) {
George Burgess IV5f308972016-07-19 01:29:15 +00002160 UpwardsMemoryQuery Q(MU->getMemoryInst(), MU);
2161 Cache.remove(MU, Q.StartingLoc, Q.IsCall);
Geoff Berry9fe26e62016-04-22 14:44:10 +00002162 } else {
2163 // If it is not a use, the best we can do right now is destroy the cache.
George Burgess IV5f308972016-07-19 01:29:15 +00002164 Cache.clear();
Geoff Berry9fe26e62016-04-22 14:44:10 +00002165 }
2166
Filipe Cabecinhas0da99372016-04-29 15:22:48 +00002167#ifdef EXPENSIVE_CHECKS
Geoff Berry9fe26e62016-04-22 14:44:10 +00002168 verifyRemoved(MA);
2169#endif
Daniel Berlin83fc77b2016-03-01 18:46:54 +00002170}
2171
George Burgess IVe1100f52016-02-02 22:46:49 +00002172/// \brief Walk the use-def chains starting at \p MA and find
2173/// the MemoryAccess that actually clobbers Loc.
2174///
2175/// \returns our clobbering memory access
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002176MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
2177 MemoryAccess *StartingAccess, UpwardsMemoryQuery &Q) {
George Burgess IV5f308972016-07-19 01:29:15 +00002178 MemoryAccess *New = Walker.findClobber(StartingAccess, Q);
2179#ifdef EXPENSIVE_CHECKS
2180 MemoryAccess *NewNoCache =
2181 Walker.findClobber(StartingAccess, Q, /*UseWalkerCache=*/false);
2182 assert(NewNoCache == New && "Cache made us hand back a different result?");
2183#endif
2184 if (AutoResetWalker)
2185 resetClobberWalker();
2186 return New;
George Burgess IVe1100f52016-02-02 22:46:49 +00002187}
2188
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002189MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
2190 MemoryAccess *StartingAccess, MemoryLocation &Loc) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002191 if (isa<MemoryPhi>(StartingAccess))
2192 return StartingAccess;
2193
2194 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
2195 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
2196 return StartingUseOrDef;
2197
2198 Instruction *I = StartingUseOrDef->getMemoryInst();
2199
2200 // Conservatively, fences are always clobbers, so don't perform the walk if we
2201 // hit a fence.
David Majnemera940f362016-07-15 17:19:24 +00002202 if (!ImmutableCallSite(I) && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002203 return StartingUseOrDef;
2204
2205 UpwardsMemoryQuery Q;
2206 Q.OriginalAccess = StartingUseOrDef;
2207 Q.StartingLoc = Loc;
George Burgess IV5f308972016-07-19 01:29:15 +00002208 Q.Inst = I;
George Burgess IVe1100f52016-02-02 22:46:49 +00002209 Q.IsCall = false;
George Burgess IVe1100f52016-02-02 22:46:49 +00002210
George Burgess IV5f308972016-07-19 01:29:15 +00002211 if (auto *CacheResult = Cache.lookup(StartingUseOrDef, Loc, Q.IsCall))
George Burgess IVe1100f52016-02-02 22:46:49 +00002212 return CacheResult;
2213
2214 // Unlike the other function, do not walk to the def of a def, because we are
2215 // handed something we already believe is the clobbering access.
2216 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
2217 ? StartingUseOrDef->getDefiningAccess()
2218 : StartingUseOrDef;
2219
2220 MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00002221 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2222 DEBUG(dbgs() << *StartingUseOrDef << "\n");
2223 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2224 DEBUG(dbgs() << *Clobber << "\n");
2225 return Clobber;
2226}
2227
2228MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002229MemorySSA::CachingWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
2230 auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
2231 // If this is a MemoryPhi, we can't do anything.
2232 if (!StartingAccess)
2233 return MA;
George Burgess IVe1100f52016-02-02 22:46:49 +00002234
George Burgess IV400ae402016-07-20 19:51:34 +00002235 const Instruction *I = StartingAccess->getMemoryInst();
George Burgess IV5f308972016-07-19 01:29:15 +00002236 UpwardsMemoryQuery Q(I, StartingAccess);
David Majnemera940f362016-07-15 17:19:24 +00002237 // We can't sanely do anything with a fences, they conservatively
George Burgess IVe1100f52016-02-02 22:46:49 +00002238 // clobber all memory, and have no locations to get pointers from to
David Majnemera940f362016-07-15 17:19:24 +00002239 // try to disambiguate.
George Burgess IV5f308972016-07-19 01:29:15 +00002240 if (!Q.IsCall && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002241 return StartingAccess;
2242
George Burgess IV5f308972016-07-19 01:29:15 +00002243 if (auto *CacheResult = Cache.lookup(StartingAccess, Q.StartingLoc, Q.IsCall))
George Burgess IVe1100f52016-02-02 22:46:49 +00002244 return CacheResult;
2245
George Burgess IV024f3d22016-08-03 19:57:02 +00002246 if (isUseTriviallyOptimizableToLiveOnEntry(*MSSA->AA, I)) {
2247 MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef();
2248 Cache.insert(StartingAccess, LiveOnEntry, Q.StartingLoc, Q.IsCall);
2249 return LiveOnEntry;
2250 }
2251
George Burgess IVe1100f52016-02-02 22:46:49 +00002252 // Start with the thing we already think clobbers this location
2253 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
2254
2255 // At this point, DefiningAccess may be the live on entry def.
2256 // If it is, we will not get a better result.
2257 if (MSSA->isLiveOnEntryDef(DefiningAccess))
2258 return DefiningAccess;
2259
2260 MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00002261 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2262 DEBUG(dbgs() << *DefiningAccess << "\n");
2263 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2264 DEBUG(dbgs() << *Result << "\n");
2265
2266 return Result;
2267}
2268
Geoff Berry9fe26e62016-04-22 14:44:10 +00002269// Verify that MA doesn't exist in any of the caches.
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002270void MemorySSA::CachingWalker::verifyRemoved(MemoryAccess *MA) {
George Burgess IV5f308972016-07-19 01:29:15 +00002271 assert(!Cache.contains(MA) && "Found removed MemoryAccess in cache.");
Geoff Berry9fe26e62016-04-22 14:44:10 +00002272}
2273
George Burgess IVe1100f52016-02-02 22:46:49 +00002274MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002275DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002276 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
2277 return Use->getDefiningAccess();
2278 return MA;
2279}
2280
2281MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
2282 MemoryAccess *StartingAccess, MemoryLocation &) {
2283 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
2284 return Use->getDefiningAccess();
2285 return StartingAccess;
2286}
George Burgess IV5f308972016-07-19 01:29:15 +00002287} // namespace llvm