blob: e4acddd969bf5294bc6709a603d8de5341be5517 [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 }
Geoff Berrycdf53332016-08-08 17:52:01 +00001028
1029 void verify(const MemorySSA *MSSA) { assert(MSSA == &this->MSSA); }
George Burgess IV5f308972016-07-19 01:29:15 +00001030};
1031
1032struct RenamePassData {
1033 DomTreeNode *DTN;
1034 DomTreeNode::const_iterator ChildIt;
1035 MemoryAccess *IncomingVal;
1036
1037 RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
1038 MemoryAccess *M)
1039 : DTN(D), ChildIt(It), IncomingVal(M) {}
1040 void swap(RenamePassData &RHS) {
1041 std::swap(DTN, RHS.DTN);
1042 std::swap(ChildIt, RHS.ChildIt);
1043 std::swap(IncomingVal, RHS.IncomingVal);
1044 }
1045};
1046} // anonymous namespace
1047
1048namespace llvm {
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001049/// \brief A MemorySSAWalker that does AA walks and caching of lookups to
1050/// disambiguate accesses.
1051///
1052/// FIXME: The current implementation of this can take quadratic space in rare
1053/// cases. This can be fixed, but it is something to note until it is fixed.
1054///
1055/// In order to trigger this behavior, you need to store to N distinct locations
1056/// (that AA can prove don't alias), perform M stores to other memory
1057/// locations that AA can prove don't alias any of the initial N locations, and
1058/// then load from all of the N locations. In this case, we insert M cache
1059/// entries for each of the N loads.
1060///
1061/// For example:
1062/// define i32 @foo() {
1063/// %a = alloca i32, align 4
1064/// %b = alloca i32, align 4
1065/// store i32 0, i32* %a, align 4
1066/// store i32 0, i32* %b, align 4
1067///
1068/// ; Insert M stores to other memory that doesn't alias %a or %b here
1069///
1070/// %c = load i32, i32* %a, align 4 ; Caches M entries in
1071/// ; CachedUpwardsClobberingAccess for the
1072/// ; MemoryLocation %a
1073/// %d = load i32, i32* %b, align 4 ; Caches M entries in
1074/// ; CachedUpwardsClobberingAccess for the
1075/// ; MemoryLocation %b
1076///
1077/// ; For completeness' sake, loading %a or %b again would not cache *another*
1078/// ; M entries.
1079/// %r = add i32 %c, %d
1080/// ret i32 %r
1081/// }
1082class MemorySSA::CachingWalker final : public MemorySSAWalker {
George Burgess IV5f308972016-07-19 01:29:15 +00001083 WalkerCache Cache;
1084 ClobberWalker Walker;
1085 bool AutoResetWalker;
1086
1087 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *, UpwardsMemoryQuery &);
1088 void verifyRemoved(MemoryAccess *);
1089
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001090public:
1091 CachingWalker(MemorySSA *, AliasAnalysis *, DominatorTree *);
1092 ~CachingWalker() override;
1093
George Burgess IV400ae402016-07-20 19:51:34 +00001094 using MemorySSAWalker::getClobberingMemoryAccess;
1095 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) override;
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001096 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
1097 MemoryLocation &) override;
1098 void invalidateInfo(MemoryAccess *) override;
1099
George Burgess IV5f308972016-07-19 01:29:15 +00001100 /// Whether we call resetClobberWalker() after each time we *actually* walk to
1101 /// answer a clobber query.
1102 void setAutoResetWalker(bool AutoReset) { AutoResetWalker = AutoReset; }
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001103
George Burgess IV5f308972016-07-19 01:29:15 +00001104 /// Drop the walker's persistent data structures. At the moment, this means
1105 /// "drop the walker's cache of BasicBlocks ->
1106 /// earliest-MemoryAccess-we-can-optimize-to". This is necessary if we're
1107 /// going to have DT updates, if we remove MemoryAccesses, etc.
1108 void resetClobberWalker() { Walker.reset(); }
Geoff Berrycdf53332016-08-08 17:52:01 +00001109
1110 void verify(const MemorySSA *MSSA) override {
1111 MemorySSAWalker::verify(MSSA);
1112 Walker.verify(MSSA);
1113 }
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001114};
George Burgess IVe1100f52016-02-02 22:46:49 +00001115
George Burgess IVe1100f52016-02-02 22:46:49 +00001116/// \brief Rename a single basic block into MemorySSA form.
1117/// Uses the standard SSA renaming algorithm.
1118/// \returns The new incoming value.
1119MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB,
1120 MemoryAccess *IncomingVal) {
1121 auto It = PerBlockAccesses.find(BB);
1122 // Skip most processing if the list is empty.
1123 if (It != PerBlockAccesses.end()) {
Daniel Berlinada263d2016-06-20 20:21:33 +00001124 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001125 for (MemoryAccess &L : *Accesses) {
Daniel Berlin868381b2016-08-22 19:14:16 +00001126 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&L)) {
1127 if (MUD->getDefiningAccess() == nullptr)
1128 MUD->setDefiningAccess(IncomingVal);
1129 if (isa<MemoryDef>(&L))
1130 IncomingVal = &L;
1131 } else {
George Burgess IVe1100f52016-02-02 22:46:49 +00001132 IncomingVal = &L;
George Burgess IVe1100f52016-02-02 22:46:49 +00001133 }
1134 }
1135 }
1136
1137 // Pass through values to our successors
1138 for (const BasicBlock *S : successors(BB)) {
1139 auto It = PerBlockAccesses.find(S);
1140 // Rename the phi nodes in our successor block
1141 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1142 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +00001143 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001144 auto *Phi = cast<MemoryPhi>(&Accesses->front());
George Burgess IVe1100f52016-02-02 22:46:49 +00001145 Phi->addIncoming(IncomingVal, BB);
1146 }
1147
1148 return IncomingVal;
1149}
1150
1151/// \brief This is the standard SSA renaming algorithm.
1152///
1153/// We walk the dominator tree in preorder, renaming accesses, and then filling
1154/// in phi nodes in our successors.
1155void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
1156 SmallPtrSet<BasicBlock *, 16> &Visited) {
1157 SmallVector<RenamePassData, 32> WorkStack;
1158 IncomingVal = renameBlock(Root->getBlock(), IncomingVal);
1159 WorkStack.push_back({Root, Root->begin(), IncomingVal});
1160 Visited.insert(Root->getBlock());
1161
1162 while (!WorkStack.empty()) {
1163 DomTreeNode *Node = WorkStack.back().DTN;
1164 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
1165 IncomingVal = WorkStack.back().IncomingVal;
1166
1167 if (ChildIt == Node->end()) {
1168 WorkStack.pop_back();
1169 } else {
1170 DomTreeNode *Child = *ChildIt;
1171 ++WorkStack.back().ChildIt;
1172 BasicBlock *BB = Child->getBlock();
1173 Visited.insert(BB);
1174 IncomingVal = renameBlock(BB, IncomingVal);
1175 WorkStack.push_back({Child, Child->begin(), IncomingVal});
1176 }
1177 }
1178}
1179
1180/// \brief Compute dominator levels, used by the phi insertion algorithm above.
1181void MemorySSA::computeDomLevels(DenseMap<DomTreeNode *, unsigned> &DomLevels) {
1182 for (auto DFI = df_begin(DT->getRootNode()), DFE = df_end(DT->getRootNode());
1183 DFI != DFE; ++DFI)
1184 DomLevels[*DFI] = DFI.getPathLength() - 1;
1185}
1186
George Burgess IVa362b092016-07-06 00:28:43 +00001187/// \brief This handles unreachable block accesses by deleting phi nodes in
George Burgess IVe1100f52016-02-02 22:46:49 +00001188/// unreachable blocks, and marking all other unreachable MemoryAccess's as
1189/// being uses of the live on entry definition.
1190void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
1191 assert(!DT->isReachableFromEntry(BB) &&
1192 "Reachable block found while handling unreachable blocks");
1193
Daniel Berlinfc7e6512016-07-06 05:32:05 +00001194 // Make sure phi nodes in our reachable successors end up with a
1195 // LiveOnEntryDef for our incoming edge, even though our block is forward
1196 // unreachable. We could just disconnect these blocks from the CFG fully,
1197 // but we do not right now.
1198 for (const BasicBlock *S : successors(BB)) {
1199 if (!DT->isReachableFromEntry(S))
1200 continue;
1201 auto It = PerBlockAccesses.find(S);
1202 // Rename the phi nodes in our successor block
1203 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1204 continue;
1205 AccessList *Accesses = It->second.get();
1206 auto *Phi = cast<MemoryPhi>(&Accesses->front());
1207 Phi->addIncoming(LiveOnEntryDef.get(), BB);
1208 }
1209
George Burgess IVe1100f52016-02-02 22:46:49 +00001210 auto It = PerBlockAccesses.find(BB);
1211 if (It == PerBlockAccesses.end())
1212 return;
1213
1214 auto &Accesses = It->second;
1215 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1216 auto Next = std::next(AI);
1217 // If we have a phi, just remove it. We are going to replace all
1218 // users with live on entry.
1219 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1220 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1221 else
1222 Accesses->erase(AI);
1223 AI = Next;
1224 }
1225}
1226
Geoff Berryb96d3b22016-06-01 21:30:40 +00001227MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
1228 : AA(AA), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
1229 NextID(0) {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001230 buildMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001231}
1232
George Burgess IVe1100f52016-02-02 22:46:49 +00001233MemorySSA::~MemorySSA() {
1234 // Drop all our references
1235 for (const auto &Pair : PerBlockAccesses)
1236 for (MemoryAccess &MA : *Pair.second)
1237 MA.dropAllReferences();
1238}
1239
Daniel Berlin14300262016-06-21 18:39:20 +00001240MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001241 auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
1242
1243 if (Res.second)
Daniel Berlinada263d2016-06-20 20:21:33 +00001244 Res.first->second = make_unique<AccessList>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001245 return Res.first->second.get();
1246}
1247
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001248/// This class is a batch walker of all MemoryUse's in the program, and points
1249/// their defining access at the thing that actually clobbers them. Because it
1250/// is a batch walker that touches everything, it does not operate like the
1251/// other walkers. This walker is basically performing a top-down SSA renaming
1252/// pass, where the version stack is used as the cache. This enables it to be
1253/// significantly more time and memory efficient than using the regular walker,
1254/// which is walking bottom-up.
1255class MemorySSA::OptimizeUses {
1256public:
1257 OptimizeUses(MemorySSA *MSSA, MemorySSAWalker *Walker, AliasAnalysis *AA,
1258 DominatorTree *DT)
1259 : MSSA(MSSA), Walker(Walker), AA(AA), DT(DT) {
1260 Walker = MSSA->getWalker();
1261 }
1262
1263 void optimizeUses();
1264
1265private:
1266 /// This represents where a given memorylocation is in the stack.
1267 struct MemlocStackInfo {
1268 // This essentially is keeping track of versions of the stack. Whenever
1269 // the stack changes due to pushes or pops, these versions increase.
1270 unsigned long StackEpoch;
1271 unsigned long PopEpoch;
1272 // This is the lower bound of places on the stack to check. It is equal to
1273 // the place the last stack walk ended.
1274 // Note: Correctness depends on this being initialized to 0, which densemap
1275 // does
1276 unsigned long LowerBound;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001277 const BasicBlock *LowerBoundBlock;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001278 // This is where the last walk for this memory location ended.
1279 unsigned long LastKill;
1280 bool LastKillValid;
1281 };
1282 void optimizeUsesInBlock(const BasicBlock *, unsigned long &, unsigned long &,
1283 SmallVectorImpl<MemoryAccess *> &,
1284 DenseMap<MemoryLocOrCall, MemlocStackInfo> &);
1285 MemorySSA *MSSA;
1286 MemorySSAWalker *Walker;
1287 AliasAnalysis *AA;
1288 DominatorTree *DT;
1289};
1290
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001291/// Optimize the uses in a given block This is basically the SSA renaming
1292/// algorithm, with one caveat: We are able to use a single stack for all
1293/// MemoryUses. This is because the set of *possible* reaching MemoryDefs is
1294/// the same for every MemoryUse. The *actual* clobbering MemoryDef is just
1295/// going to be some position in that stack of possible ones.
1296///
1297/// We track the stack positions that each MemoryLocation needs
1298/// to check, and last ended at. This is because we only want to check the
1299/// things that changed since last time. The same MemoryLocation should
1300/// get clobbered by the same store (getModRefInfo does not use invariantness or
1301/// things like this, and if they start, we can modify MemoryLocOrCall to
1302/// include relevant data)
1303void MemorySSA::OptimizeUses::optimizeUsesInBlock(
1304 const BasicBlock *BB, unsigned long &StackEpoch, unsigned long &PopEpoch,
1305 SmallVectorImpl<MemoryAccess *> &VersionStack,
1306 DenseMap<MemoryLocOrCall, MemlocStackInfo> &LocStackInfo) {
1307
1308 /// If no accesses, nothing to do.
1309 MemorySSA::AccessList *Accesses = MSSA->getWritableBlockAccesses(BB);
1310 if (Accesses == nullptr)
1311 return;
1312
1313 // Pop everything that doesn't dominate the current block off the stack,
1314 // increment the PopEpoch to account for this.
1315 while (!VersionStack.empty()) {
1316 BasicBlock *BackBlock = VersionStack.back()->getBlock();
1317 if (DT->dominates(BackBlock, BB))
1318 break;
1319 while (VersionStack.back()->getBlock() == BackBlock)
1320 VersionStack.pop_back();
1321 ++PopEpoch;
1322 }
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001323 for (MemoryAccess &MA : *Accesses) {
1324 auto *MU = dyn_cast<MemoryUse>(&MA);
1325 if (!MU) {
1326 VersionStack.push_back(&MA);
1327 ++StackEpoch;
1328 continue;
1329 }
1330
George Burgess IV024f3d22016-08-03 19:57:02 +00001331 if (isUseTriviallyOptimizableToLiveOnEntry(*AA, MU->getMemoryInst())) {
1332 MU->setDefiningAccess(MSSA->getLiveOnEntryDef());
1333 continue;
1334 }
1335
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001336 MemoryLocOrCall UseMLOC(MU);
1337 auto &LocInfo = LocStackInfo[UseMLOC];
Daniel Berlin26fcea92016-08-02 20:02:21 +00001338 // If the pop epoch changed, it means we've removed stuff from top of
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001339 // stack due to changing blocks. We may have to reset the lower bound or
1340 // last kill info.
1341 if (LocInfo.PopEpoch != PopEpoch) {
1342 LocInfo.PopEpoch = PopEpoch;
1343 LocInfo.StackEpoch = StackEpoch;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001344 // If the lower bound was in something that no longer dominates us, we
1345 // have to reset it.
1346 // We can't simply track stack size, because the stack may have had
1347 // pushes/pops in the meantime.
1348 // XXX: This is non-optimal, but only is slower cases with heavily
1349 // branching dominator trees. To get the optimal number of queries would
1350 // be to make lowerbound and lastkill a per-loc stack, and pop it until
1351 // the top of that stack dominates us. This does not seem worth it ATM.
1352 // A much cheaper optimization would be to always explore the deepest
1353 // branch of the dominator tree first. This will guarantee this resets on
1354 // the smallest set of blocks.
1355 if (LocInfo.LowerBoundBlock && LocInfo.LowerBoundBlock != BB &&
1356 !DT->dominates(LocInfo.LowerBoundBlock, BB)){
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001357 // Reset the lower bound of things to check.
1358 // TODO: Some day we should be able to reset to last kill, rather than
1359 // 0.
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001360 LocInfo.LowerBound = 0;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001361 LocInfo.LowerBoundBlock = VersionStack[0]->getBlock();
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001362 LocInfo.LastKillValid = false;
1363 }
1364 } else if (LocInfo.StackEpoch != StackEpoch) {
1365 // If all that has changed is the StackEpoch, we only have to check the
1366 // new things on the stack, because we've checked everything before. In
1367 // this case, the lower bound of things to check remains the same.
1368 LocInfo.PopEpoch = PopEpoch;
1369 LocInfo.StackEpoch = StackEpoch;
1370 }
1371 if (!LocInfo.LastKillValid) {
1372 LocInfo.LastKill = VersionStack.size() - 1;
1373 LocInfo.LastKillValid = true;
1374 }
1375
1376 // At this point, we should have corrected last kill and LowerBound to be
1377 // in bounds.
1378 assert(LocInfo.LowerBound < VersionStack.size() &&
1379 "Lower bound out of range");
1380 assert(LocInfo.LastKill < VersionStack.size() &&
1381 "Last kill info out of range");
1382 // In any case, the new upper bound is the top of the stack.
1383 unsigned long UpperBound = VersionStack.size() - 1;
1384
1385 if (UpperBound - LocInfo.LowerBound > MaxCheckLimit) {
Daniel Berlin26fcea92016-08-02 20:02:21 +00001386 DEBUG(dbgs() << "MemorySSA skipping optimization of " << *MU << " ("
1387 << *(MU->getMemoryInst()) << ")"
1388 << " because there are " << UpperBound - LocInfo.LowerBound
1389 << " stores to disambiguate\n");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001390 // Because we did not walk, LastKill is no longer valid, as this may
1391 // have been a kill.
1392 LocInfo.LastKillValid = false;
1393 continue;
1394 }
1395 bool FoundClobberResult = false;
1396 while (UpperBound > LocInfo.LowerBound) {
1397 if (isa<MemoryPhi>(VersionStack[UpperBound])) {
1398 // For phis, use the walker, see where we ended up, go there
1399 Instruction *UseInst = MU->getMemoryInst();
1400 MemoryAccess *Result = Walker->getClobberingMemoryAccess(UseInst);
1401 // We are guaranteed to find it or something is wrong
1402 while (VersionStack[UpperBound] != Result) {
1403 assert(UpperBound != 0);
1404 --UpperBound;
1405 }
1406 FoundClobberResult = true;
1407 break;
1408 }
1409
1410 MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]);
Daniel Berlindf101192016-08-03 00:01:46 +00001411 // If the lifetime of the pointer ends at this instruction, it's live on
1412 // entry.
1413 if (!UseMLOC.IsCall && lifetimeEndsAt(MD, UseMLOC.getLoc(), *AA)) {
1414 // Reset UpperBound to liveOnEntryDef's place in the stack
1415 UpperBound = 0;
1416 FoundClobberResult = true;
1417 break;
1418 }
Daniel Berlindff31de2016-08-02 21:57:52 +00001419 if (instructionClobbersQuery(MD, MU, UseMLOC, *AA)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001420 FoundClobberResult = true;
1421 break;
1422 }
1423 --UpperBound;
1424 }
1425 // At the end of this loop, UpperBound is either a clobber, or lower bound
1426 // PHI walking may cause it to be < LowerBound, and in fact, < LastKill.
1427 if (FoundClobberResult || UpperBound < LocInfo.LastKill) {
1428 MU->setDefiningAccess(VersionStack[UpperBound]);
1429 // We were last killed now by where we got to
1430 LocInfo.LastKill = UpperBound;
1431 } else {
1432 // Otherwise, we checked all the new ones, and now we know we can get to
1433 // LastKill.
1434 MU->setDefiningAccess(VersionStack[LocInfo.LastKill]);
1435 }
1436 LocInfo.LowerBound = VersionStack.size() - 1;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001437 LocInfo.LowerBoundBlock = BB;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001438 }
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;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001453 VersionStack.push_back(MSSA->getLiveOnEntryDef());
1454
1455 unsigned long StackEpoch = 1;
1456 unsigned long PopEpoch = 1;
Daniel Berlin7ac3d742016-08-05 22:09:14 +00001457 for (const auto *DomNode : depth_first(DT->getRootNode()))
1458 optimizeUsesInBlock(DomNode->getBlock(), StackEpoch, PopEpoch, VersionStack,
1459 LocStackInfo);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001460}
1461
Daniel Berlin3d512a22016-08-22 19:14:30 +00001462void MemorySSA::placePHINodes(
1463 const SmallPtrSetImpl<BasicBlock *> &DefiningBlocks,
1464 const SmallPtrSetImpl<BasicBlock *> &LiveInBlocks) {
1465 // Determine where our MemoryPhi's should go
1466 ForwardIDFCalculator IDFs(*DT);
1467 IDFs.setDefiningBlocks(DefiningBlocks);
1468 IDFs.setLiveInBlocks(LiveInBlocks);
1469 SmallVector<BasicBlock *, 32> IDFBlocks;
1470 IDFs.calculate(IDFBlocks);
1471
1472 // Now place MemoryPhi nodes.
1473 for (auto &BB : IDFBlocks) {
1474 // Insert phi node
1475 AccessList *Accesses = getOrCreateAccessList(BB);
1476 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
1477 ValueToMemoryAccess[BB] = Phi;
1478 // Phi's always are placed at the front of the block.
1479 Accesses->push_front(Phi);
1480 }
1481}
1482
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001483void MemorySSA::buildMemorySSA() {
George Burgess IVe1100f52016-02-02 22:46:49 +00001484 // We create an access to represent "live on entry", for things like
1485 // arguments or users of globals, where the memory they use is defined before
1486 // the beginning of the function. We do not actually insert it into the IR.
1487 // We do not define a live on exit for the immediate uses, and thus our
1488 // semantics do *not* imply that something with no immediate uses can simply
1489 // be removed.
1490 BasicBlock &StartingPoint = F.getEntryBlock();
1491 LiveOnEntryDef = make_unique<MemoryDef>(F.getContext(), nullptr, nullptr,
1492 &StartingPoint, NextID++);
1493
1494 // We maintain lists of memory accesses per-block, trading memory for time. We
1495 // could just look up the memory access for every possible instruction in the
1496 // stream.
1497 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001498 SmallPtrSet<BasicBlock *, 32> DefUseBlocks;
George Burgess IVe1100f52016-02-02 22:46:49 +00001499 // Go through each block, figure out where defs occur, and chain together all
1500 // the accesses.
1501 for (BasicBlock &B : F) {
Daniel Berlin7898ca62016-02-07 01:52:15 +00001502 bool InsertIntoDef = false;
Daniel Berlinada263d2016-06-20 20:21:33 +00001503 AccessList *Accesses = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +00001504 for (Instruction &I : B) {
Peter Collingbourneffecb142016-05-26 01:19:17 +00001505 MemoryUseOrDef *MUD = createNewAccess(&I);
George Burgess IVb42b7622016-03-11 19:34:03 +00001506 if (!MUD)
George Burgess IVe1100f52016-02-02 22:46:49 +00001507 continue;
George Burgess IV3887a412016-03-21 21:25:39 +00001508 InsertIntoDef |= isa<MemoryDef>(MUD);
Daniel Berlin1b51a292016-02-07 01:52:19 +00001509
George Burgess IVe1100f52016-02-02 22:46:49 +00001510 if (!Accesses)
1511 Accesses = getOrCreateAccessList(&B);
George Burgess IVb42b7622016-03-11 19:34:03 +00001512 Accesses->push_back(MUD);
George Burgess IVe1100f52016-02-02 22:46:49 +00001513 }
Daniel Berlin7898ca62016-02-07 01:52:15 +00001514 if (InsertIntoDef)
1515 DefiningBlocks.insert(&B);
George Burgess IV3887a412016-03-21 21:25:39 +00001516 if (Accesses)
Daniel Berlin1b51a292016-02-07 01:52:19 +00001517 DefUseBlocks.insert(&B);
1518 }
1519
1520 // Compute live-in.
1521 // Live in is normally defined as "all the blocks on the path from each def to
1522 // each of it's uses".
1523 // MemoryDef's are implicit uses of previous state, so they are also uses.
1524 // This means we don't really have def-only instructions. The only
1525 // MemoryDef's that are not really uses are those that are of the LiveOnEntry
1526 // variable (because LiveOnEntry can reach anywhere, and every def is a
1527 // must-kill of LiveOnEntry).
1528 // In theory, you could precisely compute live-in by using alias-analysis to
1529 // disambiguate defs and uses to see which really pair up with which.
1530 // In practice, this would be really expensive and difficult. So we simply
1531 // assume all defs are also uses that need to be kept live.
1532 // Because of this, the end result of this live-in computation will be "the
1533 // entire set of basic blocks that reach any use".
1534
1535 SmallPtrSet<BasicBlock *, 32> LiveInBlocks;
1536 SmallVector<BasicBlock *, 64> LiveInBlockWorklist(DefUseBlocks.begin(),
1537 DefUseBlocks.end());
1538 // Now that we have a set of blocks where a value is live-in, recursively add
1539 // predecessors until we find the full region the value is live.
1540 while (!LiveInBlockWorklist.empty()) {
1541 BasicBlock *BB = LiveInBlockWorklist.pop_back_val();
1542
1543 // The block really is live in here, insert it into the set. If already in
1544 // the set, then it has already been processed.
1545 if (!LiveInBlocks.insert(BB).second)
1546 continue;
1547
1548 // Since the value is live into BB, it is either defined in a predecessor or
1549 // live into it to.
1550 LiveInBlockWorklist.append(pred_begin(BB), pred_end(BB));
George Burgess IVe1100f52016-02-02 22:46:49 +00001551 }
Daniel Berlin3d512a22016-08-22 19:14:30 +00001552 placePHINodes(DefiningBlocks, LiveInBlocks);
George Burgess IVe1100f52016-02-02 22:46:49 +00001553
1554 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
1555 // filled in with all blocks.
1556 SmallPtrSet<BasicBlock *, 16> Visited;
1557 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1558
George Burgess IV5f308972016-07-19 01:29:15 +00001559 CachingWalker *Walker = getWalkerImpl();
1560
1561 // We're doing a batch of updates; don't drop useful caches between them.
1562 Walker->setAutoResetWalker(false);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001563 OptimizeUses(this, Walker, AA, DT).optimizeUses();
George Burgess IV5f308972016-07-19 01:29:15 +00001564 Walker->setAutoResetWalker(true);
1565 Walker->resetClobberWalker();
1566
George Burgess IVe1100f52016-02-02 22:46:49 +00001567 // Mark the uses in unreachable blocks as live on entry, so that they go
1568 // somewhere.
1569 for (auto &BB : F)
1570 if (!Visited.count(&BB))
1571 markUnreachableAsLiveOnEntry(&BB);
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001572}
George Burgess IVe1100f52016-02-02 22:46:49 +00001573
George Burgess IV5f308972016-07-19 01:29:15 +00001574MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
1575
1576MemorySSA::CachingWalker *MemorySSA::getWalkerImpl() {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001577 if (Walker)
1578 return Walker.get();
1579
1580 Walker = make_unique<CachingWalker>(this, AA, DT);
Geoff Berryb96d3b22016-06-01 21:30:40 +00001581 return Walker.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001582}
1583
Daniel Berlin14300262016-06-21 18:39:20 +00001584MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
1585 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
1586 AccessList *Accesses = getOrCreateAccessList(BB);
1587 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlin5130cc82016-07-31 21:08:20 +00001588 ValueToMemoryAccess[BB] = Phi;
Daniel Berlin14300262016-06-21 18:39:20 +00001589 // Phi's always are placed at the front of the block.
1590 Accesses->push_front(Phi);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001591 BlockNumberingValid.erase(BB);
Daniel Berlin14300262016-06-21 18:39:20 +00001592 return Phi;
1593}
1594
1595MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
1596 MemoryAccess *Definition) {
1597 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
1598 MemoryUseOrDef *NewAccess = createNewAccess(I);
1599 assert(
1600 NewAccess != nullptr &&
1601 "Tried to create a memory access for a non-memory touching instruction");
1602 NewAccess->setDefiningAccess(Definition);
1603 return NewAccess;
1604}
1605
1606MemoryAccess *MemorySSA::createMemoryAccessInBB(Instruction *I,
1607 MemoryAccess *Definition,
1608 const BasicBlock *BB,
1609 InsertionPlace Point) {
1610 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1611 auto *Accesses = getOrCreateAccessList(BB);
1612 if (Point == Beginning) {
1613 // It goes after any phi nodes
David Majnemer42531262016-08-12 03:55:06 +00001614 auto AI = find_if(
1615 *Accesses, [](const MemoryAccess &MA) { return !isa<MemoryPhi>(MA); });
Daniel Berlin14300262016-06-21 18:39:20 +00001616
1617 Accesses->insert(AI, NewAccess);
1618 } else {
1619 Accesses->push_back(NewAccess);
1620 }
Daniel Berlin5c46b942016-07-19 22:49:43 +00001621 BlockNumberingValid.erase(BB);
Daniel Berlin14300262016-06-21 18:39:20 +00001622 return NewAccess;
1623}
1624MemoryAccess *MemorySSA::createMemoryAccessBefore(Instruction *I,
1625 MemoryAccess *Definition,
1626 MemoryAccess *InsertPt) {
1627 assert(I->getParent() == InsertPt->getBlock() &&
1628 "New and old access must be in the same block");
1629 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1630 auto *Accesses = getOrCreateAccessList(InsertPt->getBlock());
1631 Accesses->insert(AccessList::iterator(InsertPt), NewAccess);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001632 BlockNumberingValid.erase(InsertPt->getBlock());
Daniel Berlin14300262016-06-21 18:39:20 +00001633 return NewAccess;
1634}
1635
1636MemoryAccess *MemorySSA::createMemoryAccessAfter(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->insertAfter(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
George Burgess IVe1100f52016-02-02 22:46:49 +00001648/// \brief Helper function to create new memory accesses
Peter Collingbourneffecb142016-05-26 01:19:17 +00001649MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I) {
Peter Collingbourneb9aa1f42016-05-26 04:58:46 +00001650 // The assume intrinsic has a control dependency which we model by claiming
1651 // that it writes arbitrarily. Ignore that fake memory dependency here.
1652 // FIXME: Replace this special casing with a more accurate modelling of
1653 // assume's control dependency.
1654 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1655 if (II->getIntrinsicID() == Intrinsic::assume)
1656 return nullptr;
1657
George Burgess IVe1100f52016-02-02 22:46:49 +00001658 // Find out what affect this instruction has on memory.
1659 ModRefInfo ModRef = AA->getModRefInfo(I);
1660 bool Def = bool(ModRef & MRI_Mod);
1661 bool Use = bool(ModRef & MRI_Ref);
1662
1663 // It's possible for an instruction to not modify memory at all. During
1664 // construction, we ignore them.
Peter Collingbourneffecb142016-05-26 01:19:17 +00001665 if (!Def && !Use)
George Burgess IVe1100f52016-02-02 22:46:49 +00001666 return nullptr;
1667
1668 assert((Def || Use) &&
1669 "Trying to create a memory access with a non-memory instruction");
1670
George Burgess IVb42b7622016-03-11 19:34:03 +00001671 MemoryUseOrDef *MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001672 if (Def)
George Burgess IVb42b7622016-03-11 19:34:03 +00001673 MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
George Burgess IVe1100f52016-02-02 22:46:49 +00001674 else
George Burgess IVb42b7622016-03-11 19:34:03 +00001675 MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
Daniel Berlin5130cc82016-07-31 21:08:20 +00001676 ValueToMemoryAccess[I] = MUD;
George Burgess IVb42b7622016-03-11 19:34:03 +00001677 return MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001678}
1679
1680MemoryAccess *MemorySSA::findDominatingDef(BasicBlock *UseBlock,
1681 enum InsertionPlace Where) {
1682 // Handle the initial case
1683 if (Where == Beginning)
1684 // The only thing that could define us at the beginning is a phi node
1685 if (MemoryPhi *Phi = getMemoryAccess(UseBlock))
1686 return Phi;
1687
1688 DomTreeNode *CurrNode = DT->getNode(UseBlock);
1689 // Need to be defined by our dominator
1690 if (Where == Beginning)
1691 CurrNode = CurrNode->getIDom();
1692 Where = End;
1693 while (CurrNode) {
1694 auto It = PerBlockAccesses.find(CurrNode->getBlock());
1695 if (It != PerBlockAccesses.end()) {
1696 auto &Accesses = It->second;
David Majnemerd7708772016-06-24 04:05:21 +00001697 for (MemoryAccess &RA : reverse(*Accesses)) {
1698 if (isa<MemoryDef>(RA) || isa<MemoryPhi>(RA))
1699 return &RA;
George Burgess IVe1100f52016-02-02 22:46:49 +00001700 }
1701 }
1702 CurrNode = CurrNode->getIDom();
1703 }
1704 return LiveOnEntryDef.get();
1705}
1706
1707/// \brief Returns true if \p Replacer dominates \p Replacee .
1708bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
1709 const MemoryAccess *Replacee) const {
1710 if (isa<MemoryUseOrDef>(Replacee))
1711 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
1712 const auto *MP = cast<MemoryPhi>(Replacee);
1713 // For a phi node, the use occurs in the predecessor block of the phi node.
1714 // Since we may occur multiple times in the phi node, we have to check each
1715 // operand to ensure Replacer dominates each operand where Replacee occurs.
1716 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +00001717 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +00001718 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
1719 return false;
1720 }
1721 return true;
1722}
1723
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001724/// \brief If all arguments of a MemoryPHI are defined by the same incoming
1725/// argument, return that argument.
1726static MemoryAccess *onlySingleValue(MemoryPhi *MP) {
1727 MemoryAccess *MA = nullptr;
1728
1729 for (auto &Arg : MP->operands()) {
1730 if (!MA)
1731 MA = cast<MemoryAccess>(Arg);
1732 else if (MA != Arg)
1733 return nullptr;
1734 }
1735 return MA;
1736}
1737
1738/// \brief Properly remove \p MA from all of MemorySSA's lookup tables.
1739///
1740/// Because of the way the intrusive list and use lists work, it is important to
1741/// do removal in the right order.
1742void MemorySSA::removeFromLookups(MemoryAccess *MA) {
1743 assert(MA->use_empty() &&
1744 "Trying to remove memory access that still has uses");
Daniel Berlin5c46b942016-07-19 22:49:43 +00001745 BlockNumbering.erase(MA);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001746 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA))
1747 MUD->setDefiningAccess(nullptr);
1748 // Invalidate our walker's cache if necessary
1749 if (!isa<MemoryUse>(MA))
1750 Walker->invalidateInfo(MA);
1751 // The call below to erase will destroy MA, so we can't change the order we
1752 // are doing things here
1753 Value *MemoryInst;
1754 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
1755 MemoryInst = MUD->getMemoryInst();
1756 } else {
1757 MemoryInst = MA->getBlock();
1758 }
Daniel Berlin5130cc82016-07-31 21:08:20 +00001759 auto VMA = ValueToMemoryAccess.find(MemoryInst);
1760 if (VMA->second == MA)
1761 ValueToMemoryAccess.erase(VMA);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001762
George Burgess IVe0e6e482016-03-02 02:35:04 +00001763 auto AccessIt = PerBlockAccesses.find(MA->getBlock());
Daniel Berlinada263d2016-06-20 20:21:33 +00001764 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001765 Accesses->erase(MA);
George Burgess IVe0e6e482016-03-02 02:35:04 +00001766 if (Accesses->empty())
1767 PerBlockAccesses.erase(AccessIt);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001768}
1769
1770void MemorySSA::removeMemoryAccess(MemoryAccess *MA) {
1771 assert(!isLiveOnEntryDef(MA) && "Trying to remove the live on entry def");
1772 // We can only delete phi nodes if they have no uses, or we can replace all
1773 // uses with a single definition.
1774 MemoryAccess *NewDefTarget = nullptr;
1775 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(MA)) {
1776 // Note that it is sufficient to know that all edges of the phi node have
1777 // the same argument. If they do, by the definition of dominance frontiers
1778 // (which we used to place this phi), that argument must dominate this phi,
1779 // and thus, must dominate the phi's uses, and so we will not hit the assert
1780 // below.
1781 NewDefTarget = onlySingleValue(MP);
1782 assert((NewDefTarget || MP->use_empty()) &&
1783 "We can't delete this memory phi");
1784 } else {
1785 NewDefTarget = cast<MemoryUseOrDef>(MA)->getDefiningAccess();
1786 }
1787
1788 // Re-point the uses at our defining access
1789 if (!MA->use_empty())
1790 MA->replaceAllUsesWith(NewDefTarget);
1791
1792 // The call below to erase will destroy MA, so we can't change the order we
1793 // are doing things here
1794 removeFromLookups(MA);
1795}
1796
George Burgess IVe1100f52016-02-02 22:46:49 +00001797void MemorySSA::print(raw_ostream &OS) const {
1798 MemorySSAAnnotatedWriter Writer(this);
1799 F.print(OS, &Writer);
1800}
1801
1802void MemorySSA::dump() const {
1803 MemorySSAAnnotatedWriter Writer(this);
1804 F.print(dbgs(), &Writer);
1805}
1806
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001807void MemorySSA::verifyMemorySSA() const {
1808 verifyDefUses(F);
1809 verifyDomination(F);
Daniel Berlin14300262016-06-21 18:39:20 +00001810 verifyOrdering(F);
Geoff Berrycdf53332016-08-08 17:52:01 +00001811 Walker->verify(this);
Daniel Berlin14300262016-06-21 18:39:20 +00001812}
1813
1814/// \brief Verify that the order and existence of MemoryAccesses matches the
1815/// order and existence of memory affecting instructions.
1816void MemorySSA::verifyOrdering(Function &F) const {
1817 // Walk all the blocks, comparing what the lookups think and what the access
1818 // lists think, as well as the order in the blocks vs the order in the access
1819 // lists.
1820 SmallVector<MemoryAccess *, 32> ActualAccesses;
1821 for (BasicBlock &B : F) {
1822 const AccessList *AL = getBlockAccesses(&B);
1823 MemoryAccess *Phi = getMemoryAccess(&B);
1824 if (Phi)
1825 ActualAccesses.push_back(Phi);
1826 for (Instruction &I : B) {
1827 MemoryAccess *MA = getMemoryAccess(&I);
1828 assert((!MA || AL) && "We have memory affecting instructions "
1829 "in this block but they are not in the "
1830 "access list");
1831 if (MA)
1832 ActualAccesses.push_back(MA);
1833 }
1834 // Either we hit the assert, really have no accesses, or we have both
1835 // accesses and an access list
1836 if (!AL)
1837 continue;
1838 assert(AL->size() == ActualAccesses.size() &&
1839 "We don't have the same number of accesses in the block as on the "
1840 "access list");
1841 auto ALI = AL->begin();
1842 auto AAI = ActualAccesses.begin();
1843 while (ALI != AL->end() && AAI != ActualAccesses.end()) {
1844 assert(&*ALI == *AAI && "Not the same accesses in the same order");
1845 ++ALI;
1846 ++AAI;
1847 }
1848 ActualAccesses.clear();
1849 }
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001850}
1851
George Burgess IVe1100f52016-02-02 22:46:49 +00001852/// \brief Verify the domination properties of MemorySSA by checking that each
1853/// definition dominates all of its uses.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001854void MemorySSA::verifyDomination(Function &F) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001855#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001856 for (BasicBlock &B : F) {
1857 // Phi nodes are attached to basic blocks
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001858 if (MemoryPhi *MP = getMemoryAccess(&B))
1859 for (const Use &U : MP->uses())
1860 assert(dominates(MP, U) && "Memory PHI does not dominate it's uses");
Daniel Berlin7af95872016-08-05 21:47:20 +00001861
George Burgess IVe1100f52016-02-02 22:46:49 +00001862 for (Instruction &I : B) {
1863 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
1864 if (!MD)
1865 continue;
1866
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001867 for (const Use &U : MD->uses())
1868 assert(dominates(MD, U) && "Memory Def does not dominate it's uses");
George Burgess IVe1100f52016-02-02 22:46:49 +00001869 }
1870 }
Daniel Berlin7af95872016-08-05 21:47:20 +00001871#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001872}
1873
1874/// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use
1875/// appears in the use list of \p Def.
Daniel Berlin7af95872016-08-05 21:47:20 +00001876
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001877void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001878#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001879 // The live on entry use may cause us to get a NULL def here
Daniel Berlin7af95872016-08-05 21:47:20 +00001880 if (!Def)
1881 assert(isLiveOnEntryDef(Use) &&
1882 "Null def but use not point to live on entry def");
1883 else
Daniel Berlinda2f38e2016-08-11 21:26:50 +00001884 assert(is_contained(Def->users(), Use) &&
Daniel Berlin7af95872016-08-05 21:47:20 +00001885 "Did not find use in def's use list");
1886#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001887}
1888
1889/// \brief Verify the immediate use information, by walking all the memory
1890/// accesses and verifying that, for each use, it appears in the
1891/// appropriate def's use list
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001892void MemorySSA::verifyDefUses(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001893 for (BasicBlock &B : F) {
1894 // Phi nodes are attached to basic blocks
Daniel Berlin14300262016-06-21 18:39:20 +00001895 if (MemoryPhi *Phi = getMemoryAccess(&B)) {
David Majnemer580e7542016-06-25 00:04:06 +00001896 assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
1897 pred_begin(&B), pred_end(&B))) &&
Daniel Berlin14300262016-06-21 18:39:20 +00001898 "Incomplete MemoryPhi Node");
George Burgess IVe1100f52016-02-02 22:46:49 +00001899 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
1900 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
Daniel Berlin14300262016-06-21 18:39:20 +00001901 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001902
1903 for (Instruction &I : B) {
1904 if (MemoryAccess *MA = getMemoryAccess(&I)) {
1905 assert(isa<MemoryUseOrDef>(MA) &&
1906 "Found a phi node not attached to a bb");
1907 verifyUseInDefs(cast<MemoryUseOrDef>(MA)->getDefiningAccess(), MA);
1908 }
1909 }
1910 }
1911}
1912
1913MemoryAccess *MemorySSA::getMemoryAccess(const Value *I) const {
Daniel Berlinf6c9ae92016-02-10 17:41:25 +00001914 return ValueToMemoryAccess.lookup(I);
George Burgess IVe1100f52016-02-02 22:46:49 +00001915}
1916
1917MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const {
1918 return cast_or_null<MemoryPhi>(getMemoryAccess((const Value *)BB));
1919}
1920
Daniel Berlin5c46b942016-07-19 22:49:43 +00001921/// Perform a local numbering on blocks so that instruction ordering can be
1922/// determined in constant time.
1923/// TODO: We currently just number in order. If we numbered by N, we could
1924/// allow at least N-1 sequences of insertBefore or insertAfter (and at least
1925/// log2(N) sequences of mixed before and after) without needing to invalidate
1926/// the numbering.
1927void MemorySSA::renumberBlock(const BasicBlock *B) const {
1928 // The pre-increment ensures the numbers really start at 1.
1929 unsigned long CurrentNumber = 0;
1930 const AccessList *AL = getBlockAccesses(B);
1931 assert(AL != nullptr && "Asking to renumber an empty block");
1932 for (const auto &I : *AL)
1933 BlockNumbering[&I] = ++CurrentNumber;
1934 BlockNumberingValid.insert(B);
1935}
1936
George Burgess IVe1100f52016-02-02 22:46:49 +00001937/// \brief Determine, for two memory accesses in the same block,
1938/// whether \p Dominator dominates \p Dominatee.
1939/// \returns True if \p Dominator dominates \p Dominatee.
1940bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
1941 const MemoryAccess *Dominatee) const {
Sebastian Pope1f60b12016-06-10 21:36:41 +00001942
Daniel Berlin5c46b942016-07-19 22:49:43 +00001943 const BasicBlock *DominatorBlock = Dominator->getBlock();
Daniel Berlin5c46b942016-07-19 22:49:43 +00001944
Daniel Berlin19860302016-07-19 23:08:08 +00001945 assert((DominatorBlock == Dominatee->getBlock()) &&
Daniel Berlin5c46b942016-07-19 22:49:43 +00001946 "Asking for local domination when accesses are in different blocks!");
Sebastian Pope1f60b12016-06-10 21:36:41 +00001947 // A node dominates itself.
1948 if (Dominatee == Dominator)
1949 return true;
1950
1951 // When Dominatee is defined on function entry, it is not dominated by another
1952 // memory access.
1953 if (isLiveOnEntryDef(Dominatee))
1954 return false;
1955
1956 // When Dominator is defined on function entry, it dominates the other memory
1957 // access.
1958 if (isLiveOnEntryDef(Dominator))
1959 return true;
1960
Daniel Berlin5c46b942016-07-19 22:49:43 +00001961 if (!BlockNumberingValid.count(DominatorBlock))
1962 renumberBlock(DominatorBlock);
George Burgess IVe1100f52016-02-02 22:46:49 +00001963
Daniel Berlin5c46b942016-07-19 22:49:43 +00001964 unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
1965 // All numbers start with 1
1966 assert(DominatorNum != 0 && "Block was not numbered properly");
1967 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
1968 assert(DominateeNum != 0 && "Block was not numbered properly");
1969 return DominatorNum < DominateeNum;
George Burgess IVe1100f52016-02-02 22:46:49 +00001970}
1971
George Burgess IV5f308972016-07-19 01:29:15 +00001972bool MemorySSA::dominates(const MemoryAccess *Dominator,
1973 const MemoryAccess *Dominatee) const {
1974 if (Dominator == Dominatee)
1975 return true;
1976
1977 if (isLiveOnEntryDef(Dominatee))
1978 return false;
1979
1980 if (Dominator->getBlock() != Dominatee->getBlock())
1981 return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
1982 return locallyDominates(Dominator, Dominatee);
1983}
1984
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001985bool MemorySSA::dominates(const MemoryAccess *Dominator,
1986 const Use &Dominatee) const {
1987 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Dominatee.getUser())) {
1988 BasicBlock *UseBB = MP->getIncomingBlock(Dominatee);
1989 // The def must dominate the incoming block of the phi.
1990 if (UseBB != Dominator->getBlock())
1991 return DT->dominates(Dominator->getBlock(), UseBB);
1992 // If the UseBB and the DefBB are the same, compare locally.
1993 return locallyDominates(Dominator, cast<MemoryAccess>(Dominatee));
1994 }
1995 // If it's not a PHI node use, the normal dominates can already handle it.
1996 return dominates(Dominator, cast<MemoryAccess>(Dominatee.getUser()));
1997}
1998
George Burgess IVe1100f52016-02-02 22:46:49 +00001999const static char LiveOnEntryStr[] = "liveOnEntry";
2000
2001void MemoryDef::print(raw_ostream &OS) const {
2002 MemoryAccess *UO = getDefiningAccess();
2003
2004 OS << getID() << " = MemoryDef(";
2005 if (UO && UO->getID())
2006 OS << UO->getID();
2007 else
2008 OS << LiveOnEntryStr;
2009 OS << ')';
2010}
2011
2012void MemoryPhi::print(raw_ostream &OS) const {
2013 bool First = true;
2014 OS << getID() << " = MemoryPhi(";
2015 for (const auto &Op : operands()) {
2016 BasicBlock *BB = getIncomingBlock(Op);
2017 MemoryAccess *MA = cast<MemoryAccess>(Op);
2018 if (!First)
2019 OS << ',';
2020 else
2021 First = false;
2022
2023 OS << '{';
2024 if (BB->hasName())
2025 OS << BB->getName();
2026 else
2027 BB->printAsOperand(OS, false);
2028 OS << ',';
2029 if (unsigned ID = MA->getID())
2030 OS << ID;
2031 else
2032 OS << LiveOnEntryStr;
2033 OS << '}';
2034 }
2035 OS << ')';
2036}
2037
2038MemoryAccess::~MemoryAccess() {}
2039
2040void MemoryUse::print(raw_ostream &OS) const {
2041 MemoryAccess *UO = getDefiningAccess();
2042 OS << "MemoryUse(";
2043 if (UO && UO->getID())
2044 OS << UO->getID();
2045 else
2046 OS << LiveOnEntryStr;
2047 OS << ')';
2048}
2049
2050void MemoryAccess::dump() const {
2051 print(dbgs());
2052 dbgs() << "\n";
2053}
2054
Chad Rosier232e29e2016-07-06 21:20:47 +00002055char MemorySSAPrinterLegacyPass::ID = 0;
2056
2057MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) {
2058 initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
2059}
2060
2061void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
2062 AU.setPreservesAll();
2063 AU.addRequired<MemorySSAWrapperPass>();
2064 AU.addPreserved<MemorySSAWrapperPass>();
2065}
2066
2067bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) {
2068 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
2069 MSSA.print(dbgs());
2070 if (VerifyMemorySSA)
2071 MSSA.verifyMemorySSA();
2072 return false;
2073}
2074
Geoff Berryb96d3b22016-06-01 21:30:40 +00002075char MemorySSAAnalysis::PassID;
George Burgess IVe1100f52016-02-02 22:46:49 +00002076
Geoff Berry290a13e2016-08-08 18:27:22 +00002077MemorySSAAnalysis::Result
Sean Silva36e0d012016-08-09 00:28:15 +00002078MemorySSAAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
Geoff Berryb96d3b22016-06-01 21:30:40 +00002079 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2080 auto &AA = AM.getResult<AAManager>(F);
Geoff Berry290a13e2016-08-08 18:27:22 +00002081 return MemorySSAAnalysis::Result(make_unique<MemorySSA>(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00002082}
2083
Geoff Berryb96d3b22016-06-01 21:30:40 +00002084PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
2085 FunctionAnalysisManager &AM) {
2086 OS << "MemorySSA for function: " << F.getName() << "\n";
Geoff Berry290a13e2016-08-08 18:27:22 +00002087 AM.getResult<MemorySSAAnalysis>(F).getMSSA().print(OS);
Geoff Berryb96d3b22016-06-01 21:30:40 +00002088
2089 return PreservedAnalyses::all();
George Burgess IVe1100f52016-02-02 22:46:49 +00002090}
2091
Geoff Berryb96d3b22016-06-01 21:30:40 +00002092PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
2093 FunctionAnalysisManager &AM) {
Geoff Berry290a13e2016-08-08 18:27:22 +00002094 AM.getResult<MemorySSAAnalysis>(F).getMSSA().verifyMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00002095
2096 return PreservedAnalyses::all();
2097}
2098
2099char MemorySSAWrapperPass::ID = 0;
2100
2101MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
2102 initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
2103}
2104
2105void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
2106
2107void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00002108 AU.setPreservesAll();
Geoff Berryb96d3b22016-06-01 21:30:40 +00002109 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
2110 AU.addRequiredTransitive<AAResultsWrapperPass>();
George Burgess IVe1100f52016-02-02 22:46:49 +00002111}
2112
Geoff Berryb96d3b22016-06-01 21:30:40 +00002113bool MemorySSAWrapperPass::runOnFunction(Function &F) {
2114 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2115 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2116 MSSA.reset(new MemorySSA(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00002117 return false;
2118}
2119
Geoff Berryb96d3b22016-06-01 21:30:40 +00002120void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); }
George Burgess IVe1100f52016-02-02 22:46:49 +00002121
Geoff Berryb96d3b22016-06-01 21:30:40 +00002122void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00002123 MSSA->print(OS);
2124}
2125
George Burgess IVe1100f52016-02-02 22:46:49 +00002126MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
2127
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002128MemorySSA::CachingWalker::CachingWalker(MemorySSA *M, AliasAnalysis *A,
2129 DominatorTree *D)
Daniel Berlin5c46b942016-07-19 22:49:43 +00002130 : MemorySSAWalker(M), Walker(*M, *A, *D, Cache), AutoResetWalker(true) {}
George Burgess IVe1100f52016-02-02 22:46:49 +00002131
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002132MemorySSA::CachingWalker::~CachingWalker() {}
George Burgess IVe1100f52016-02-02 22:46:49 +00002133
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002134void MemorySSA::CachingWalker::invalidateInfo(MemoryAccess *MA) {
Daniel Berlin83fc77b2016-03-01 18:46:54 +00002135 // TODO: We can do much better cache invalidation with differently stored
2136 // caches. For now, for MemoryUses, we simply remove them
2137 // from the cache, and kill the entire call/non-call cache for everything
2138 // else. The problem is for phis or defs, currently we'd need to follow use
2139 // chains down and invalidate anything below us in the chain that currently
2140 // terminates at this access.
2141
2142 // See if this is a MemoryUse, if so, just remove the cached info. MemoryUse
2143 // is by definition never a barrier, so nothing in the cache could point to
2144 // this use. In that case, we only need invalidate the info for the use
2145 // itself.
2146
2147 if (MemoryUse *MU = dyn_cast<MemoryUse>(MA)) {
George Burgess IV5f308972016-07-19 01:29:15 +00002148 UpwardsMemoryQuery Q(MU->getMemoryInst(), MU);
2149 Cache.remove(MU, Q.StartingLoc, Q.IsCall);
Geoff Berry9fe26e62016-04-22 14:44:10 +00002150 } else {
2151 // 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 +00002152 Cache.clear();
Geoff Berry9fe26e62016-04-22 14:44:10 +00002153 }
2154
Filipe Cabecinhas0da99372016-04-29 15:22:48 +00002155#ifdef EXPENSIVE_CHECKS
Geoff Berry9fe26e62016-04-22 14:44:10 +00002156 verifyRemoved(MA);
2157#endif
Daniel Berlin83fc77b2016-03-01 18:46:54 +00002158}
2159
George Burgess IVe1100f52016-02-02 22:46:49 +00002160/// \brief Walk the use-def chains starting at \p MA and find
2161/// the MemoryAccess that actually clobbers Loc.
2162///
2163/// \returns our clobbering memory access
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002164MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
2165 MemoryAccess *StartingAccess, UpwardsMemoryQuery &Q) {
George Burgess IV5f308972016-07-19 01:29:15 +00002166 MemoryAccess *New = Walker.findClobber(StartingAccess, Q);
2167#ifdef EXPENSIVE_CHECKS
2168 MemoryAccess *NewNoCache =
2169 Walker.findClobber(StartingAccess, Q, /*UseWalkerCache=*/false);
2170 assert(NewNoCache == New && "Cache made us hand back a different result?");
2171#endif
2172 if (AutoResetWalker)
2173 resetClobberWalker();
2174 return New;
George Burgess IVe1100f52016-02-02 22:46:49 +00002175}
2176
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002177MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
2178 MemoryAccess *StartingAccess, MemoryLocation &Loc) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002179 if (isa<MemoryPhi>(StartingAccess))
2180 return StartingAccess;
2181
2182 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
2183 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
2184 return StartingUseOrDef;
2185
2186 Instruction *I = StartingUseOrDef->getMemoryInst();
2187
2188 // Conservatively, fences are always clobbers, so don't perform the walk if we
2189 // hit a fence.
David Majnemera940f362016-07-15 17:19:24 +00002190 if (!ImmutableCallSite(I) && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002191 return StartingUseOrDef;
2192
2193 UpwardsMemoryQuery Q;
2194 Q.OriginalAccess = StartingUseOrDef;
2195 Q.StartingLoc = Loc;
George Burgess IV5f308972016-07-19 01:29:15 +00002196 Q.Inst = I;
George Burgess IVe1100f52016-02-02 22:46:49 +00002197 Q.IsCall = false;
George Burgess IVe1100f52016-02-02 22:46:49 +00002198
George Burgess IV5f308972016-07-19 01:29:15 +00002199 if (auto *CacheResult = Cache.lookup(StartingUseOrDef, Loc, Q.IsCall))
George Burgess IVe1100f52016-02-02 22:46:49 +00002200 return CacheResult;
2201
2202 // Unlike the other function, do not walk to the def of a def, because we are
2203 // handed something we already believe is the clobbering access.
2204 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
2205 ? StartingUseOrDef->getDefiningAccess()
2206 : StartingUseOrDef;
2207
2208 MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00002209 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2210 DEBUG(dbgs() << *StartingUseOrDef << "\n");
2211 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2212 DEBUG(dbgs() << *Clobber << "\n");
2213 return Clobber;
2214}
2215
2216MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002217MemorySSA::CachingWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
2218 auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
2219 // If this is a MemoryPhi, we can't do anything.
2220 if (!StartingAccess)
2221 return MA;
George Burgess IVe1100f52016-02-02 22:46:49 +00002222
George Burgess IV400ae402016-07-20 19:51:34 +00002223 const Instruction *I = StartingAccess->getMemoryInst();
George Burgess IV5f308972016-07-19 01:29:15 +00002224 UpwardsMemoryQuery Q(I, StartingAccess);
David Majnemera940f362016-07-15 17:19:24 +00002225 // We can't sanely do anything with a fences, they conservatively
George Burgess IVe1100f52016-02-02 22:46:49 +00002226 // clobber all memory, and have no locations to get pointers from to
David Majnemera940f362016-07-15 17:19:24 +00002227 // try to disambiguate.
George Burgess IV5f308972016-07-19 01:29:15 +00002228 if (!Q.IsCall && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002229 return StartingAccess;
2230
George Burgess IV5f308972016-07-19 01:29:15 +00002231 if (auto *CacheResult = Cache.lookup(StartingAccess, Q.StartingLoc, Q.IsCall))
George Burgess IVe1100f52016-02-02 22:46:49 +00002232 return CacheResult;
2233
George Burgess IV024f3d22016-08-03 19:57:02 +00002234 if (isUseTriviallyOptimizableToLiveOnEntry(*MSSA->AA, I)) {
2235 MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef();
2236 Cache.insert(StartingAccess, LiveOnEntry, Q.StartingLoc, Q.IsCall);
2237 return LiveOnEntry;
2238 }
2239
George Burgess IVe1100f52016-02-02 22:46:49 +00002240 // Start with the thing we already think clobbers this location
2241 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
2242
2243 // At this point, DefiningAccess may be the live on entry def.
2244 // If it is, we will not get a better result.
2245 if (MSSA->isLiveOnEntryDef(DefiningAccess))
2246 return DefiningAccess;
2247
2248 MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00002249 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2250 DEBUG(dbgs() << *DefiningAccess << "\n");
2251 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2252 DEBUG(dbgs() << *Result << "\n");
2253
2254 return Result;
2255}
2256
Geoff Berry9fe26e62016-04-22 14:44:10 +00002257// Verify that MA doesn't exist in any of the caches.
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002258void MemorySSA::CachingWalker::verifyRemoved(MemoryAccess *MA) {
George Burgess IV5f308972016-07-19 01:29:15 +00002259 assert(!Cache.contains(MA) && "Found removed MemoryAccess in cache.");
Geoff Berry9fe26e62016-04-22 14:44:10 +00002260}
2261
George Burgess IVe1100f52016-02-02 22:46:49 +00002262MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002263DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002264 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
2265 return Use->getDefiningAccess();
2266 return MA;
2267}
2268
2269MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
2270 MemoryAccess *StartingAccess, MemoryLocation &) {
2271 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
2272 return Use->getDefiningAccess();
2273 return StartingAccess;
2274}
George Burgess IV5f308972016-07-19 01:29:15 +00002275} // namespace llvm