blob: 30c8bd09547ac68296b38dc549bd63e803320ba1 [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)),
1239 Walker(std::move(MSSA.Walker)), NextID(MSSA.NextID) {
1240 // Update the Walker MSSA pointer so it doesn't point to the moved-from MSSA
1241 // object any more.
1242 Walker->MSSA = this;
1243}
George Burgess IVe1100f52016-02-02 22:46:49 +00001244
1245MemorySSA::~MemorySSA() {
1246 // Drop all our references
1247 for (const auto &Pair : PerBlockAccesses)
1248 for (MemoryAccess &MA : *Pair.second)
1249 MA.dropAllReferences();
1250}
1251
Daniel Berlin14300262016-06-21 18:39:20 +00001252MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001253 auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
1254
1255 if (Res.second)
Daniel Berlinada263d2016-06-20 20:21:33 +00001256 Res.first->second = make_unique<AccessList>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001257 return Res.first->second.get();
1258}
1259
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001260/// This class is a batch walker of all MemoryUse's in the program, and points
1261/// their defining access at the thing that actually clobbers them. Because it
1262/// is a batch walker that touches everything, it does not operate like the
1263/// other walkers. This walker is basically performing a top-down SSA renaming
1264/// pass, where the version stack is used as the cache. This enables it to be
1265/// significantly more time and memory efficient than using the regular walker,
1266/// which is walking bottom-up.
1267class MemorySSA::OptimizeUses {
1268public:
1269 OptimizeUses(MemorySSA *MSSA, MemorySSAWalker *Walker, AliasAnalysis *AA,
1270 DominatorTree *DT)
1271 : MSSA(MSSA), Walker(Walker), AA(AA), DT(DT) {
1272 Walker = MSSA->getWalker();
1273 }
1274
1275 void optimizeUses();
1276
1277private:
1278 /// This represents where a given memorylocation is in the stack.
1279 struct MemlocStackInfo {
1280 // This essentially is keeping track of versions of the stack. Whenever
1281 // the stack changes due to pushes or pops, these versions increase.
1282 unsigned long StackEpoch;
1283 unsigned long PopEpoch;
1284 // This is the lower bound of places on the stack to check. It is equal to
1285 // the place the last stack walk ended.
1286 // Note: Correctness depends on this being initialized to 0, which densemap
1287 // does
1288 unsigned long LowerBound;
1289 // This is where the last walk for this memory location ended.
1290 unsigned long LastKill;
1291 bool LastKillValid;
1292 };
1293 void optimizeUsesInBlock(const BasicBlock *, unsigned long &, unsigned long &,
1294 SmallVectorImpl<MemoryAccess *> &,
1295 DenseMap<MemoryLocOrCall, MemlocStackInfo> &);
1296 MemorySSA *MSSA;
1297 MemorySSAWalker *Walker;
1298 AliasAnalysis *AA;
1299 DominatorTree *DT;
1300};
1301
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001302/// Optimize the uses in a given block This is basically the SSA renaming
1303/// algorithm, with one caveat: We are able to use a single stack for all
1304/// MemoryUses. This is because the set of *possible* reaching MemoryDefs is
1305/// the same for every MemoryUse. The *actual* clobbering MemoryDef is just
1306/// going to be some position in that stack of possible ones.
1307///
1308/// We track the stack positions that each MemoryLocation needs
1309/// to check, and last ended at. This is because we only want to check the
1310/// things that changed since last time. The same MemoryLocation should
1311/// get clobbered by the same store (getModRefInfo does not use invariantness or
1312/// things like this, and if they start, we can modify MemoryLocOrCall to
1313/// include relevant data)
1314void MemorySSA::OptimizeUses::optimizeUsesInBlock(
1315 const BasicBlock *BB, unsigned long &StackEpoch, unsigned long &PopEpoch,
1316 SmallVectorImpl<MemoryAccess *> &VersionStack,
1317 DenseMap<MemoryLocOrCall, MemlocStackInfo> &LocStackInfo) {
1318
1319 /// If no accesses, nothing to do.
1320 MemorySSA::AccessList *Accesses = MSSA->getWritableBlockAccesses(BB);
1321 if (Accesses == nullptr)
1322 return;
1323
1324 // Pop everything that doesn't dominate the current block off the stack,
1325 // increment the PopEpoch to account for this.
1326 while (!VersionStack.empty()) {
1327 BasicBlock *BackBlock = VersionStack.back()->getBlock();
1328 if (DT->dominates(BackBlock, BB))
1329 break;
1330 while (VersionStack.back()->getBlock() == BackBlock)
1331 VersionStack.pop_back();
1332 ++PopEpoch;
1333 }
1334
1335 for (MemoryAccess &MA : *Accesses) {
1336 auto *MU = dyn_cast<MemoryUse>(&MA);
1337 if (!MU) {
1338 VersionStack.push_back(&MA);
1339 ++StackEpoch;
1340 continue;
1341 }
1342
George Burgess IV024f3d22016-08-03 19:57:02 +00001343 if (isUseTriviallyOptimizableToLiveOnEntry(*AA, MU->getMemoryInst())) {
1344 MU->setDefiningAccess(MSSA->getLiveOnEntryDef());
1345 continue;
1346 }
1347
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001348 MemoryLocOrCall UseMLOC(MU);
1349 auto &LocInfo = LocStackInfo[UseMLOC];
Daniel Berlin26fcea92016-08-02 20:02:21 +00001350 // If the pop epoch changed, it means we've removed stuff from top of
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001351 // stack due to changing blocks. We may have to reset the lower bound or
1352 // last kill info.
1353 if (LocInfo.PopEpoch != PopEpoch) {
1354 LocInfo.PopEpoch = PopEpoch;
1355 LocInfo.StackEpoch = StackEpoch;
1356 // If the lower bound was in the info we popped, we have to reset it.
1357 if (LocInfo.LowerBound >= VersionStack.size()) {
1358 // Reset the lower bound of things to check.
1359 // TODO: Some day we should be able to reset to last kill, rather than
1360 // 0.
1361
1362 LocInfo.LowerBound = 0;
1363 LocInfo.LastKillValid = false;
1364 }
1365 } else if (LocInfo.StackEpoch != StackEpoch) {
1366 // If all that has changed is the StackEpoch, we only have to check the
1367 // new things on the stack, because we've checked everything before. In
1368 // this case, the lower bound of things to check remains the same.
1369 LocInfo.PopEpoch = PopEpoch;
1370 LocInfo.StackEpoch = StackEpoch;
1371 }
1372 if (!LocInfo.LastKillValid) {
1373 LocInfo.LastKill = VersionStack.size() - 1;
1374 LocInfo.LastKillValid = true;
1375 }
1376
1377 // At this point, we should have corrected last kill and LowerBound to be
1378 // in bounds.
1379 assert(LocInfo.LowerBound < VersionStack.size() &&
1380 "Lower bound out of range");
1381 assert(LocInfo.LastKill < VersionStack.size() &&
1382 "Last kill info out of range");
1383 // In any case, the new upper bound is the top of the stack.
1384 unsigned long UpperBound = VersionStack.size() - 1;
1385
1386 if (UpperBound - LocInfo.LowerBound > MaxCheckLimit) {
Daniel Berlin26fcea92016-08-02 20:02:21 +00001387 DEBUG(dbgs() << "MemorySSA skipping optimization of " << *MU << " ("
1388 << *(MU->getMemoryInst()) << ")"
1389 << " because there are " << UpperBound - LocInfo.LowerBound
1390 << " stores to disambiguate\n");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001391 // Because we did not walk, LastKill is no longer valid, as this may
1392 // have been a kill.
1393 LocInfo.LastKillValid = false;
1394 continue;
1395 }
1396 bool FoundClobberResult = false;
1397 while (UpperBound > LocInfo.LowerBound) {
1398 if (isa<MemoryPhi>(VersionStack[UpperBound])) {
1399 // For phis, use the walker, see where we ended up, go there
1400 Instruction *UseInst = MU->getMemoryInst();
1401 MemoryAccess *Result = Walker->getClobberingMemoryAccess(UseInst);
1402 // We are guaranteed to find it or something is wrong
1403 while (VersionStack[UpperBound] != Result) {
1404 assert(UpperBound != 0);
1405 --UpperBound;
1406 }
1407 FoundClobberResult = true;
1408 break;
1409 }
1410
1411 MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]);
Daniel Berlindf101192016-08-03 00:01:46 +00001412 // If the lifetime of the pointer ends at this instruction, it's live on
1413 // entry.
1414 if (!UseMLOC.IsCall && lifetimeEndsAt(MD, UseMLOC.getLoc(), *AA)) {
1415 // Reset UpperBound to liveOnEntryDef's place in the stack
1416 UpperBound = 0;
1417 FoundClobberResult = true;
1418 break;
1419 }
Daniel Berlindff31de2016-08-02 21:57:52 +00001420 if (instructionClobbersQuery(MD, MU, UseMLOC, *AA)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001421 FoundClobberResult = true;
1422 break;
1423 }
1424 --UpperBound;
1425 }
1426 // At the end of this loop, UpperBound is either a clobber, or lower bound
1427 // PHI walking may cause it to be < LowerBound, and in fact, < LastKill.
1428 if (FoundClobberResult || UpperBound < LocInfo.LastKill) {
1429 MU->setDefiningAccess(VersionStack[UpperBound]);
1430 // We were last killed now by where we got to
1431 LocInfo.LastKill = UpperBound;
1432 } else {
1433 // Otherwise, we checked all the new ones, and now we know we can get to
1434 // LastKill.
1435 MU->setDefiningAccess(VersionStack[LocInfo.LastKill]);
1436 }
1437 LocInfo.LowerBound = VersionStack.size() - 1;
1438 }
1439}
1440
1441/// Optimize uses to point to their actual clobbering definitions.
1442void MemorySSA::OptimizeUses::optimizeUses() {
1443
1444 // We perform a non-recursive top-down dominator tree walk
1445 struct StackInfo {
1446 const DomTreeNode *Node;
1447 DomTreeNode::const_iterator Iter;
1448 };
1449
1450 SmallVector<MemoryAccess *, 16> VersionStack;
1451 SmallVector<StackInfo, 16> DomTreeWorklist;
1452 DenseMap<MemoryLocOrCall, MemlocStackInfo> LocStackInfo;
1453 DomTreeWorklist.push_back({DT->getRootNode(), DT->getRootNode()->begin()});
1454 // Bottom of the version stack is always live on entry.
1455 VersionStack.push_back(MSSA->getLiveOnEntryDef());
1456
1457 unsigned long StackEpoch = 1;
1458 unsigned long PopEpoch = 1;
1459 while (!DomTreeWorklist.empty()) {
1460 const auto *DomNode = DomTreeWorklist.back().Node;
1461 const auto DomIter = DomTreeWorklist.back().Iter;
1462 BasicBlock *BB = DomNode->getBlock();
1463 optimizeUsesInBlock(BB, StackEpoch, PopEpoch, VersionStack, LocStackInfo);
1464 if (DomIter == DomNode->end()) {
1465 // Hit the end, pop the worklist
1466 DomTreeWorklist.pop_back();
1467 continue;
1468 }
1469 // Move the iterator to the next child for the next time we get to process
1470 // children
1471 ++DomTreeWorklist.back().Iter;
1472
1473 // Now visit the next child
1474 DomTreeWorklist.push_back({*DomIter, (*DomIter)->begin()});
1475 }
1476}
1477
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001478void MemorySSA::buildMemorySSA() {
George Burgess IVe1100f52016-02-02 22:46:49 +00001479 // We create an access to represent "live on entry", for things like
1480 // arguments or users of globals, where the memory they use is defined before
1481 // the beginning of the function. We do not actually insert it into the IR.
1482 // We do not define a live on exit for the immediate uses, and thus our
1483 // semantics do *not* imply that something with no immediate uses can simply
1484 // be removed.
1485 BasicBlock &StartingPoint = F.getEntryBlock();
1486 LiveOnEntryDef = make_unique<MemoryDef>(F.getContext(), nullptr, nullptr,
1487 &StartingPoint, NextID++);
1488
1489 // We maintain lists of memory accesses per-block, trading memory for time. We
1490 // could just look up the memory access for every possible instruction in the
1491 // stream.
1492 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001493 SmallPtrSet<BasicBlock *, 32> DefUseBlocks;
George Burgess IVe1100f52016-02-02 22:46:49 +00001494 // Go through each block, figure out where defs occur, and chain together all
1495 // the accesses.
1496 for (BasicBlock &B : F) {
Daniel Berlin7898ca62016-02-07 01:52:15 +00001497 bool InsertIntoDef = false;
Daniel Berlinada263d2016-06-20 20:21:33 +00001498 AccessList *Accesses = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +00001499 for (Instruction &I : B) {
Peter Collingbourneffecb142016-05-26 01:19:17 +00001500 MemoryUseOrDef *MUD = createNewAccess(&I);
George Burgess IVb42b7622016-03-11 19:34:03 +00001501 if (!MUD)
George Burgess IVe1100f52016-02-02 22:46:49 +00001502 continue;
George Burgess IV3887a412016-03-21 21:25:39 +00001503 InsertIntoDef |= isa<MemoryDef>(MUD);
Daniel Berlin1b51a292016-02-07 01:52:19 +00001504
George Burgess IVe1100f52016-02-02 22:46:49 +00001505 if (!Accesses)
1506 Accesses = getOrCreateAccessList(&B);
George Burgess IVb42b7622016-03-11 19:34:03 +00001507 Accesses->push_back(MUD);
George Burgess IVe1100f52016-02-02 22:46:49 +00001508 }
Daniel Berlin7898ca62016-02-07 01:52:15 +00001509 if (InsertIntoDef)
1510 DefiningBlocks.insert(&B);
George Burgess IV3887a412016-03-21 21:25:39 +00001511 if (Accesses)
Daniel Berlin1b51a292016-02-07 01:52:19 +00001512 DefUseBlocks.insert(&B);
1513 }
1514
1515 // Compute live-in.
1516 // Live in is normally defined as "all the blocks on the path from each def to
1517 // each of it's uses".
1518 // MemoryDef's are implicit uses of previous state, so they are also uses.
1519 // This means we don't really have def-only instructions. The only
1520 // MemoryDef's that are not really uses are those that are of the LiveOnEntry
1521 // variable (because LiveOnEntry can reach anywhere, and every def is a
1522 // must-kill of LiveOnEntry).
1523 // In theory, you could precisely compute live-in by using alias-analysis to
1524 // disambiguate defs and uses to see which really pair up with which.
1525 // In practice, this would be really expensive and difficult. So we simply
1526 // assume all defs are also uses that need to be kept live.
1527 // Because of this, the end result of this live-in computation will be "the
1528 // entire set of basic blocks that reach any use".
1529
1530 SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
1531 SmallVector<BasicBlock *, 64> LiveInBlockWorklist(DefUseBlocks.begin(),
1532 DefUseBlocks.end());
1533 // Now that we have a set of blocks where a value is live-in, recursively add
1534 // predecessors until we find the full region the value is live.
1535 while (!LiveInBlockWorklist.empty()) {
1536 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
1537
1538 // The block really is live in here, insert it into the set. If already in
1539 // the set, then it has already been processed.
1540 if (!LiveInBlocks.insert(BB).second)
1541 continue;
1542
1543 // Since the value is live into BB, it is either defined in a predecessor or
1544 // live into it to.
1545 LiveInBlockWorklist.append(pred_begin(BB), pred_end(BB));
George Burgess IVe1100f52016-02-02 22:46:49 +00001546 }
1547
1548 // Determine where our MemoryPhi's should go
Daniel Berlin77fa84e2016-04-19 06:13:28 +00001549 ForwardIDFCalculator IDFs(*DT);
George Burgess IVe1100f52016-02-02 22:46:49 +00001550 IDFs.setDefiningBlocks(DefiningBlocks);
Daniel Berlin1b51a292016-02-07 01:52:19 +00001551 IDFs.setLiveInBlocks(LiveInBlocks);
George Burgess IVe1100f52016-02-02 22:46:49 +00001552 SmallVector<BasicBlock *, 32> IDFBlocks;
1553 IDFs.calculate(IDFBlocks);
1554
1555 // Now place MemoryPhi nodes.
1556 for (auto &BB : IDFBlocks) {
1557 // Insert phi node
Daniel Berlinada263d2016-06-20 20:21:33 +00001558 AccessList *Accesses = getOrCreateAccessList(BB);
Daniel Berlin14300262016-06-21 18:39:20 +00001559 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlin5130cc82016-07-31 21:08:20 +00001560 ValueToMemoryAccess[BB] = Phi;
George Burgess IVe1100f52016-02-02 22:46:49 +00001561 // Phi's always are placed at the front of the block.
1562 Accesses->push_front(Phi);
1563 }
1564
1565 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
1566 // filled in with all blocks.
1567 SmallPtrSet<BasicBlock *, 16> Visited;
1568 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1569
George Burgess IV5f308972016-07-19 01:29:15 +00001570 CachingWalker *Walker = getWalkerImpl();
1571
1572 // We're doing a batch of updates; don't drop useful caches between them.
1573 Walker->setAutoResetWalker(false);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001574 OptimizeUses(this, Walker, AA, DT).optimizeUses();
George Burgess IV5f308972016-07-19 01:29:15 +00001575 Walker->setAutoResetWalker(true);
1576 Walker->resetClobberWalker();
1577
George Burgess IVe1100f52016-02-02 22:46:49 +00001578 // Mark the uses in unreachable blocks as live on entry, so that they go
1579 // somewhere.
1580 for (auto &BB : F)
1581 if (!Visited.count(&BB))
1582 markUnreachableAsLiveOnEntry(&BB);
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001583}
George Burgess IVe1100f52016-02-02 22:46:49 +00001584
George Burgess IV5f308972016-07-19 01:29:15 +00001585MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
1586
1587MemorySSA::CachingWalker *MemorySSA::getWalkerImpl() {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001588 if (Walker)
1589 return Walker.get();
1590
1591 Walker = make_unique<CachingWalker>(this, AA, DT);
Geoff Berryb96d3b22016-06-01 21:30:40 +00001592 return Walker.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001593}
1594
Daniel Berlin14300262016-06-21 18:39:20 +00001595MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
1596 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
1597 AccessList *Accesses = getOrCreateAccessList(BB);
1598 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlin5130cc82016-07-31 21:08:20 +00001599 ValueToMemoryAccess[BB] = Phi;
Daniel Berlin14300262016-06-21 18:39:20 +00001600 // Phi's always are placed at the front of the block.
1601 Accesses->push_front(Phi);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001602 BlockNumberingValid.erase(BB);
Daniel Berlin14300262016-06-21 18:39:20 +00001603 return Phi;
1604}
1605
1606MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
1607 MemoryAccess *Definition) {
1608 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
1609 MemoryUseOrDef *NewAccess = createNewAccess(I);
1610 assert(
1611 NewAccess != nullptr &&
1612 "Tried to create a memory access for a non-memory touching instruction");
1613 NewAccess->setDefiningAccess(Definition);
1614 return NewAccess;
1615}
1616
1617MemoryAccess *MemorySSA::createMemoryAccessInBB(Instruction *I,
1618 MemoryAccess *Definition,
1619 const BasicBlock *BB,
1620 InsertionPlace Point) {
1621 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1622 auto *Accesses = getOrCreateAccessList(BB);
1623 if (Point == Beginning) {
1624 // It goes after any phi nodes
1625 auto AI = std::find_if(
1626 Accesses->begin(), Accesses->end(),
1627 [](const MemoryAccess &MA) { return !isa<MemoryPhi>(MA); });
1628
1629 Accesses->insert(AI, NewAccess);
1630 } else {
1631 Accesses->push_back(NewAccess);
1632 }
Daniel Berlin5c46b942016-07-19 22:49:43 +00001633 BlockNumberingValid.erase(BB);
Daniel Berlin14300262016-06-21 18:39:20 +00001634 return NewAccess;
1635}
1636MemoryAccess *MemorySSA::createMemoryAccessBefore(Instruction *I,
1637 MemoryAccess *Definition,
1638 MemoryAccess *InsertPt) {
1639 assert(I->getParent() == InsertPt->getBlock() &&
1640 "New and old access must be in the same block");
1641 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1642 auto *Accesses = getOrCreateAccessList(InsertPt->getBlock());
1643 Accesses->insert(AccessList::iterator(InsertPt), NewAccess);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001644 BlockNumberingValid.erase(InsertPt->getBlock());
Daniel Berlin14300262016-06-21 18:39:20 +00001645 return NewAccess;
1646}
1647
1648MemoryAccess *MemorySSA::createMemoryAccessAfter(Instruction *I,
1649 MemoryAccess *Definition,
1650 MemoryAccess *InsertPt) {
1651 assert(I->getParent() == InsertPt->getBlock() &&
1652 "New and old access must be in the same block");
1653 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1654 auto *Accesses = getOrCreateAccessList(InsertPt->getBlock());
1655 Accesses->insertAfter(AccessList::iterator(InsertPt), NewAccess);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001656 BlockNumberingValid.erase(InsertPt->getBlock());
Daniel Berlin14300262016-06-21 18:39:20 +00001657 return NewAccess;
1658}
1659
George Burgess IVe1100f52016-02-02 22:46:49 +00001660/// \brief Helper function to create new memory accesses
Peter Collingbourneffecb142016-05-26 01:19:17 +00001661MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I) {
Peter Collingbourneb9aa1f42016-05-26 04:58:46 +00001662 // The assume intrinsic has a control dependency which we model by claiming
1663 // that it writes arbitrarily. Ignore that fake memory dependency here.
1664 // FIXME: Replace this special casing with a more accurate modelling of
1665 // assume's control dependency.
1666 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1667 if (II->getIntrinsicID() == Intrinsic::assume)
1668 return nullptr;
1669
George Burgess IVe1100f52016-02-02 22:46:49 +00001670 // Find out what affect this instruction has on memory.
1671 ModRefInfo ModRef = AA->getModRefInfo(I);
1672 bool Def = bool(ModRef & MRI_Mod);
1673 bool Use = bool(ModRef & MRI_Ref);
1674
1675 // It's possible for an instruction to not modify memory at all. During
1676 // construction, we ignore them.
Peter Collingbourneffecb142016-05-26 01:19:17 +00001677 if (!Def && !Use)
George Burgess IVe1100f52016-02-02 22:46:49 +00001678 return nullptr;
1679
1680 assert((Def || Use) &&
1681 "Trying to create a memory access with a non-memory instruction");
1682
George Burgess IVb42b7622016-03-11 19:34:03 +00001683 MemoryUseOrDef *MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001684 if (Def)
George Burgess IVb42b7622016-03-11 19:34:03 +00001685 MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
George Burgess IVe1100f52016-02-02 22:46:49 +00001686 else
George Burgess IVb42b7622016-03-11 19:34:03 +00001687 MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
Daniel Berlin5130cc82016-07-31 21:08:20 +00001688 ValueToMemoryAccess[I] = MUD;
George Burgess IVb42b7622016-03-11 19:34:03 +00001689 return MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001690}
1691
1692MemoryAccess *MemorySSA::findDominatingDef(BasicBlock *UseBlock,
1693 enum InsertionPlace Where) {
1694 // Handle the initial case
1695 if (Where == Beginning)
1696 // The only thing that could define us at the beginning is a phi node
1697 if (MemoryPhi *Phi = getMemoryAccess(UseBlock))
1698 return Phi;
1699
1700 DomTreeNode *CurrNode = DT->getNode(UseBlock);
1701 // Need to be defined by our dominator
1702 if (Where == Beginning)
1703 CurrNode = CurrNode->getIDom();
1704 Where = End;
1705 while (CurrNode) {
1706 auto It = PerBlockAccesses.find(CurrNode->getBlock());
1707 if (It != PerBlockAccesses.end()) {
1708 auto &Accesses = It->second;
David Majnemerd7708772016-06-24 04:05:21 +00001709 for (MemoryAccess &RA : reverse(*Accesses)) {
1710 if (isa<MemoryDef>(RA) || isa<MemoryPhi>(RA))
1711 return &RA;
George Burgess IVe1100f52016-02-02 22:46:49 +00001712 }
1713 }
1714 CurrNode = CurrNode->getIDom();
1715 }
1716 return LiveOnEntryDef.get();
1717}
1718
1719/// \brief Returns true if \p Replacer dominates \p Replacee .
1720bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
1721 const MemoryAccess *Replacee) const {
1722 if (isa<MemoryUseOrDef>(Replacee))
1723 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
1724 const auto *MP = cast<MemoryPhi>(Replacee);
1725 // For a phi node, the use occurs in the predecessor block of the phi node.
1726 // Since we may occur multiple times in the phi node, we have to check each
1727 // operand to ensure Replacer dominates each operand where Replacee occurs.
1728 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +00001729 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +00001730 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
1731 return false;
1732 }
1733 return true;
1734}
1735
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001736/// \brief If all arguments of a MemoryPHI are defined by the same incoming
1737/// argument, return that argument.
1738static MemoryAccess *onlySingleValue(MemoryPhi *MP) {
1739 MemoryAccess *MA = nullptr;
1740
1741 for (auto &Arg : MP->operands()) {
1742 if (!MA)
1743 MA = cast<MemoryAccess>(Arg);
1744 else if (MA != Arg)
1745 return nullptr;
1746 }
1747 return MA;
1748}
1749
1750/// \brief Properly remove \p MA from all of MemorySSA's lookup tables.
1751///
1752/// Because of the way the intrusive list and use lists work, it is important to
1753/// do removal in the right order.
1754void MemorySSA::removeFromLookups(MemoryAccess *MA) {
1755 assert(MA->use_empty() &&
1756 "Trying to remove memory access that still has uses");
Daniel Berlin5c46b942016-07-19 22:49:43 +00001757 BlockNumbering.erase(MA);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001758 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA))
1759 MUD->setDefiningAccess(nullptr);
1760 // Invalidate our walker's cache if necessary
1761 if (!isa<MemoryUse>(MA))
1762 Walker->invalidateInfo(MA);
1763 // The call below to erase will destroy MA, so we can't change the order we
1764 // are doing things here
1765 Value *MemoryInst;
1766 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
1767 MemoryInst = MUD->getMemoryInst();
1768 } else {
1769 MemoryInst = MA->getBlock();
1770 }
Daniel Berlin5130cc82016-07-31 21:08:20 +00001771 auto VMA = ValueToMemoryAccess.find(MemoryInst);
1772 if (VMA->second == MA)
1773 ValueToMemoryAccess.erase(VMA);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001774
George Burgess IVe0e6e482016-03-02 02:35:04 +00001775 auto AccessIt = PerBlockAccesses.find(MA->getBlock());
Daniel Berlinada263d2016-06-20 20:21:33 +00001776 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001777 Accesses->erase(MA);
George Burgess IVe0e6e482016-03-02 02:35:04 +00001778 if (Accesses->empty())
1779 PerBlockAccesses.erase(AccessIt);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001780}
1781
1782void MemorySSA::removeMemoryAccess(MemoryAccess *MA) {
1783 assert(!isLiveOnEntryDef(MA) && "Trying to remove the live on entry def");
1784 // We can only delete phi nodes if they have no uses, or we can replace all
1785 // uses with a single definition.
1786 MemoryAccess *NewDefTarget = nullptr;
1787 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(MA)) {
1788 // Note that it is sufficient to know that all edges of the phi node have
1789 // the same argument. If they do, by the definition of dominance frontiers
1790 // (which we used to place this phi), that argument must dominate this phi,
1791 // and thus, must dominate the phi's uses, and so we will not hit the assert
1792 // below.
1793 NewDefTarget = onlySingleValue(MP);
1794 assert((NewDefTarget || MP->use_empty()) &&
1795 "We can't delete this memory phi");
1796 } else {
1797 NewDefTarget = cast<MemoryUseOrDef>(MA)->getDefiningAccess();
1798 }
1799
1800 // Re-point the uses at our defining access
1801 if (!MA->use_empty())
1802 MA->replaceAllUsesWith(NewDefTarget);
1803
1804 // The call below to erase will destroy MA, so we can't change the order we
1805 // are doing things here
1806 removeFromLookups(MA);
1807}
1808
George Burgess IVe1100f52016-02-02 22:46:49 +00001809void MemorySSA::print(raw_ostream &OS) const {
1810 MemorySSAAnnotatedWriter Writer(this);
1811 F.print(OS, &Writer);
1812}
1813
1814void MemorySSA::dump() const {
1815 MemorySSAAnnotatedWriter Writer(this);
1816 F.print(dbgs(), &Writer);
1817}
1818
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001819void MemorySSA::verifyMemorySSA() const {
1820 verifyDefUses(F);
1821 verifyDomination(F);
Daniel Berlin14300262016-06-21 18:39:20 +00001822 verifyOrdering(F);
1823}
1824
1825/// \brief Verify that the order and existence of MemoryAccesses matches the
1826/// order and existence of memory affecting instructions.
1827void MemorySSA::verifyOrdering(Function &F) const {
1828 // Walk all the blocks, comparing what the lookups think and what the access
1829 // lists think, as well as the order in the blocks vs the order in the access
1830 // lists.
1831 SmallVector<MemoryAccess *, 32> ActualAccesses;
1832 for (BasicBlock &B : F) {
1833 const AccessList *AL = getBlockAccesses(&B);
1834 MemoryAccess *Phi = getMemoryAccess(&B);
1835 if (Phi)
1836 ActualAccesses.push_back(Phi);
1837 for (Instruction &I : B) {
1838 MemoryAccess *MA = getMemoryAccess(&I);
1839 assert((!MA || AL) && "We have memory affecting instructions "
1840 "in this block but they are not in the "
1841 "access list");
1842 if (MA)
1843 ActualAccesses.push_back(MA);
1844 }
1845 // Either we hit the assert, really have no accesses, or we have both
1846 // accesses and an access list
1847 if (!AL)
1848 continue;
1849 assert(AL->size() == ActualAccesses.size() &&
1850 "We don't have the same number of accesses in the block as on the "
1851 "access list");
1852 auto ALI = AL->begin();
1853 auto AAI = ActualAccesses.begin();
1854 while (ALI != AL->end() && AAI != ActualAccesses.end()) {
1855 assert(&*ALI == *AAI && "Not the same accesses in the same order");
1856 ++ALI;
1857 ++AAI;
1858 }
1859 ActualAccesses.clear();
1860 }
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001861}
1862
George Burgess IVe1100f52016-02-02 22:46:49 +00001863/// \brief Verify the domination properties of MemorySSA by checking that each
1864/// definition dominates all of its uses.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001865void MemorySSA::verifyDomination(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001866 for (BasicBlock &B : F) {
1867 // Phi nodes are attached to basic blocks
1868 if (MemoryPhi *MP = getMemoryAccess(&B)) {
1869 for (User *U : MP->users()) {
1870 BasicBlock *UseBlock;
1871 // Phi operands are used on edges, we simulate the right domination by
1872 // acting as if the use occurred at the end of the predecessor block.
1873 if (MemoryPhi *P = dyn_cast<MemoryPhi>(U)) {
1874 for (const auto &Arg : P->operands()) {
1875 if (Arg == MP) {
1876 UseBlock = P->getIncomingBlock(Arg);
1877 break;
1878 }
1879 }
1880 } else {
1881 UseBlock = cast<MemoryAccess>(U)->getBlock();
1882 }
George Burgess IV60adac42016-02-02 23:26:01 +00001883 (void)UseBlock;
George Burgess IVe1100f52016-02-02 22:46:49 +00001884 assert(DT->dominates(MP->getBlock(), UseBlock) &&
1885 "Memory PHI does not dominate it's uses");
1886 }
1887 }
1888
1889 for (Instruction &I : B) {
1890 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
1891 if (!MD)
1892 continue;
1893
Benjamin Kramer451f54c2016-02-22 13:11:58 +00001894 for (User *U : MD->users()) {
Daniel Berlinada263d2016-06-20 20:21:33 +00001895 BasicBlock *UseBlock;
1896 (void)UseBlock;
George Burgess IVe1100f52016-02-02 22:46:49 +00001897 // Things are allowed to flow to phi nodes over their predecessor edge.
1898 if (auto *P = dyn_cast<MemoryPhi>(U)) {
1899 for (const auto &Arg : P->operands()) {
1900 if (Arg == MD) {
1901 UseBlock = P->getIncomingBlock(Arg);
1902 break;
1903 }
1904 }
1905 } else {
1906 UseBlock = cast<MemoryAccess>(U)->getBlock();
1907 }
1908 assert(DT->dominates(MD->getBlock(), UseBlock) &&
1909 "Memory Def does not dominate it's uses");
1910 }
1911 }
1912 }
1913}
1914
1915/// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use
1916/// appears in the use list of \p Def.
1917///
1918/// llvm_unreachable is used instead of asserts because this may be called in
1919/// a build without asserts. In that case, we don't want this to turn into a
1920/// nop.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001921void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001922 // The live on entry use may cause us to get a NULL def here
1923 if (!Def) {
1924 if (!isLiveOnEntryDef(Use))
1925 llvm_unreachable("Null def but use not point to live on entry def");
1926 } else if (std::find(Def->user_begin(), Def->user_end(), Use) ==
1927 Def->user_end()) {
1928 llvm_unreachable("Did not find use in def's use list");
1929 }
1930}
1931
1932/// \brief Verify the immediate use information, by walking all the memory
1933/// accesses and verifying that, for each use, it appears in the
1934/// appropriate def's use list
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001935void MemorySSA::verifyDefUses(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001936 for (BasicBlock &B : F) {
1937 // Phi nodes are attached to basic blocks
Daniel Berlin14300262016-06-21 18:39:20 +00001938 if (MemoryPhi *Phi = getMemoryAccess(&B)) {
David Majnemer580e7542016-06-25 00:04:06 +00001939 assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
1940 pred_begin(&B), pred_end(&B))) &&
Daniel Berlin14300262016-06-21 18:39:20 +00001941 "Incomplete MemoryPhi Node");
George Burgess IVe1100f52016-02-02 22:46:49 +00001942 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
1943 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
Daniel Berlin14300262016-06-21 18:39:20 +00001944 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001945
1946 for (Instruction &I : B) {
1947 if (MemoryAccess *MA = getMemoryAccess(&I)) {
1948 assert(isa<MemoryUseOrDef>(MA) &&
1949 "Found a phi node not attached to a bb");
1950 verifyUseInDefs(cast<MemoryUseOrDef>(MA)->getDefiningAccess(), MA);
1951 }
1952 }
1953 }
1954}
1955
1956MemoryAccess *MemorySSA::getMemoryAccess(const Value *I) const {
Daniel Berlinf6c9ae92016-02-10 17:41:25 +00001957 return ValueToMemoryAccess.lookup(I);
George Burgess IVe1100f52016-02-02 22:46:49 +00001958}
1959
1960MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const {
1961 return cast_or_null<MemoryPhi>(getMemoryAccess((const Value *)BB));
1962}
1963
Daniel Berlin5c46b942016-07-19 22:49:43 +00001964/// Perform a local numbering on blocks so that instruction ordering can be
1965/// determined in constant time.
1966/// TODO: We currently just number in order. If we numbered by N, we could
1967/// allow at least N-1 sequences of insertBefore or insertAfter (and at least
1968/// log2(N) sequences of mixed before and after) without needing to invalidate
1969/// the numbering.
1970void MemorySSA::renumberBlock(const BasicBlock *B) const {
1971 // The pre-increment ensures the numbers really start at 1.
1972 unsigned long CurrentNumber = 0;
1973 const AccessList *AL = getBlockAccesses(B);
1974 assert(AL != nullptr && "Asking to renumber an empty block");
1975 for (const auto &I : *AL)
1976 BlockNumbering[&I] = ++CurrentNumber;
1977 BlockNumberingValid.insert(B);
1978}
1979
George Burgess IVe1100f52016-02-02 22:46:49 +00001980/// \brief Determine, for two memory accesses in the same block,
1981/// whether \p Dominator dominates \p Dominatee.
1982/// \returns True if \p Dominator dominates \p Dominatee.
1983bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
1984 const MemoryAccess *Dominatee) const {
Sebastian Pope1f60b12016-06-10 21:36:41 +00001985
Daniel Berlin5c46b942016-07-19 22:49:43 +00001986 const BasicBlock *DominatorBlock = Dominator->getBlock();
Daniel Berlin5c46b942016-07-19 22:49:43 +00001987
Daniel Berlin19860302016-07-19 23:08:08 +00001988 assert((DominatorBlock == Dominatee->getBlock()) &&
Daniel Berlin5c46b942016-07-19 22:49:43 +00001989 "Asking for local domination when accesses are in different blocks!");
Sebastian Pope1f60b12016-06-10 21:36:41 +00001990 // A node dominates itself.
1991 if (Dominatee == Dominator)
1992 return true;
1993
1994 // When Dominatee is defined on function entry, it is not dominated by another
1995 // memory access.
1996 if (isLiveOnEntryDef(Dominatee))
1997 return false;
1998
1999 // When Dominator is defined on function entry, it dominates the other memory
2000 // access.
2001 if (isLiveOnEntryDef(Dominator))
2002 return true;
2003
Daniel Berlin5c46b942016-07-19 22:49:43 +00002004 if (!BlockNumberingValid.count(DominatorBlock))
2005 renumberBlock(DominatorBlock);
George Burgess IVe1100f52016-02-02 22:46:49 +00002006
Daniel Berlin5c46b942016-07-19 22:49:43 +00002007 unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
2008 // All numbers start with 1
2009 assert(DominatorNum != 0 && "Block was not numbered properly");
2010 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
2011 assert(DominateeNum != 0 && "Block was not numbered properly");
2012 return DominatorNum < DominateeNum;
George Burgess IVe1100f52016-02-02 22:46:49 +00002013}
2014
George Burgess IV5f308972016-07-19 01:29:15 +00002015bool MemorySSA::dominates(const MemoryAccess *Dominator,
2016 const MemoryAccess *Dominatee) const {
2017 if (Dominator == Dominatee)
2018 return true;
2019
2020 if (isLiveOnEntryDef(Dominatee))
2021 return false;
2022
2023 if (Dominator->getBlock() != Dominatee->getBlock())
2024 return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
2025 return locallyDominates(Dominator, Dominatee);
2026}
2027
George Burgess IVe1100f52016-02-02 22:46:49 +00002028const static char LiveOnEntryStr[] = "liveOnEntry";
2029
2030void MemoryDef::print(raw_ostream &OS) const {
2031 MemoryAccess *UO = getDefiningAccess();
2032
2033 OS << getID() << " = MemoryDef(";
2034 if (UO && UO->getID())
2035 OS << UO->getID();
2036 else
2037 OS << LiveOnEntryStr;
2038 OS << ')';
2039}
2040
2041void MemoryPhi::print(raw_ostream &OS) const {
2042 bool First = true;
2043 OS << getID() << " = MemoryPhi(";
2044 for (const auto &Op : operands()) {
2045 BasicBlock *BB = getIncomingBlock(Op);
2046 MemoryAccess *MA = cast<MemoryAccess>(Op);
2047 if (!First)
2048 OS << ',';
2049 else
2050 First = false;
2051
2052 OS << '{';
2053 if (BB->hasName())
2054 OS << BB->getName();
2055 else
2056 BB->printAsOperand(OS, false);
2057 OS << ',';
2058 if (unsigned ID = MA->getID())
2059 OS << ID;
2060 else
2061 OS << LiveOnEntryStr;
2062 OS << '}';
2063 }
2064 OS << ')';
2065}
2066
2067MemoryAccess::~MemoryAccess() {}
2068
2069void MemoryUse::print(raw_ostream &OS) const {
2070 MemoryAccess *UO = getDefiningAccess();
2071 OS << "MemoryUse(";
2072 if (UO && UO->getID())
2073 OS << UO->getID();
2074 else
2075 OS << LiveOnEntryStr;
2076 OS << ')';
2077}
2078
2079void MemoryAccess::dump() const {
2080 print(dbgs());
2081 dbgs() << "\n";
2082}
2083
Chad Rosier232e29e2016-07-06 21:20:47 +00002084char MemorySSAPrinterLegacyPass::ID = 0;
2085
2086MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) {
2087 initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
2088}
2089
2090void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
2091 AU.setPreservesAll();
2092 AU.addRequired<MemorySSAWrapperPass>();
2093 AU.addPreserved<MemorySSAWrapperPass>();
2094}
2095
2096bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) {
2097 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
2098 MSSA.print(dbgs());
2099 if (VerifyMemorySSA)
2100 MSSA.verifyMemorySSA();
2101 return false;
2102}
2103
Geoff Berryb96d3b22016-06-01 21:30:40 +00002104char MemorySSAAnalysis::PassID;
George Burgess IVe1100f52016-02-02 22:46:49 +00002105
Geoff Berryb96d3b22016-06-01 21:30:40 +00002106MemorySSA MemorySSAAnalysis::run(Function &F, AnalysisManager<Function> &AM) {
2107 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2108 auto &AA = AM.getResult<AAManager>(F);
2109 return MemorySSA(F, &AA, &DT);
George Burgess IVe1100f52016-02-02 22:46:49 +00002110}
2111
Geoff Berryb96d3b22016-06-01 21:30:40 +00002112PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
2113 FunctionAnalysisManager &AM) {
2114 OS << "MemorySSA for function: " << F.getName() << "\n";
2115 AM.getResult<MemorySSAAnalysis>(F).print(OS);
2116
2117 return PreservedAnalyses::all();
George Burgess IVe1100f52016-02-02 22:46:49 +00002118}
2119
Geoff Berryb96d3b22016-06-01 21:30:40 +00002120PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
2121 FunctionAnalysisManager &AM) {
2122 AM.getResult<MemorySSAAnalysis>(F).verifyMemorySSA();
2123
2124 return PreservedAnalyses::all();
2125}
2126
2127char MemorySSAWrapperPass::ID = 0;
2128
2129MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
2130 initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
2131}
2132
2133void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
2134
2135void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00002136 AU.setPreservesAll();
Geoff Berryb96d3b22016-06-01 21:30:40 +00002137 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
2138 AU.addRequiredTransitive<AAResultsWrapperPass>();
George Burgess IVe1100f52016-02-02 22:46:49 +00002139}
2140
Geoff Berryb96d3b22016-06-01 21:30:40 +00002141bool MemorySSAWrapperPass::runOnFunction(Function &F) {
2142 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2143 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2144 MSSA.reset(new MemorySSA(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00002145 return false;
2146}
2147
Geoff Berryb96d3b22016-06-01 21:30:40 +00002148void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); }
George Burgess IVe1100f52016-02-02 22:46:49 +00002149
Geoff Berryb96d3b22016-06-01 21:30:40 +00002150void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00002151 MSSA->print(OS);
2152}
2153
George Burgess IVe1100f52016-02-02 22:46:49 +00002154MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
2155
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002156MemorySSA::CachingWalker::CachingWalker(MemorySSA *M, AliasAnalysis *A,
2157 DominatorTree *D)
Daniel Berlin5c46b942016-07-19 22:49:43 +00002158 : MemorySSAWalker(M), Walker(*M, *A, *D, Cache), AutoResetWalker(true) {}
George Burgess IVe1100f52016-02-02 22:46:49 +00002159
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002160MemorySSA::CachingWalker::~CachingWalker() {}
George Burgess IVe1100f52016-02-02 22:46:49 +00002161
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002162void MemorySSA::CachingWalker::invalidateInfo(MemoryAccess *MA) {
Daniel Berlin83fc77b2016-03-01 18:46:54 +00002163 // TODO: We can do much better cache invalidation with differently stored
2164 // caches. For now, for MemoryUses, we simply remove them
2165 // from the cache, and kill the entire call/non-call cache for everything
2166 // else. The problem is for phis or defs, currently we'd need to follow use
2167 // chains down and invalidate anything below us in the chain that currently
2168 // terminates at this access.
2169
2170 // See if this is a MemoryUse, if so, just remove the cached info. MemoryUse
2171 // is by definition never a barrier, so nothing in the cache could point to
2172 // this use. In that case, we only need invalidate the info for the use
2173 // itself.
2174
2175 if (MemoryUse *MU = dyn_cast<MemoryUse>(MA)) {
George Burgess IV5f308972016-07-19 01:29:15 +00002176 UpwardsMemoryQuery Q(MU->getMemoryInst(), MU);
2177 Cache.remove(MU, Q.StartingLoc, Q.IsCall);
Geoff Berry9fe26e62016-04-22 14:44:10 +00002178 } else {
2179 // 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 +00002180 Cache.clear();
Geoff Berry9fe26e62016-04-22 14:44:10 +00002181 }
2182
Filipe Cabecinhas0da99372016-04-29 15:22:48 +00002183#ifdef EXPENSIVE_CHECKS
Geoff Berry9fe26e62016-04-22 14:44:10 +00002184 verifyRemoved(MA);
2185#endif
Daniel Berlin83fc77b2016-03-01 18:46:54 +00002186}
2187
George Burgess IVe1100f52016-02-02 22:46:49 +00002188/// \brief Walk the use-def chains starting at \p MA and find
2189/// the MemoryAccess that actually clobbers Loc.
2190///
2191/// \returns our clobbering memory access
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002192MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
2193 MemoryAccess *StartingAccess, UpwardsMemoryQuery &Q) {
George Burgess IV5f308972016-07-19 01:29:15 +00002194 MemoryAccess *New = Walker.findClobber(StartingAccess, Q);
2195#ifdef EXPENSIVE_CHECKS
2196 MemoryAccess *NewNoCache =
2197 Walker.findClobber(StartingAccess, Q, /*UseWalkerCache=*/false);
2198 assert(NewNoCache == New && "Cache made us hand back a different result?");
2199#endif
2200 if (AutoResetWalker)
2201 resetClobberWalker();
2202 return New;
George Burgess IVe1100f52016-02-02 22:46:49 +00002203}
2204
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002205MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
2206 MemoryAccess *StartingAccess, MemoryLocation &Loc) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002207 if (isa<MemoryPhi>(StartingAccess))
2208 return StartingAccess;
2209
2210 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
2211 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
2212 return StartingUseOrDef;
2213
2214 Instruction *I = StartingUseOrDef->getMemoryInst();
2215
2216 // Conservatively, fences are always clobbers, so don't perform the walk if we
2217 // hit a fence.
David Majnemera940f362016-07-15 17:19:24 +00002218 if (!ImmutableCallSite(I) && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002219 return StartingUseOrDef;
2220
2221 UpwardsMemoryQuery Q;
2222 Q.OriginalAccess = StartingUseOrDef;
2223 Q.StartingLoc = Loc;
George Burgess IV5f308972016-07-19 01:29:15 +00002224 Q.Inst = I;
George Burgess IVe1100f52016-02-02 22:46:49 +00002225 Q.IsCall = false;
George Burgess IVe1100f52016-02-02 22:46:49 +00002226
George Burgess IV5f308972016-07-19 01:29:15 +00002227 if (auto *CacheResult = Cache.lookup(StartingUseOrDef, Loc, Q.IsCall))
George Burgess IVe1100f52016-02-02 22:46:49 +00002228 return CacheResult;
2229
2230 // Unlike the other function, do not walk to the def of a def, because we are
2231 // handed something we already believe is the clobbering access.
2232 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
2233 ? StartingUseOrDef->getDefiningAccess()
2234 : StartingUseOrDef;
2235
2236 MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00002237 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2238 DEBUG(dbgs() << *StartingUseOrDef << "\n");
2239 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2240 DEBUG(dbgs() << *Clobber << "\n");
2241 return Clobber;
2242}
2243
2244MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002245MemorySSA::CachingWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
2246 auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
2247 // If this is a MemoryPhi, we can't do anything.
2248 if (!StartingAccess)
2249 return MA;
George Burgess IVe1100f52016-02-02 22:46:49 +00002250
George Burgess IV400ae402016-07-20 19:51:34 +00002251 const Instruction *I = StartingAccess->getMemoryInst();
George Burgess IV5f308972016-07-19 01:29:15 +00002252 UpwardsMemoryQuery Q(I, StartingAccess);
David Majnemera940f362016-07-15 17:19:24 +00002253 // We can't sanely do anything with a fences, they conservatively
George Burgess IVe1100f52016-02-02 22:46:49 +00002254 // clobber all memory, and have no locations to get pointers from to
David Majnemera940f362016-07-15 17:19:24 +00002255 // try to disambiguate.
George Burgess IV5f308972016-07-19 01:29:15 +00002256 if (!Q.IsCall && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002257 return StartingAccess;
2258
George Burgess IV5f308972016-07-19 01:29:15 +00002259 if (auto *CacheResult = Cache.lookup(StartingAccess, Q.StartingLoc, Q.IsCall))
George Burgess IVe1100f52016-02-02 22:46:49 +00002260 return CacheResult;
2261
George Burgess IV024f3d22016-08-03 19:57:02 +00002262 if (isUseTriviallyOptimizableToLiveOnEntry(*MSSA->AA, I)) {
2263 MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef();
2264 Cache.insert(StartingAccess, LiveOnEntry, Q.StartingLoc, Q.IsCall);
2265 return LiveOnEntry;
2266 }
2267
George Burgess IVe1100f52016-02-02 22:46:49 +00002268 // Start with the thing we already think clobbers this location
2269 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
2270
2271 // At this point, DefiningAccess may be the live on entry def.
2272 // If it is, we will not get a better result.
2273 if (MSSA->isLiveOnEntryDef(DefiningAccess))
2274 return DefiningAccess;
2275
2276 MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00002277 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2278 DEBUG(dbgs() << *DefiningAccess << "\n");
2279 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2280 DEBUG(dbgs() << *Result << "\n");
2281
2282 return Result;
2283}
2284
Geoff Berry9fe26e62016-04-22 14:44:10 +00002285// Verify that MA doesn't exist in any of the caches.
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002286void MemorySSA::CachingWalker::verifyRemoved(MemoryAccess *MA) {
George Burgess IV5f308972016-07-19 01:29:15 +00002287 assert(!Cache.contains(MA) && "Found removed MemoryAccess in cache.");
Geoff Berry9fe26e62016-04-22 14:44:10 +00002288}
2289
George Burgess IVe1100f52016-02-02 22:46:49 +00002290MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002291DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002292 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
2293 return Use->getDefiningAccess();
2294 return MA;
2295}
2296
2297MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
2298 MemoryAccess *StartingAccess, MemoryLocation &) {
2299 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
2300 return Use->getDefiningAccess();
2301 return StartingAccess;
2302}
George Burgess IV5f308972016-07-19 01:29:15 +00002303} // namespace llvm