blob: e06b60484c5e4b0e5ee923a67fc661898e55bc76 [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;
George Burgess IV5f308972016-07-19 01:29:15 +0000493 Optional<ListIndex> Previous;
494
495 DefPath(const MemoryLocation &Loc, MemoryAccess *First, MemoryAccess *Last,
496 Optional<ListIndex> Previous)
497 : Loc(Loc), First(First), Last(Last), Previous(Previous) {}
498
499 DefPath(const MemoryLocation &Loc, MemoryAccess *Init,
500 Optional<ListIndex> Previous)
501 : DefPath(Loc, Init, Init, Previous) {}
502 };
503
504 const MemorySSA &MSSA;
505 AliasAnalysis &AA;
506 DominatorTree &DT;
507 WalkerCache &WC;
508 UpwardsMemoryQuery *Query;
509 bool UseCache;
510
511 // Phi optimization bookkeeping
512 SmallVector<DefPath, 32> Paths;
513 DenseSet<ConstMemoryAccessPair> VisitedPhis;
514 DenseMap<const BasicBlock *, MemoryAccess *> WalkTargetCache;
515
516 void setUseCache(bool Use) { UseCache = Use; }
517 bool shouldIgnoreCache() const {
518 // UseCache will only be false when we're debugging, or when expensive
519 // checks are enabled. In either case, we don't care deeply about speed.
520 return LLVM_UNLIKELY(!UseCache);
521 }
522
523 void addCacheEntry(const MemoryAccess *What, MemoryAccess *To,
524 const MemoryLocation &Loc) const {
Daniel Berlin5c46b942016-07-19 22:49:43 +0000525// EXPENSIVE_CHECKS because most of these queries are redundant.
George Burgess IV5f308972016-07-19 01:29:15 +0000526#ifdef EXPENSIVE_CHECKS
527 assert(MSSA.dominates(To, What));
528#endif
529 if (shouldIgnoreCache())
530 return;
531 WC.insert(What, To, Loc, Query->IsCall);
532 }
533
534 MemoryAccess *lookupCache(const MemoryAccess *MA, const MemoryLocation &Loc) {
535 return shouldIgnoreCache() ? nullptr : WC.lookup(MA, Loc, Query->IsCall);
536 }
537
538 void cacheDefPath(const DefPath &DN, MemoryAccess *Target) const {
539 if (shouldIgnoreCache())
540 return;
541
542 for (MemoryAccess *MA : def_chain(DN.First, DN.Last))
543 addCacheEntry(MA, Target, DN.Loc);
544
545 // DefPaths only express the path we walked. So, DN.Last could either be a
546 // thing we want to cache, or not.
547 if (DN.Last != Target)
548 addCacheEntry(DN.Last, Target, DN.Loc);
549 }
550
551 /// Find the nearest def or phi that `From` can legally be optimized to.
552 ///
553 /// FIXME: Deduplicate this with MSSA::findDominatingDef. Ideally, MSSA should
554 /// keep track of this information for us, and allow us O(1) lookups of this
555 /// info.
556 MemoryAccess *getWalkTarget(const MemoryPhi *From) {
George Burgess IV5f308972016-07-19 01:29:15 +0000557 assert(From->getNumOperands() && "Phi with no operands?");
558
559 BasicBlock *BB = From->getBlock();
560 auto At = WalkTargetCache.find(BB);
561 if (At != WalkTargetCache.end())
562 return At->second;
563
564 SmallVector<const BasicBlock *, 8> ToCache;
565 ToCache.push_back(BB);
566
567 MemoryAccess *Result = MSSA.getLiveOnEntryDef();
568 DomTreeNode *Node = DT.getNode(BB);
569 while ((Node = Node->getIDom())) {
570 auto At = WalkTargetCache.find(BB);
571 if (At != WalkTargetCache.end()) {
572 Result = At->second;
573 break;
574 }
575
576 auto *Accesses = MSSA.getBlockAccesses(Node->getBlock());
577 if (Accesses) {
578 auto Iter = find_if(reverse(*Accesses), [](const MemoryAccess &MA) {
579 return !isa<MemoryUse>(MA);
580 });
581 if (Iter != Accesses->rend()) {
582 Result = const_cast<MemoryAccess *>(&*Iter);
583 break;
584 }
585 }
586
587 ToCache.push_back(Node->getBlock());
588 }
589
590 for (const BasicBlock *BB : ToCache)
591 WalkTargetCache.insert({BB, Result});
592 return Result;
593 }
594
595 /// Result of calling walkToPhiOrClobber.
596 struct UpwardsWalkResult {
597 /// The "Result" of the walk. Either a clobber, the last thing we walked, or
598 /// both.
599 MemoryAccess *Result;
600 bool IsKnownClobber;
601 bool FromCache;
602 };
603
604 /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last.
605 /// This will update Desc.Last as it walks. It will (optionally) also stop at
606 /// StopAt.
607 ///
608 /// This does not test for whether StopAt is a clobber
609 UpwardsWalkResult walkToPhiOrClobber(DefPath &Desc,
610 MemoryAccess *StopAt = nullptr) {
611 assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");
612
613 for (MemoryAccess *Current : def_chain(Desc.Last)) {
614 Desc.Last = Current;
615 if (Current == StopAt)
616 return {Current, false, false};
617
618 if (auto *MD = dyn_cast<MemoryDef>(Current))
619 if (MSSA.isLiveOnEntryDef(MD) ||
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000620 instructionClobbersQuery(MD, Desc.Loc, Query->Inst, AA))
George Burgess IV5f308972016-07-19 01:29:15 +0000621 return {MD, true, false};
622
623 // Cache checks must be done last, because if Current is a clobber, the
624 // cache will contain the clobber for Current.
625 if (MemoryAccess *MA = lookupCache(Current, Desc.Loc))
626 return {MA, true, true};
627 }
628
629 assert(isa<MemoryPhi>(Desc.Last) &&
630 "Ended at a non-clobber that's not a phi?");
631 return {Desc.Last, false, false};
632 }
633
634 void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches,
635 ListIndex PriorNode) {
636 auto UpwardDefs = make_range(upward_defs_begin({Phi, Paths[PriorNode].Loc}),
637 upward_defs_end());
638 for (const MemoryAccessPair &P : UpwardDefs) {
639 PausedSearches.push_back(Paths.size());
640 Paths.emplace_back(P.second, P.first, PriorNode);
641 }
642 }
643
644 /// Represents a search that terminated after finding a clobber. This clobber
645 /// may or may not be present in the path of defs from LastNode..SearchStart,
646 /// since it may have been retrieved from cache.
647 struct TerminatedPath {
648 MemoryAccess *Clobber;
649 ListIndex LastNode;
650 };
651
652 /// Get an access that keeps us from optimizing to the given phi.
653 ///
654 /// PausedSearches is an array of indices into the Paths array. Its incoming
655 /// value is the indices of searches that stopped at the last phi optimization
656 /// target. It's left in an unspecified state.
657 ///
658 /// If this returns None, NewPaused is a vector of searches that terminated
659 /// at StopWhere. Otherwise, NewPaused is left in an unspecified state.
George Burgess IV14633b52016-08-03 01:22:19 +0000660 Optional<TerminatedPath>
George Burgess IV5f308972016-07-19 01:29:15 +0000661 getBlockingAccess(MemoryAccess *StopWhere,
662 SmallVectorImpl<ListIndex> &PausedSearches,
663 SmallVectorImpl<ListIndex> &NewPaused,
664 SmallVectorImpl<TerminatedPath> &Terminated) {
665 assert(!PausedSearches.empty() && "No searches to continue?");
666
667 // BFS vs DFS really doesn't make a difference here, so just do a DFS with
668 // PausedSearches as our stack.
669 while (!PausedSearches.empty()) {
670 ListIndex PathIndex = PausedSearches.pop_back_val();
671 DefPath &Node = Paths[PathIndex];
672
673 // If we've already visited this path with this MemoryLocation, we don't
674 // need to do so again.
675 //
676 // NOTE: That we just drop these paths on the ground makes caching
677 // behavior sporadic. e.g. given a diamond:
678 // A
679 // B C
680 // D
681 //
682 // ...If we walk D, B, A, C, we'll only cache the result of phi
683 // optimization for A, B, and D; C will be skipped because it dies here.
684 // This arguably isn't the worst thing ever, since:
685 // - We generally query things in a top-down order, so if we got below D
686 // without needing cache entries for {C, MemLoc}, then chances are
687 // that those cache entries would end up ultimately unused.
688 // - We still cache things for A, so C only needs to walk up a bit.
689 // If this behavior becomes problematic, we can fix without a ton of extra
690 // work.
691 if (!VisitedPhis.insert({Node.Last, Node.Loc}).second)
692 continue;
693
694 UpwardsWalkResult Res = walkToPhiOrClobber(Node, /*StopAt=*/StopWhere);
695 if (Res.IsKnownClobber) {
696 assert(Res.Result != StopWhere || Res.FromCache);
697 // If this wasn't a cache hit, we hit a clobber when walking. That's a
698 // failure.
George Burgess IV14633b52016-08-03 01:22:19 +0000699 TerminatedPath Term{Res.Result, PathIndex};
George Burgess IV5f308972016-07-19 01:29:15 +0000700 if (!Res.FromCache || !MSSA.dominates(Res.Result, StopWhere))
George Burgess IV14633b52016-08-03 01:22:19 +0000701 return Term;
George Burgess IV5f308972016-07-19 01:29:15 +0000702
703 // Otherwise, it's a valid thing to potentially optimize to.
George Burgess IV14633b52016-08-03 01:22:19 +0000704 Terminated.push_back(Term);
George Burgess IV5f308972016-07-19 01:29:15 +0000705 continue;
706 }
707
708 if (Res.Result == StopWhere) {
709 // We've hit our target. Save this path off for if we want to continue
710 // walking.
711 NewPaused.push_back(PathIndex);
712 continue;
713 }
714
715 assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");
716 addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
717 }
718
719 return None;
720 }
721
722 template <typename T, typename Walker>
723 struct generic_def_path_iterator
724 : public iterator_facade_base<generic_def_path_iterator<T, Walker>,
725 std::forward_iterator_tag, T *> {
726 generic_def_path_iterator() : W(nullptr), N(None) {}
727 generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}
728
729 T &operator*() const { return curNode(); }
730
731 generic_def_path_iterator &operator++() {
732 N = curNode().Previous;
733 return *this;
734 }
735
736 bool operator==(const generic_def_path_iterator &O) const {
737 if (N.hasValue() != O.N.hasValue())
738 return false;
739 return !N.hasValue() || *N == *O.N;
740 }
741
742 private:
743 T &curNode() const { return W->Paths[*N]; }
744
745 Walker *W;
746 Optional<ListIndex> N;
747 };
748
749 using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
750 using const_def_path_iterator =
751 generic_def_path_iterator<const DefPath, const ClobberWalker>;
752
753 iterator_range<def_path_iterator> def_path(ListIndex From) {
754 return make_range(def_path_iterator(this, From), def_path_iterator());
755 }
756
757 iterator_range<const_def_path_iterator> const_def_path(ListIndex From) const {
758 return make_range(const_def_path_iterator(this, From),
759 const_def_path_iterator());
760 }
761
762 struct OptznResult {
763 /// The path that contains our result.
764 TerminatedPath PrimaryClobber;
765 /// The paths that we can legally cache back from, but that aren't
766 /// necessarily the result of the Phi optimization.
767 SmallVector<TerminatedPath, 4> OtherClobbers;
768 };
769
770 ListIndex defPathIndex(const DefPath &N) const {
771 // The assert looks nicer if we don't need to do &N
772 const DefPath *NP = &N;
773 assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
774 "Out of bounds DefPath!");
775 return NP - &Paths.front();
776 }
777
778 /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths
779 /// that act as legal clobbers. Note that this won't return *all* clobbers.
780 ///
781 /// Phi optimization algorithm tl;dr:
782 /// - Find the earliest def/phi, A, we can optimize to
783 /// - Find if all paths from the starting memory access ultimately reach A
784 /// - If not, optimization isn't possible.
785 /// - Otherwise, walk from A to another clobber or phi, A'.
786 /// - If A' is a def, we're done.
787 /// - If A' is a phi, try to optimize it.
788 ///
789 /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path
790 /// terminates when a MemoryAccess that clobbers said MemoryLocation is found.
791 OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start,
792 const MemoryLocation &Loc) {
793 assert(Paths.empty() && VisitedPhis.empty() &&
794 "Reset the optimization state.");
795
796 Paths.emplace_back(Loc, Start, Phi, None);
797 // Stores how many "valid" optimization nodes we had prior to calling
798 // addSearches/getBlockingAccess. Necessary for caching if we had a blocker.
799 auto PriorPathsSize = Paths.size();
800
801 SmallVector<ListIndex, 16> PausedSearches;
802 SmallVector<ListIndex, 8> NewPaused;
803 SmallVector<TerminatedPath, 4> TerminatedPaths;
804
805 addSearches(Phi, PausedSearches, 0);
806
807 // Moves the TerminatedPath with the "most dominated" Clobber to the end of
808 // Paths.
809 auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
810 assert(!Paths.empty() && "Need a path to move");
George Burgess IV5f308972016-07-19 01:29:15 +0000811 auto Dom = Paths.begin();
812 for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I)
813 if (!MSSA.dominates(I->Clobber, Dom->Clobber))
814 Dom = I;
815 auto Last = Paths.end() - 1;
816 if (Last != Dom)
817 std::iter_swap(Last, Dom);
818 };
819
820 MemoryPhi *Current = Phi;
821 while (1) {
822 assert(!MSSA.isLiveOnEntryDef(Current) &&
823 "liveOnEntry wasn't treated as a clobber?");
824
825 MemoryAccess *Target = getWalkTarget(Current);
826 // If a TerminatedPath doesn't dominate Target, then it wasn't a legal
827 // optimization for the prior phi.
828 assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {
829 return MSSA.dominates(P.Clobber, Target);
830 }));
831
832 // FIXME: This is broken, because the Blocker may be reported to be
833 // liveOnEntry, and we'll happily wait for that to disappear (read: never)
George Burgess IV7f414b92016-08-22 23:40:01 +0000834 // For the moment, this is fine, since we do nothing with blocker info.
George Burgess IV14633b52016-08-03 01:22:19 +0000835 if (Optional<TerminatedPath> Blocker = getBlockingAccess(
George Burgess IV5f308972016-07-19 01:29:15 +0000836 Target, PausedSearches, NewPaused, TerminatedPaths)) {
George Burgess IV5f308972016-07-19 01:29:15 +0000837 // Cache our work on the blocking node, since we know that's correct.
George Burgess IV14633b52016-08-03 01:22:19 +0000838 cacheDefPath(Paths[Blocker->LastNode], Blocker->Clobber);
George Burgess IV5f308972016-07-19 01:29:15 +0000839
840 // Find the node we started at. We can't search based on N->Last, since
841 // we may have gone around a loop with a different MemoryLocation.
George Burgess IV14633b52016-08-03 01:22:19 +0000842 auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) {
George Burgess IV5f308972016-07-19 01:29:15 +0000843 return defPathIndex(N) < PriorPathsSize;
844 });
845 assert(Iter != def_path_iterator());
846
847 DefPath &CurNode = *Iter;
848 assert(CurNode.Last == Current);
George Burgess IV5f308972016-07-19 01:29:15 +0000849
850 // Two things:
851 // A. We can't reliably cache all of NewPaused back. Consider a case
852 // where we have two paths in NewPaused; one of which can't optimize
853 // above this phi, whereas the other can. If we cache the second path
854 // back, we'll end up with suboptimal cache entries. We can handle
855 // cases like this a bit better when we either try to find all
856 // clobbers that block phi optimization, or when our cache starts
857 // supporting unfinished searches.
858 // B. We can't reliably cache TerminatedPaths back here without doing
859 // extra checks; consider a case like:
860 // T
861 // / \
862 // D C
863 // \ /
864 // S
865 // Where T is our target, C is a node with a clobber on it, D is a
866 // diamond (with a clobber *only* on the left or right node, N), and
867 // S is our start. Say we walk to D, through the node opposite N
868 // (read: ignoring the clobber), and see a cache entry in the top
869 // node of D. That cache entry gets put into TerminatedPaths. We then
870 // walk up to C (N is later in our worklist), find the clobber, and
871 // quit. If we append TerminatedPaths to OtherClobbers, we'll cache
872 // the bottom part of D to the cached clobber, ignoring the clobber
873 // in N. Again, this problem goes away if we start tracking all
874 // blockers for a given phi optimization.
875 TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
876 return {Result, {}};
877 }
878
879 // If there's nothing left to search, then all paths led to valid clobbers
880 // that we got from our cache; pick the nearest to the start, and allow
881 // the rest to be cached back.
882 if (NewPaused.empty()) {
883 MoveDominatedPathToEnd(TerminatedPaths);
884 TerminatedPath Result = TerminatedPaths.pop_back_val();
885 return {Result, std::move(TerminatedPaths)};
886 }
887
888 MemoryAccess *DefChainEnd = nullptr;
889 SmallVector<TerminatedPath, 4> Clobbers;
890 for (ListIndex Paused : NewPaused) {
891 UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
892 if (WR.IsKnownClobber)
893 Clobbers.push_back({WR.Result, Paused});
894 else
895 // Micro-opt: If we hit the end of the chain, save it.
896 DefChainEnd = WR.Result;
897 }
898
899 if (!TerminatedPaths.empty()) {
900 // If we couldn't find the dominating phi/liveOnEntry in the above loop,
901 // do it now.
902 if (!DefChainEnd)
903 for (MemoryAccess *MA : def_chain(Target))
904 DefChainEnd = MA;
905
906 // If any of the terminated paths don't dominate the phi we'll try to
907 // optimize, we need to figure out what they are and quit.
908 const BasicBlock *ChainBB = DefChainEnd->getBlock();
909 for (const TerminatedPath &TP : TerminatedPaths) {
910 // Because we know that DefChainEnd is as "high" as we can go, we
911 // don't need local dominance checks; BB dominance is sufficient.
912 if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
913 Clobbers.push_back(TP);
914 }
915 }
916
917 // If we have clobbers in the def chain, find the one closest to Current
918 // and quit.
919 if (!Clobbers.empty()) {
920 MoveDominatedPathToEnd(Clobbers);
921 TerminatedPath Result = Clobbers.pop_back_val();
922 return {Result, std::move(Clobbers)};
923 }
924
925 assert(all_of(NewPaused,
926 [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
927
928 // Because liveOnEntry is a clobber, this must be a phi.
929 auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
930
931 PriorPathsSize = Paths.size();
932 PausedSearches.clear();
933 for (ListIndex I : NewPaused)
934 addSearches(DefChainPhi, PausedSearches, I);
935 NewPaused.clear();
936
937 Current = DefChainPhi;
938 }
939 }
940
941 /// Caches everything in an OptznResult.
942 void cacheOptResult(const OptznResult &R) {
943 if (R.OtherClobbers.empty()) {
944 // If we're not going to be caching OtherClobbers, don't bother with
945 // marking visited/etc.
946 for (const DefPath &N : const_def_path(R.PrimaryClobber.LastNode))
947 cacheDefPath(N, R.PrimaryClobber.Clobber);
948 return;
949 }
950
951 // PrimaryClobber is our answer. If we can cache anything back, we need to
952 // stop caching when we visit PrimaryClobber.
953 SmallBitVector Visited(Paths.size());
954 for (const DefPath &N : const_def_path(R.PrimaryClobber.LastNode)) {
955 Visited[defPathIndex(N)] = true;
956 cacheDefPath(N, R.PrimaryClobber.Clobber);
957 }
958
959 for (const TerminatedPath &P : R.OtherClobbers) {
960 for (const DefPath &N : const_def_path(P.LastNode)) {
961 ListIndex NIndex = defPathIndex(N);
962 if (Visited[NIndex])
963 break;
964 Visited[NIndex] = true;
965 cacheDefPath(N, P.Clobber);
966 }
967 }
968 }
969
970 void verifyOptResult(const OptznResult &R) const {
971 assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
972 return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
973 }));
974 }
975
976 void resetPhiOptznState() {
977 Paths.clear();
978 VisitedPhis.clear();
979 }
980
981public:
982 ClobberWalker(const MemorySSA &MSSA, AliasAnalysis &AA, DominatorTree &DT,
983 WalkerCache &WC)
984 : MSSA(MSSA), AA(AA), DT(DT), WC(WC), UseCache(true) {}
985
986 void reset() { WalkTargetCache.clear(); }
987
988 /// Finds the nearest clobber for the given query, optimizing phis if
989 /// possible.
990 MemoryAccess *findClobber(MemoryAccess *Start, UpwardsMemoryQuery &Q,
991 bool UseWalkerCache = true) {
992 setUseCache(UseWalkerCache);
993 Query = &Q;
994
995 MemoryAccess *Current = Start;
996 // This walker pretends uses don't exist. If we're handed one, silently grab
997 // its def. (This has the nice side-effect of ensuring we never cache uses)
998 if (auto *MU = dyn_cast<MemoryUse>(Start))
999 Current = MU->getDefiningAccess();
1000
1001 DefPath FirstDesc(Q.StartingLoc, Current, Current, None);
1002 // Fast path for the overly-common case (no crazy phi optimization
1003 // necessary)
1004 UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
George Burgess IV93ea19b2016-07-24 07:03:49 +00001005 MemoryAccess *Result;
George Burgess IV5f308972016-07-19 01:29:15 +00001006 if (WalkResult.IsKnownClobber) {
1007 cacheDefPath(FirstDesc, WalkResult.Result);
George Burgess IV93ea19b2016-07-24 07:03:49 +00001008 Result = WalkResult.Result;
1009 } else {
1010 OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
1011 Current, Q.StartingLoc);
1012 verifyOptResult(OptRes);
1013 cacheOptResult(OptRes);
1014 resetPhiOptznState();
1015 Result = OptRes.PrimaryClobber.Clobber;
George Burgess IV5f308972016-07-19 01:29:15 +00001016 }
1017
George Burgess IV5f308972016-07-19 01:29:15 +00001018#ifdef EXPENSIVE_CHECKS
George Burgess IV93ea19b2016-07-24 07:03:49 +00001019 checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, AA);
George Burgess IV5f308972016-07-19 01:29:15 +00001020#endif
George Burgess IV93ea19b2016-07-24 07:03:49 +00001021 return Result;
George Burgess IV5f308972016-07-19 01:29:15 +00001022 }
Geoff Berrycdf53332016-08-08 17:52:01 +00001023
1024 void verify(const MemorySSA *MSSA) { assert(MSSA == &this->MSSA); }
George Burgess IV5f308972016-07-19 01:29:15 +00001025};
1026
1027struct RenamePassData {
1028 DomTreeNode *DTN;
1029 DomTreeNode::const_iterator ChildIt;
1030 MemoryAccess *IncomingVal;
1031
1032 RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
1033 MemoryAccess *M)
1034 : DTN(D), ChildIt(It), IncomingVal(M) {}
1035 void swap(RenamePassData &RHS) {
1036 std::swap(DTN, RHS.DTN);
1037 std::swap(ChildIt, RHS.ChildIt);
1038 std::swap(IncomingVal, RHS.IncomingVal);
1039 }
1040};
1041} // anonymous namespace
1042
1043namespace llvm {
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001044/// \brief A MemorySSAWalker that does AA walks and caching of lookups to
1045/// disambiguate accesses.
1046///
1047/// FIXME: The current implementation of this can take quadratic space in rare
1048/// cases. This can be fixed, but it is something to note until it is fixed.
1049///
1050/// In order to trigger this behavior, you need to store to N distinct locations
1051/// (that AA can prove don't alias), perform M stores to other memory
1052/// locations that AA can prove don't alias any of the initial N locations, and
1053/// then load from all of the N locations. In this case, we insert M cache
1054/// entries for each of the N loads.
1055///
1056/// For example:
1057/// define i32 @foo() {
1058/// %a = alloca i32, align 4
1059/// %b = alloca i32, align 4
1060/// store i32 0, i32* %a, align 4
1061/// store i32 0, i32* %b, align 4
1062///
1063/// ; Insert M stores to other memory that doesn't alias %a or %b here
1064///
1065/// %c = load i32, i32* %a, align 4 ; Caches M entries in
1066/// ; CachedUpwardsClobberingAccess for the
1067/// ; MemoryLocation %a
1068/// %d = load i32, i32* %b, align 4 ; Caches M entries in
1069/// ; CachedUpwardsClobberingAccess for the
1070/// ; MemoryLocation %b
1071///
1072/// ; For completeness' sake, loading %a or %b again would not cache *another*
1073/// ; M entries.
1074/// %r = add i32 %c, %d
1075/// ret i32 %r
1076/// }
1077class MemorySSA::CachingWalker final : public MemorySSAWalker {
George Burgess IV5f308972016-07-19 01:29:15 +00001078 WalkerCache Cache;
1079 ClobberWalker Walker;
1080 bool AutoResetWalker;
1081
1082 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *, UpwardsMemoryQuery &);
1083 void verifyRemoved(MemoryAccess *);
1084
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001085public:
1086 CachingWalker(MemorySSA *, AliasAnalysis *, DominatorTree *);
1087 ~CachingWalker() override;
1088
George Burgess IV400ae402016-07-20 19:51:34 +00001089 using MemorySSAWalker::getClobberingMemoryAccess;
1090 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) override;
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001091 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
1092 MemoryLocation &) override;
1093 void invalidateInfo(MemoryAccess *) override;
1094
George Burgess IV5f308972016-07-19 01:29:15 +00001095 /// Whether we call resetClobberWalker() after each time we *actually* walk to
1096 /// answer a clobber query.
1097 void setAutoResetWalker(bool AutoReset) { AutoResetWalker = AutoReset; }
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001098
George Burgess IV5f308972016-07-19 01:29:15 +00001099 /// Drop the walker's persistent data structures. At the moment, this means
1100 /// "drop the walker's cache of BasicBlocks ->
1101 /// earliest-MemoryAccess-we-can-optimize-to". This is necessary if we're
1102 /// going to have DT updates, if we remove MemoryAccesses, etc.
1103 void resetClobberWalker() { Walker.reset(); }
Geoff Berrycdf53332016-08-08 17:52:01 +00001104
1105 void verify(const MemorySSA *MSSA) override {
1106 MemorySSAWalker::verify(MSSA);
1107 Walker.verify(MSSA);
1108 }
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001109};
George Burgess IVe1100f52016-02-02 22:46:49 +00001110
George Burgess IVe1100f52016-02-02 22:46:49 +00001111/// \brief Rename a single basic block into MemorySSA form.
1112/// Uses the standard SSA renaming algorithm.
1113/// \returns The new incoming value.
1114MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB,
1115 MemoryAccess *IncomingVal) {
1116 auto It = PerBlockAccesses.find(BB);
1117 // Skip most processing if the list is empty.
1118 if (It != PerBlockAccesses.end()) {
Daniel Berlinada263d2016-06-20 20:21:33 +00001119 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001120 for (MemoryAccess &L : *Accesses) {
Daniel Berlin868381b2016-08-22 19:14:16 +00001121 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&L)) {
1122 if (MUD->getDefiningAccess() == nullptr)
1123 MUD->setDefiningAccess(IncomingVal);
1124 if (isa<MemoryDef>(&L))
1125 IncomingVal = &L;
1126 } else {
George Burgess IVe1100f52016-02-02 22:46:49 +00001127 IncomingVal = &L;
George Burgess IVe1100f52016-02-02 22:46:49 +00001128 }
1129 }
1130 }
1131
1132 // Pass through values to our successors
1133 for (const BasicBlock *S : successors(BB)) {
1134 auto It = PerBlockAccesses.find(S);
1135 // Rename the phi nodes in our successor block
1136 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1137 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +00001138 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001139 auto *Phi = cast<MemoryPhi>(&Accesses->front());
George Burgess IVe1100f52016-02-02 22:46:49 +00001140 Phi->addIncoming(IncomingVal, BB);
1141 }
1142
1143 return IncomingVal;
1144}
1145
1146/// \brief This is the standard SSA renaming algorithm.
1147///
1148/// We walk the dominator tree in preorder, renaming accesses, and then filling
1149/// in phi nodes in our successors.
1150void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
1151 SmallPtrSet<BasicBlock *, 16> &Visited) {
1152 SmallVector<RenamePassData, 32> WorkStack;
1153 IncomingVal = renameBlock(Root->getBlock(), IncomingVal);
1154 WorkStack.push_back({Root, Root->begin(), IncomingVal});
1155 Visited.insert(Root->getBlock());
1156
1157 while (!WorkStack.empty()) {
1158 DomTreeNode *Node = WorkStack.back().DTN;
1159 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
1160 IncomingVal = WorkStack.back().IncomingVal;
1161
1162 if (ChildIt == Node->end()) {
1163 WorkStack.pop_back();
1164 } else {
1165 DomTreeNode *Child = *ChildIt;
1166 ++WorkStack.back().ChildIt;
1167 BasicBlock *BB = Child->getBlock();
1168 Visited.insert(BB);
1169 IncomingVal = renameBlock(BB, IncomingVal);
1170 WorkStack.push_back({Child, Child->begin(), IncomingVal});
1171 }
1172 }
1173}
1174
1175/// \brief Compute dominator levels, used by the phi insertion algorithm above.
1176void MemorySSA::computeDomLevels(DenseMap<DomTreeNode *, unsigned> &DomLevels) {
1177 for (auto DFI = df_begin(DT->getRootNode()), DFE = df_end(DT->getRootNode());
1178 DFI != DFE; ++DFI)
1179 DomLevels[*DFI] = DFI.getPathLength() - 1;
1180}
1181
George Burgess IVa362b092016-07-06 00:28:43 +00001182/// \brief This handles unreachable block accesses by deleting phi nodes in
George Burgess IVe1100f52016-02-02 22:46:49 +00001183/// unreachable blocks, and marking all other unreachable MemoryAccess's as
1184/// being uses of the live on entry definition.
1185void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
1186 assert(!DT->isReachableFromEntry(BB) &&
1187 "Reachable block found while handling unreachable blocks");
1188
Daniel Berlinfc7e6512016-07-06 05:32:05 +00001189 // Make sure phi nodes in our reachable successors end up with a
1190 // LiveOnEntryDef for our incoming edge, even though our block is forward
1191 // unreachable. We could just disconnect these blocks from the CFG fully,
1192 // but we do not right now.
1193 for (const BasicBlock *S : successors(BB)) {
1194 if (!DT->isReachableFromEntry(S))
1195 continue;
1196 auto It = PerBlockAccesses.find(S);
1197 // Rename the phi nodes in our successor block
1198 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1199 continue;
1200 AccessList *Accesses = It->second.get();
1201 auto *Phi = cast<MemoryPhi>(&Accesses->front());
1202 Phi->addIncoming(LiveOnEntryDef.get(), BB);
1203 }
1204
George Burgess IVe1100f52016-02-02 22:46:49 +00001205 auto It = PerBlockAccesses.find(BB);
1206 if (It == PerBlockAccesses.end())
1207 return;
1208
1209 auto &Accesses = It->second;
1210 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1211 auto Next = std::next(AI);
1212 // If we have a phi, just remove it. We are going to replace all
1213 // users with live on entry.
1214 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1215 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1216 else
1217 Accesses->erase(AI);
1218 AI = Next;
1219 }
1220}
1221
Geoff Berryb96d3b22016-06-01 21:30:40 +00001222MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
1223 : AA(AA), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
1224 NextID(0) {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001225 buildMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001226}
1227
George Burgess IVe1100f52016-02-02 22:46:49 +00001228MemorySSA::~MemorySSA() {
1229 // Drop all our references
1230 for (const auto &Pair : PerBlockAccesses)
1231 for (MemoryAccess &MA : *Pair.second)
1232 MA.dropAllReferences();
1233}
1234
Daniel Berlin14300262016-06-21 18:39:20 +00001235MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001236 auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
1237
1238 if (Res.second)
Daniel Berlinada263d2016-06-20 20:21:33 +00001239 Res.first->second = make_unique<AccessList>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001240 return Res.first->second.get();
1241}
1242
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001243/// This class is a batch walker of all MemoryUse's in the program, and points
1244/// their defining access at the thing that actually clobbers them. Because it
1245/// is a batch walker that touches everything, it does not operate like the
1246/// other walkers. This walker is basically performing a top-down SSA renaming
1247/// pass, where the version stack is used as the cache. This enables it to be
1248/// significantly more time and memory efficient than using the regular walker,
1249/// which is walking bottom-up.
1250class MemorySSA::OptimizeUses {
1251public:
1252 OptimizeUses(MemorySSA *MSSA, MemorySSAWalker *Walker, AliasAnalysis *AA,
1253 DominatorTree *DT)
1254 : MSSA(MSSA), Walker(Walker), AA(AA), DT(DT) {
1255 Walker = MSSA->getWalker();
1256 }
1257
1258 void optimizeUses();
1259
1260private:
1261 /// This represents where a given memorylocation is in the stack.
1262 struct MemlocStackInfo {
1263 // This essentially is keeping track of versions of the stack. Whenever
1264 // the stack changes due to pushes or pops, these versions increase.
1265 unsigned long StackEpoch;
1266 unsigned long PopEpoch;
1267 // This is the lower bound of places on the stack to check. It is equal to
1268 // the place the last stack walk ended.
1269 // Note: Correctness depends on this being initialized to 0, which densemap
1270 // does
1271 unsigned long LowerBound;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001272 const BasicBlock *LowerBoundBlock;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001273 // This is where the last walk for this memory location ended.
1274 unsigned long LastKill;
1275 bool LastKillValid;
1276 };
1277 void optimizeUsesInBlock(const BasicBlock *, unsigned long &, unsigned long &,
1278 SmallVectorImpl<MemoryAccess *> &,
1279 DenseMap<MemoryLocOrCall, MemlocStackInfo> &);
1280 MemorySSA *MSSA;
1281 MemorySSAWalker *Walker;
1282 AliasAnalysis *AA;
1283 DominatorTree *DT;
1284};
1285
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001286/// Optimize the uses in a given block This is basically the SSA renaming
1287/// algorithm, with one caveat: We are able to use a single stack for all
1288/// MemoryUses. This is because the set of *possible* reaching MemoryDefs is
1289/// the same for every MemoryUse. The *actual* clobbering MemoryDef is just
1290/// going to be some position in that stack of possible ones.
1291///
1292/// We track the stack positions that each MemoryLocation needs
1293/// to check, and last ended at. This is because we only want to check the
1294/// things that changed since last time. The same MemoryLocation should
1295/// get clobbered by the same store (getModRefInfo does not use invariantness or
1296/// things like this, and if they start, we can modify MemoryLocOrCall to
1297/// include relevant data)
1298void MemorySSA::OptimizeUses::optimizeUsesInBlock(
1299 const BasicBlock *BB, unsigned long &StackEpoch, unsigned long &PopEpoch,
1300 SmallVectorImpl<MemoryAccess *> &VersionStack,
1301 DenseMap<MemoryLocOrCall, MemlocStackInfo> &LocStackInfo) {
1302
1303 /// If no accesses, nothing to do.
1304 MemorySSA::AccessList *Accesses = MSSA->getWritableBlockAccesses(BB);
1305 if (Accesses == nullptr)
1306 return;
1307
1308 // Pop everything that doesn't dominate the current block off the stack,
1309 // increment the PopEpoch to account for this.
1310 while (!VersionStack.empty()) {
1311 BasicBlock *BackBlock = VersionStack.back()->getBlock();
1312 if (DT->dominates(BackBlock, BB))
1313 break;
1314 while (VersionStack.back()->getBlock() == BackBlock)
1315 VersionStack.pop_back();
1316 ++PopEpoch;
1317 }
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001318 for (MemoryAccess &MA : *Accesses) {
1319 auto *MU = dyn_cast<MemoryUse>(&MA);
1320 if (!MU) {
1321 VersionStack.push_back(&MA);
1322 ++StackEpoch;
1323 continue;
1324 }
1325
George Burgess IV024f3d22016-08-03 19:57:02 +00001326 if (isUseTriviallyOptimizableToLiveOnEntry(*AA, MU->getMemoryInst())) {
1327 MU->setDefiningAccess(MSSA->getLiveOnEntryDef());
1328 continue;
1329 }
1330
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001331 MemoryLocOrCall UseMLOC(MU);
1332 auto &LocInfo = LocStackInfo[UseMLOC];
Daniel Berlin26fcea92016-08-02 20:02:21 +00001333 // If the pop epoch changed, it means we've removed stuff from top of
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001334 // stack due to changing blocks. We may have to reset the lower bound or
1335 // last kill info.
1336 if (LocInfo.PopEpoch != PopEpoch) {
1337 LocInfo.PopEpoch = PopEpoch;
1338 LocInfo.StackEpoch = StackEpoch;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001339 // If the lower bound was in something that no longer dominates us, we
1340 // have to reset it.
1341 // We can't simply track stack size, because the stack may have had
1342 // pushes/pops in the meantime.
1343 // XXX: This is non-optimal, but only is slower cases with heavily
1344 // branching dominator trees. To get the optimal number of queries would
1345 // be to make lowerbound and lastkill a per-loc stack, and pop it until
1346 // the top of that stack dominates us. This does not seem worth it ATM.
1347 // A much cheaper optimization would be to always explore the deepest
1348 // branch of the dominator tree first. This will guarantee this resets on
1349 // the smallest set of blocks.
1350 if (LocInfo.LowerBoundBlock && LocInfo.LowerBoundBlock != BB &&
Daniel Berlin1e98c042016-09-26 17:22:54 +00001351 !DT->dominates(LocInfo.LowerBoundBlock, BB)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001352 // Reset the lower bound of things to check.
1353 // TODO: Some day we should be able to reset to last kill, rather than
1354 // 0.
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001355 LocInfo.LowerBound = 0;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001356 LocInfo.LowerBoundBlock = VersionStack[0]->getBlock();
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001357 LocInfo.LastKillValid = false;
1358 }
1359 } else if (LocInfo.StackEpoch != StackEpoch) {
1360 // If all that has changed is the StackEpoch, we only have to check the
1361 // new things on the stack, because we've checked everything before. In
1362 // this case, the lower bound of things to check remains the same.
1363 LocInfo.PopEpoch = PopEpoch;
1364 LocInfo.StackEpoch = StackEpoch;
1365 }
1366 if (!LocInfo.LastKillValid) {
1367 LocInfo.LastKill = VersionStack.size() - 1;
1368 LocInfo.LastKillValid = true;
1369 }
1370
1371 // At this point, we should have corrected last kill and LowerBound to be
1372 // in bounds.
1373 assert(LocInfo.LowerBound < VersionStack.size() &&
1374 "Lower bound out of range");
1375 assert(LocInfo.LastKill < VersionStack.size() &&
1376 "Last kill info out of range");
1377 // In any case, the new upper bound is the top of the stack.
1378 unsigned long UpperBound = VersionStack.size() - 1;
1379
1380 if (UpperBound - LocInfo.LowerBound > MaxCheckLimit) {
Daniel Berlin26fcea92016-08-02 20:02:21 +00001381 DEBUG(dbgs() << "MemorySSA skipping optimization of " << *MU << " ("
1382 << *(MU->getMemoryInst()) << ")"
1383 << " because there are " << UpperBound - LocInfo.LowerBound
1384 << " stores to disambiguate\n");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001385 // Because we did not walk, LastKill is no longer valid, as this may
1386 // have been a kill.
1387 LocInfo.LastKillValid = false;
1388 continue;
1389 }
1390 bool FoundClobberResult = false;
1391 while (UpperBound > LocInfo.LowerBound) {
1392 if (isa<MemoryPhi>(VersionStack[UpperBound])) {
1393 // For phis, use the walker, see where we ended up, go there
1394 Instruction *UseInst = MU->getMemoryInst();
1395 MemoryAccess *Result = Walker->getClobberingMemoryAccess(UseInst);
1396 // We are guaranteed to find it or something is wrong
1397 while (VersionStack[UpperBound] != Result) {
1398 assert(UpperBound != 0);
1399 --UpperBound;
1400 }
1401 FoundClobberResult = true;
1402 break;
1403 }
1404
1405 MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]);
Daniel Berlindf101192016-08-03 00:01:46 +00001406 // If the lifetime of the pointer ends at this instruction, it's live on
1407 // entry.
1408 if (!UseMLOC.IsCall && lifetimeEndsAt(MD, UseMLOC.getLoc(), *AA)) {
1409 // Reset UpperBound to liveOnEntryDef's place in the stack
1410 UpperBound = 0;
1411 FoundClobberResult = true;
1412 break;
1413 }
Daniel Berlindff31de2016-08-02 21:57:52 +00001414 if (instructionClobbersQuery(MD, MU, UseMLOC, *AA)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001415 FoundClobberResult = true;
1416 break;
1417 }
1418 --UpperBound;
1419 }
1420 // At the end of this loop, UpperBound is either a clobber, or lower bound
1421 // PHI walking may cause it to be < LowerBound, and in fact, < LastKill.
1422 if (FoundClobberResult || UpperBound < LocInfo.LastKill) {
1423 MU->setDefiningAccess(VersionStack[UpperBound]);
1424 // We were last killed now by where we got to
1425 LocInfo.LastKill = UpperBound;
1426 } else {
1427 // Otherwise, we checked all the new ones, and now we know we can get to
1428 // LastKill.
1429 MU->setDefiningAccess(VersionStack[LocInfo.LastKill]);
1430 }
1431 LocInfo.LowerBound = VersionStack.size() - 1;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001432 LocInfo.LowerBoundBlock = BB;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001433 }
1434}
1435
1436/// Optimize uses to point to their actual clobbering definitions.
1437void MemorySSA::OptimizeUses::optimizeUses() {
1438
1439 // We perform a non-recursive top-down dominator tree walk
1440 struct StackInfo {
1441 const DomTreeNode *Node;
1442 DomTreeNode::const_iterator Iter;
1443 };
1444
1445 SmallVector<MemoryAccess *, 16> VersionStack;
1446 SmallVector<StackInfo, 16> DomTreeWorklist;
1447 DenseMap<MemoryLocOrCall, MemlocStackInfo> LocStackInfo;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001448 VersionStack.push_back(MSSA->getLiveOnEntryDef());
1449
1450 unsigned long StackEpoch = 1;
1451 unsigned long PopEpoch = 1;
Daniel Berlin7ac3d742016-08-05 22:09:14 +00001452 for (const auto *DomNode : depth_first(DT->getRootNode()))
1453 optimizeUsesInBlock(DomNode->getBlock(), StackEpoch, PopEpoch, VersionStack,
1454 LocStackInfo);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001455}
1456
Daniel Berlin3d512a22016-08-22 19:14:30 +00001457void MemorySSA::placePHINodes(
Daniel Berlin1e98c042016-09-26 17:22:54 +00001458 const SmallPtrSetImpl<BasicBlock *> &DefiningBlocks) {
Daniel Berlin3d512a22016-08-22 19:14:30 +00001459 // Determine where our MemoryPhi's should go
1460 ForwardIDFCalculator IDFs(*DT);
1461 IDFs.setDefiningBlocks(DefiningBlocks);
Daniel Berlin3d512a22016-08-22 19:14:30 +00001462 SmallVector<BasicBlock *, 32> IDFBlocks;
1463 IDFs.calculate(IDFBlocks);
1464
1465 // Now place MemoryPhi nodes.
1466 for (auto &BB : IDFBlocks) {
1467 // Insert phi node
1468 AccessList *Accesses = getOrCreateAccessList(BB);
1469 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
1470 ValueToMemoryAccess[BB] = Phi;
1471 // Phi's always are placed at the front of the block.
1472 Accesses->push_front(Phi);
1473 }
1474}
1475
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001476void MemorySSA::buildMemorySSA() {
George Burgess IVe1100f52016-02-02 22:46:49 +00001477 // We create an access to represent "live on entry", for things like
1478 // arguments or users of globals, where the memory they use is defined before
1479 // the beginning of the function. We do not actually insert it into the IR.
1480 // We do not define a live on exit for the immediate uses, and thus our
1481 // semantics do *not* imply that something with no immediate uses can simply
1482 // be removed.
1483 BasicBlock &StartingPoint = F.getEntryBlock();
1484 LiveOnEntryDef = make_unique<MemoryDef>(F.getContext(), nullptr, nullptr,
1485 &StartingPoint, NextID++);
1486
1487 // We maintain lists of memory accesses per-block, trading memory for time. We
1488 // could just look up the memory access for every possible instruction in the
1489 // stream.
1490 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001491 SmallPtrSet<BasicBlock *, 32> DefUseBlocks;
George Burgess IVe1100f52016-02-02 22:46:49 +00001492 // Go through each block, figure out where defs occur, and chain together all
1493 // the accesses.
1494 for (BasicBlock &B : F) {
Daniel Berlin7898ca62016-02-07 01:52:15 +00001495 bool InsertIntoDef = false;
Daniel Berlinada263d2016-06-20 20:21:33 +00001496 AccessList *Accesses = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +00001497 for (Instruction &I : B) {
Peter Collingbourneffecb142016-05-26 01:19:17 +00001498 MemoryUseOrDef *MUD = createNewAccess(&I);
George Burgess IVb42b7622016-03-11 19:34:03 +00001499 if (!MUD)
George Burgess IVe1100f52016-02-02 22:46:49 +00001500 continue;
George Burgess IV3887a412016-03-21 21:25:39 +00001501 InsertIntoDef |= isa<MemoryDef>(MUD);
Daniel Berlin1b51a292016-02-07 01:52:19 +00001502
George Burgess IVe1100f52016-02-02 22:46:49 +00001503 if (!Accesses)
1504 Accesses = getOrCreateAccessList(&B);
George Burgess IVb42b7622016-03-11 19:34:03 +00001505 Accesses->push_back(MUD);
George Burgess IVe1100f52016-02-02 22:46:49 +00001506 }
Daniel Berlin7898ca62016-02-07 01:52:15 +00001507 if (InsertIntoDef)
1508 DefiningBlocks.insert(&B);
George Burgess IV3887a412016-03-21 21:25:39 +00001509 if (Accesses)
Daniel Berlin1b51a292016-02-07 01:52:19 +00001510 DefUseBlocks.insert(&B);
1511 }
Daniel Berlin1e98c042016-09-26 17:22:54 +00001512 placePHINodes(DefiningBlocks);
George Burgess IVe1100f52016-02-02 22:46:49 +00001513
1514 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
1515 // filled in with all blocks.
1516 SmallPtrSet<BasicBlock *, 16> Visited;
1517 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1518
George Burgess IV5f308972016-07-19 01:29:15 +00001519 CachingWalker *Walker = getWalkerImpl();
1520
1521 // We're doing a batch of updates; don't drop useful caches between them.
1522 Walker->setAutoResetWalker(false);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001523 OptimizeUses(this, Walker, AA, DT).optimizeUses();
George Burgess IV5f308972016-07-19 01:29:15 +00001524 Walker->setAutoResetWalker(true);
1525 Walker->resetClobberWalker();
1526
George Burgess IVe1100f52016-02-02 22:46:49 +00001527 // Mark the uses in unreachable blocks as live on entry, so that they go
1528 // somewhere.
1529 for (auto &BB : F)
1530 if (!Visited.count(&BB))
1531 markUnreachableAsLiveOnEntry(&BB);
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001532}
George Burgess IVe1100f52016-02-02 22:46:49 +00001533
George Burgess IV5f308972016-07-19 01:29:15 +00001534MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
1535
1536MemorySSA::CachingWalker *MemorySSA::getWalkerImpl() {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001537 if (Walker)
1538 return Walker.get();
1539
1540 Walker = make_unique<CachingWalker>(this, AA, DT);
Geoff Berryb96d3b22016-06-01 21:30:40 +00001541 return Walker.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001542}
1543
Daniel Berlin14300262016-06-21 18:39:20 +00001544MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
1545 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
1546 AccessList *Accesses = getOrCreateAccessList(BB);
1547 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlin5130cc82016-07-31 21:08:20 +00001548 ValueToMemoryAccess[BB] = Phi;
Daniel Berlin14300262016-06-21 18:39:20 +00001549 // Phi's always are placed at the front of the block.
1550 Accesses->push_front(Phi);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001551 BlockNumberingValid.erase(BB);
Daniel Berlin14300262016-06-21 18:39:20 +00001552 return Phi;
1553}
1554
1555MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
1556 MemoryAccess *Definition) {
1557 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
1558 MemoryUseOrDef *NewAccess = createNewAccess(I);
1559 assert(
1560 NewAccess != nullptr &&
1561 "Tried to create a memory access for a non-memory touching instruction");
1562 NewAccess->setDefiningAccess(Definition);
1563 return NewAccess;
1564}
1565
1566MemoryAccess *MemorySSA::createMemoryAccessInBB(Instruction *I,
1567 MemoryAccess *Definition,
1568 const BasicBlock *BB,
1569 InsertionPlace Point) {
1570 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1571 auto *Accesses = getOrCreateAccessList(BB);
1572 if (Point == Beginning) {
1573 // It goes after any phi nodes
David Majnemer42531262016-08-12 03:55:06 +00001574 auto AI = find_if(
1575 *Accesses, [](const MemoryAccess &MA) { return !isa<MemoryPhi>(MA); });
Daniel Berlin14300262016-06-21 18:39:20 +00001576
1577 Accesses->insert(AI, NewAccess);
1578 } else {
1579 Accesses->push_back(NewAccess);
1580 }
Daniel Berlin5c46b942016-07-19 22:49:43 +00001581 BlockNumberingValid.erase(BB);
Daniel Berlin14300262016-06-21 18:39:20 +00001582 return NewAccess;
1583}
1584MemoryAccess *MemorySSA::createMemoryAccessBefore(Instruction *I,
1585 MemoryAccess *Definition,
1586 MemoryAccess *InsertPt) {
1587 assert(I->getParent() == InsertPt->getBlock() &&
1588 "New and old access must be in the same block");
1589 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1590 auto *Accesses = getOrCreateAccessList(InsertPt->getBlock());
1591 Accesses->insert(AccessList::iterator(InsertPt), NewAccess);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001592 BlockNumberingValid.erase(InsertPt->getBlock());
Daniel Berlin14300262016-06-21 18:39:20 +00001593 return NewAccess;
1594}
1595
1596MemoryAccess *MemorySSA::createMemoryAccessAfter(Instruction *I,
1597 MemoryAccess *Definition,
1598 MemoryAccess *InsertPt) {
1599 assert(I->getParent() == InsertPt->getBlock() &&
1600 "New and old access must be in the same block");
1601 MemoryUseOrDef *NewAccess = createDefinedAccess(I, Definition);
1602 auto *Accesses = getOrCreateAccessList(InsertPt->getBlock());
1603 Accesses->insertAfter(AccessList::iterator(InsertPt), NewAccess);
Daniel Berlin5c46b942016-07-19 22:49:43 +00001604 BlockNumberingValid.erase(InsertPt->getBlock());
Daniel Berlin14300262016-06-21 18:39:20 +00001605 return NewAccess;
1606}
1607
George Burgess IVe1100f52016-02-02 22:46:49 +00001608/// \brief Helper function to create new memory accesses
Peter Collingbourneffecb142016-05-26 01:19:17 +00001609MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I) {
Peter Collingbourneb9aa1f42016-05-26 04:58:46 +00001610 // The assume intrinsic has a control dependency which we model by claiming
1611 // that it writes arbitrarily. Ignore that fake memory dependency here.
1612 // FIXME: Replace this special casing with a more accurate modelling of
1613 // assume's control dependency.
1614 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1615 if (II->getIntrinsicID() == Intrinsic::assume)
1616 return nullptr;
1617
George Burgess IVe1100f52016-02-02 22:46:49 +00001618 // Find out what affect this instruction has on memory.
1619 ModRefInfo ModRef = AA->getModRefInfo(I);
1620 bool Def = bool(ModRef & MRI_Mod);
1621 bool Use = bool(ModRef & MRI_Ref);
1622
1623 // It's possible for an instruction to not modify memory at all. During
1624 // construction, we ignore them.
Peter Collingbourneffecb142016-05-26 01:19:17 +00001625 if (!Def && !Use)
George Burgess IVe1100f52016-02-02 22:46:49 +00001626 return nullptr;
1627
1628 assert((Def || Use) &&
1629 "Trying to create a memory access with a non-memory instruction");
1630
George Burgess IVb42b7622016-03-11 19:34:03 +00001631 MemoryUseOrDef *MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001632 if (Def)
George Burgess IVb42b7622016-03-11 19:34:03 +00001633 MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
George Burgess IVe1100f52016-02-02 22:46:49 +00001634 else
George Burgess IVb42b7622016-03-11 19:34:03 +00001635 MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
Daniel Berlin5130cc82016-07-31 21:08:20 +00001636 ValueToMemoryAccess[I] = MUD;
George Burgess IVb42b7622016-03-11 19:34:03 +00001637 return MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001638}
1639
1640MemoryAccess *MemorySSA::findDominatingDef(BasicBlock *UseBlock,
1641 enum InsertionPlace Where) {
1642 // Handle the initial case
1643 if (Where == Beginning)
1644 // The only thing that could define us at the beginning is a phi node
1645 if (MemoryPhi *Phi = getMemoryAccess(UseBlock))
1646 return Phi;
1647
1648 DomTreeNode *CurrNode = DT->getNode(UseBlock);
1649 // Need to be defined by our dominator
1650 if (Where == Beginning)
1651 CurrNode = CurrNode->getIDom();
1652 Where = End;
1653 while (CurrNode) {
1654 auto It = PerBlockAccesses.find(CurrNode->getBlock());
1655 if (It != PerBlockAccesses.end()) {
1656 auto &Accesses = It->second;
David Majnemerd7708772016-06-24 04:05:21 +00001657 for (MemoryAccess &RA : reverse(*Accesses)) {
1658 if (isa<MemoryDef>(RA) || isa<MemoryPhi>(RA))
1659 return &RA;
George Burgess IVe1100f52016-02-02 22:46:49 +00001660 }
1661 }
1662 CurrNode = CurrNode->getIDom();
1663 }
1664 return LiveOnEntryDef.get();
1665}
1666
1667/// \brief Returns true if \p Replacer dominates \p Replacee .
1668bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
1669 const MemoryAccess *Replacee) const {
1670 if (isa<MemoryUseOrDef>(Replacee))
1671 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
1672 const auto *MP = cast<MemoryPhi>(Replacee);
1673 // For a phi node, the use occurs in the predecessor block of the phi node.
1674 // Since we may occur multiple times in the phi node, we have to check each
1675 // operand to ensure Replacer dominates each operand where Replacee occurs.
1676 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +00001677 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +00001678 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
1679 return false;
1680 }
1681 return true;
1682}
1683
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001684/// \brief If all arguments of a MemoryPHI are defined by the same incoming
1685/// argument, return that argument.
1686static MemoryAccess *onlySingleValue(MemoryPhi *MP) {
1687 MemoryAccess *MA = nullptr;
1688
1689 for (auto &Arg : MP->operands()) {
1690 if (!MA)
1691 MA = cast<MemoryAccess>(Arg);
1692 else if (MA != Arg)
1693 return nullptr;
1694 }
1695 return MA;
1696}
1697
1698/// \brief Properly remove \p MA from all of MemorySSA's lookup tables.
1699///
1700/// Because of the way the intrusive list and use lists work, it is important to
1701/// do removal in the right order.
1702void MemorySSA::removeFromLookups(MemoryAccess *MA) {
1703 assert(MA->use_empty() &&
1704 "Trying to remove memory access that still has uses");
Daniel Berlin5c46b942016-07-19 22:49:43 +00001705 BlockNumbering.erase(MA);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001706 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA))
1707 MUD->setDefiningAccess(nullptr);
1708 // Invalidate our walker's cache if necessary
1709 if (!isa<MemoryUse>(MA))
1710 Walker->invalidateInfo(MA);
1711 // The call below to erase will destroy MA, so we can't change the order we
1712 // are doing things here
1713 Value *MemoryInst;
1714 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
1715 MemoryInst = MUD->getMemoryInst();
1716 } else {
1717 MemoryInst = MA->getBlock();
1718 }
Daniel Berlin5130cc82016-07-31 21:08:20 +00001719 auto VMA = ValueToMemoryAccess.find(MemoryInst);
1720 if (VMA->second == MA)
1721 ValueToMemoryAccess.erase(VMA);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001722
George Burgess IVe0e6e482016-03-02 02:35:04 +00001723 auto AccessIt = PerBlockAccesses.find(MA->getBlock());
Daniel Berlinada263d2016-06-20 20:21:33 +00001724 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001725 Accesses->erase(MA);
George Burgess IVe0e6e482016-03-02 02:35:04 +00001726 if (Accesses->empty())
1727 PerBlockAccesses.erase(AccessIt);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001728}
1729
1730void MemorySSA::removeMemoryAccess(MemoryAccess *MA) {
1731 assert(!isLiveOnEntryDef(MA) && "Trying to remove the live on entry def");
1732 // We can only delete phi nodes if they have no uses, or we can replace all
1733 // uses with a single definition.
1734 MemoryAccess *NewDefTarget = nullptr;
1735 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(MA)) {
1736 // Note that it is sufficient to know that all edges of the phi node have
1737 // the same argument. If they do, by the definition of dominance frontiers
1738 // (which we used to place this phi), that argument must dominate this phi,
1739 // and thus, must dominate the phi's uses, and so we will not hit the assert
1740 // below.
1741 NewDefTarget = onlySingleValue(MP);
1742 assert((NewDefTarget || MP->use_empty()) &&
1743 "We can't delete this memory phi");
1744 } else {
1745 NewDefTarget = cast<MemoryUseOrDef>(MA)->getDefiningAccess();
1746 }
1747
1748 // Re-point the uses at our defining access
1749 if (!MA->use_empty())
1750 MA->replaceAllUsesWith(NewDefTarget);
1751
1752 // The call below to erase will destroy MA, so we can't change the order we
1753 // are doing things here
1754 removeFromLookups(MA);
1755}
1756
George Burgess IVe1100f52016-02-02 22:46:49 +00001757void MemorySSA::print(raw_ostream &OS) const {
1758 MemorySSAAnnotatedWriter Writer(this);
1759 F.print(OS, &Writer);
1760}
1761
1762void MemorySSA::dump() const {
1763 MemorySSAAnnotatedWriter Writer(this);
1764 F.print(dbgs(), &Writer);
1765}
1766
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001767void MemorySSA::verifyMemorySSA() const {
1768 verifyDefUses(F);
1769 verifyDomination(F);
Daniel Berlin14300262016-06-21 18:39:20 +00001770 verifyOrdering(F);
Geoff Berrycdf53332016-08-08 17:52:01 +00001771 Walker->verify(this);
Daniel Berlin14300262016-06-21 18:39:20 +00001772}
1773
1774/// \brief Verify that the order and existence of MemoryAccesses matches the
1775/// order and existence of memory affecting instructions.
1776void MemorySSA::verifyOrdering(Function &F) const {
1777 // Walk all the blocks, comparing what the lookups think and what the access
1778 // lists think, as well as the order in the blocks vs the order in the access
1779 // lists.
1780 SmallVector<MemoryAccess *, 32> ActualAccesses;
1781 for (BasicBlock &B : F) {
1782 const AccessList *AL = getBlockAccesses(&B);
1783 MemoryAccess *Phi = getMemoryAccess(&B);
1784 if (Phi)
1785 ActualAccesses.push_back(Phi);
1786 for (Instruction &I : B) {
1787 MemoryAccess *MA = getMemoryAccess(&I);
1788 assert((!MA || AL) && "We have memory affecting instructions "
1789 "in this block but they are not in the "
1790 "access list");
1791 if (MA)
1792 ActualAccesses.push_back(MA);
1793 }
1794 // Either we hit the assert, really have no accesses, or we have both
1795 // accesses and an access list
1796 if (!AL)
1797 continue;
1798 assert(AL->size() == ActualAccesses.size() &&
1799 "We don't have the same number of accesses in the block as on the "
1800 "access list");
1801 auto ALI = AL->begin();
1802 auto AAI = ActualAccesses.begin();
1803 while (ALI != AL->end() && AAI != ActualAccesses.end()) {
1804 assert(&*ALI == *AAI && "Not the same accesses in the same order");
1805 ++ALI;
1806 ++AAI;
1807 }
1808 ActualAccesses.clear();
1809 }
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001810}
1811
George Burgess IVe1100f52016-02-02 22:46:49 +00001812/// \brief Verify the domination properties of MemorySSA by checking that each
1813/// definition dominates all of its uses.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001814void MemorySSA::verifyDomination(Function &F) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001815#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001816 for (BasicBlock &B : F) {
1817 // Phi nodes are attached to basic blocks
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001818 if (MemoryPhi *MP = getMemoryAccess(&B))
1819 for (const Use &U : MP->uses())
1820 assert(dominates(MP, U) && "Memory PHI does not dominate it's uses");
Daniel Berlin7af95872016-08-05 21:47:20 +00001821
George Burgess IVe1100f52016-02-02 22:46:49 +00001822 for (Instruction &I : B) {
1823 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
1824 if (!MD)
1825 continue;
1826
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001827 for (const Use &U : MD->uses())
1828 assert(dominates(MD, U) && "Memory Def does not dominate it's uses");
George Burgess IVe1100f52016-02-02 22:46:49 +00001829 }
1830 }
Daniel Berlin7af95872016-08-05 21:47:20 +00001831#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001832}
1833
1834/// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use
1835/// appears in the use list of \p Def.
Daniel Berlin7af95872016-08-05 21:47:20 +00001836
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001837void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001838#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001839 // The live on entry use may cause us to get a NULL def here
Daniel Berlin7af95872016-08-05 21:47:20 +00001840 if (!Def)
1841 assert(isLiveOnEntryDef(Use) &&
1842 "Null def but use not point to live on entry def");
1843 else
Daniel Berlinda2f38e2016-08-11 21:26:50 +00001844 assert(is_contained(Def->users(), Use) &&
Daniel Berlin7af95872016-08-05 21:47:20 +00001845 "Did not find use in def's use list");
1846#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001847}
1848
1849/// \brief Verify the immediate use information, by walking all the memory
1850/// accesses and verifying that, for each use, it appears in the
1851/// appropriate def's use list
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001852void MemorySSA::verifyDefUses(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001853 for (BasicBlock &B : F) {
1854 // Phi nodes are attached to basic blocks
Daniel Berlin14300262016-06-21 18:39:20 +00001855 if (MemoryPhi *Phi = getMemoryAccess(&B)) {
David Majnemer580e7542016-06-25 00:04:06 +00001856 assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
1857 pred_begin(&B), pred_end(&B))) &&
Daniel Berlin14300262016-06-21 18:39:20 +00001858 "Incomplete MemoryPhi Node");
George Burgess IVe1100f52016-02-02 22:46:49 +00001859 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
1860 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
Daniel Berlin14300262016-06-21 18:39:20 +00001861 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001862
1863 for (Instruction &I : B) {
1864 if (MemoryAccess *MA = getMemoryAccess(&I)) {
1865 assert(isa<MemoryUseOrDef>(MA) &&
1866 "Found a phi node not attached to a bb");
1867 verifyUseInDefs(cast<MemoryUseOrDef>(MA)->getDefiningAccess(), MA);
1868 }
1869 }
1870 }
1871}
1872
1873MemoryAccess *MemorySSA::getMemoryAccess(const Value *I) const {
Daniel Berlinf6c9ae92016-02-10 17:41:25 +00001874 return ValueToMemoryAccess.lookup(I);
George Burgess IVe1100f52016-02-02 22:46:49 +00001875}
1876
1877MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const {
1878 return cast_or_null<MemoryPhi>(getMemoryAccess((const Value *)BB));
1879}
1880
Daniel Berlin5c46b942016-07-19 22:49:43 +00001881/// Perform a local numbering on blocks so that instruction ordering can be
1882/// determined in constant time.
1883/// TODO: We currently just number in order. If we numbered by N, we could
1884/// allow at least N-1 sequences of insertBefore or insertAfter (and at least
1885/// log2(N) sequences of mixed before and after) without needing to invalidate
1886/// the numbering.
1887void MemorySSA::renumberBlock(const BasicBlock *B) const {
1888 // The pre-increment ensures the numbers really start at 1.
1889 unsigned long CurrentNumber = 0;
1890 const AccessList *AL = getBlockAccesses(B);
1891 assert(AL != nullptr && "Asking to renumber an empty block");
1892 for (const auto &I : *AL)
1893 BlockNumbering[&I] = ++CurrentNumber;
1894 BlockNumberingValid.insert(B);
1895}
1896
George Burgess IVe1100f52016-02-02 22:46:49 +00001897/// \brief Determine, for two memory accesses in the same block,
1898/// whether \p Dominator dominates \p Dominatee.
1899/// \returns True if \p Dominator dominates \p Dominatee.
1900bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
1901 const MemoryAccess *Dominatee) const {
Sebastian Pope1f60b12016-06-10 21:36:41 +00001902
Daniel Berlin5c46b942016-07-19 22:49:43 +00001903 const BasicBlock *DominatorBlock = Dominator->getBlock();
Daniel Berlin5c46b942016-07-19 22:49:43 +00001904
Daniel Berlin19860302016-07-19 23:08:08 +00001905 assert((DominatorBlock == Dominatee->getBlock()) &&
Daniel Berlin5c46b942016-07-19 22:49:43 +00001906 "Asking for local domination when accesses are in different blocks!");
Sebastian Pope1f60b12016-06-10 21:36:41 +00001907 // A node dominates itself.
1908 if (Dominatee == Dominator)
1909 return true;
1910
1911 // When Dominatee is defined on function entry, it is not dominated by another
1912 // memory access.
1913 if (isLiveOnEntryDef(Dominatee))
1914 return false;
1915
1916 // When Dominator is defined on function entry, it dominates the other memory
1917 // access.
1918 if (isLiveOnEntryDef(Dominator))
1919 return true;
1920
Daniel Berlin5c46b942016-07-19 22:49:43 +00001921 if (!BlockNumberingValid.count(DominatorBlock))
1922 renumberBlock(DominatorBlock);
George Burgess IVe1100f52016-02-02 22:46:49 +00001923
Daniel Berlin5c46b942016-07-19 22:49:43 +00001924 unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
1925 // All numbers start with 1
1926 assert(DominatorNum != 0 && "Block was not numbered properly");
1927 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
1928 assert(DominateeNum != 0 && "Block was not numbered properly");
1929 return DominatorNum < DominateeNum;
George Burgess IVe1100f52016-02-02 22:46:49 +00001930}
1931
George Burgess IV5f308972016-07-19 01:29:15 +00001932bool MemorySSA::dominates(const MemoryAccess *Dominator,
1933 const MemoryAccess *Dominatee) const {
1934 if (Dominator == Dominatee)
1935 return true;
1936
1937 if (isLiveOnEntryDef(Dominatee))
1938 return false;
1939
1940 if (Dominator->getBlock() != Dominatee->getBlock())
1941 return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
1942 return locallyDominates(Dominator, Dominatee);
1943}
1944
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001945bool MemorySSA::dominates(const MemoryAccess *Dominator,
1946 const Use &Dominatee) const {
1947 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Dominatee.getUser())) {
1948 BasicBlock *UseBB = MP->getIncomingBlock(Dominatee);
1949 // The def must dominate the incoming block of the phi.
1950 if (UseBB != Dominator->getBlock())
1951 return DT->dominates(Dominator->getBlock(), UseBB);
1952 // If the UseBB and the DefBB are the same, compare locally.
1953 return locallyDominates(Dominator, cast<MemoryAccess>(Dominatee));
1954 }
1955 // If it's not a PHI node use, the normal dominates can already handle it.
1956 return dominates(Dominator, cast<MemoryAccess>(Dominatee.getUser()));
1957}
1958
George Burgess IVe1100f52016-02-02 22:46:49 +00001959const static char LiveOnEntryStr[] = "liveOnEntry";
1960
1961void MemoryDef::print(raw_ostream &OS) const {
1962 MemoryAccess *UO = getDefiningAccess();
1963
1964 OS << getID() << " = MemoryDef(";
1965 if (UO && UO->getID())
1966 OS << UO->getID();
1967 else
1968 OS << LiveOnEntryStr;
1969 OS << ')';
1970}
1971
1972void MemoryPhi::print(raw_ostream &OS) const {
1973 bool First = true;
1974 OS << getID() << " = MemoryPhi(";
1975 for (const auto &Op : operands()) {
1976 BasicBlock *BB = getIncomingBlock(Op);
1977 MemoryAccess *MA = cast<MemoryAccess>(Op);
1978 if (!First)
1979 OS << ',';
1980 else
1981 First = false;
1982
1983 OS << '{';
1984 if (BB->hasName())
1985 OS << BB->getName();
1986 else
1987 BB->printAsOperand(OS, false);
1988 OS << ',';
1989 if (unsigned ID = MA->getID())
1990 OS << ID;
1991 else
1992 OS << LiveOnEntryStr;
1993 OS << '}';
1994 }
1995 OS << ')';
1996}
1997
1998MemoryAccess::~MemoryAccess() {}
1999
2000void MemoryUse::print(raw_ostream &OS) const {
2001 MemoryAccess *UO = getDefiningAccess();
2002 OS << "MemoryUse(";
2003 if (UO && UO->getID())
2004 OS << UO->getID();
2005 else
2006 OS << LiveOnEntryStr;
2007 OS << ')';
2008}
2009
2010void MemoryAccess::dump() const {
2011 print(dbgs());
2012 dbgs() << "\n";
2013}
2014
Chad Rosier232e29e2016-07-06 21:20:47 +00002015char MemorySSAPrinterLegacyPass::ID = 0;
2016
2017MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) {
2018 initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
2019}
2020
2021void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
2022 AU.setPreservesAll();
2023 AU.addRequired<MemorySSAWrapperPass>();
2024 AU.addPreserved<MemorySSAWrapperPass>();
2025}
2026
2027bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) {
2028 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
2029 MSSA.print(dbgs());
2030 if (VerifyMemorySSA)
2031 MSSA.verifyMemorySSA();
2032 return false;
2033}
2034
Geoff Berryb96d3b22016-06-01 21:30:40 +00002035char MemorySSAAnalysis::PassID;
George Burgess IVe1100f52016-02-02 22:46:49 +00002036
Daniel Berlin1e98c042016-09-26 17:22:54 +00002037MemorySSAAnalysis::Result MemorySSAAnalysis::run(Function &F,
2038 FunctionAnalysisManager &AM) {
Geoff Berryb96d3b22016-06-01 21:30:40 +00002039 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2040 auto &AA = AM.getResult<AAManager>(F);
Geoff Berry290a13e2016-08-08 18:27:22 +00002041 return MemorySSAAnalysis::Result(make_unique<MemorySSA>(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00002042}
2043
Geoff Berryb96d3b22016-06-01 21:30:40 +00002044PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
2045 FunctionAnalysisManager &AM) {
2046 OS << "MemorySSA for function: " << F.getName() << "\n";
Geoff Berry290a13e2016-08-08 18:27:22 +00002047 AM.getResult<MemorySSAAnalysis>(F).getMSSA().print(OS);
Geoff Berryb96d3b22016-06-01 21:30:40 +00002048
2049 return PreservedAnalyses::all();
George Burgess IVe1100f52016-02-02 22:46:49 +00002050}
2051
Geoff Berryb96d3b22016-06-01 21:30:40 +00002052PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
2053 FunctionAnalysisManager &AM) {
Geoff Berry290a13e2016-08-08 18:27:22 +00002054 AM.getResult<MemorySSAAnalysis>(F).getMSSA().verifyMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00002055
2056 return PreservedAnalyses::all();
2057}
2058
2059char MemorySSAWrapperPass::ID = 0;
2060
2061MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
2062 initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
2063}
2064
2065void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
2066
2067void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00002068 AU.setPreservesAll();
Geoff Berryb96d3b22016-06-01 21:30:40 +00002069 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
2070 AU.addRequiredTransitive<AAResultsWrapperPass>();
George Burgess IVe1100f52016-02-02 22:46:49 +00002071}
2072
Geoff Berryb96d3b22016-06-01 21:30:40 +00002073bool MemorySSAWrapperPass::runOnFunction(Function &F) {
2074 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2075 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2076 MSSA.reset(new MemorySSA(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00002077 return false;
2078}
2079
Geoff Berryb96d3b22016-06-01 21:30:40 +00002080void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); }
George Burgess IVe1100f52016-02-02 22:46:49 +00002081
Geoff Berryb96d3b22016-06-01 21:30:40 +00002082void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00002083 MSSA->print(OS);
2084}
2085
George Burgess IVe1100f52016-02-02 22:46:49 +00002086MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
2087
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002088MemorySSA::CachingWalker::CachingWalker(MemorySSA *M, AliasAnalysis *A,
2089 DominatorTree *D)
Daniel Berlin5c46b942016-07-19 22:49:43 +00002090 : MemorySSAWalker(M), Walker(*M, *A, *D, Cache), AutoResetWalker(true) {}
George Burgess IVe1100f52016-02-02 22:46:49 +00002091
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002092MemorySSA::CachingWalker::~CachingWalker() {}
George Burgess IVe1100f52016-02-02 22:46:49 +00002093
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002094void MemorySSA::CachingWalker::invalidateInfo(MemoryAccess *MA) {
Daniel Berlin83fc77b2016-03-01 18:46:54 +00002095 // TODO: We can do much better cache invalidation with differently stored
2096 // caches. For now, for MemoryUses, we simply remove them
2097 // from the cache, and kill the entire call/non-call cache for everything
2098 // else. The problem is for phis or defs, currently we'd need to follow use
2099 // chains down and invalidate anything below us in the chain that currently
2100 // terminates at this access.
2101
2102 // See if this is a MemoryUse, if so, just remove the cached info. MemoryUse
2103 // is by definition never a barrier, so nothing in the cache could point to
2104 // this use. In that case, we only need invalidate the info for the use
2105 // itself.
2106
2107 if (MemoryUse *MU = dyn_cast<MemoryUse>(MA)) {
George Burgess IV5f308972016-07-19 01:29:15 +00002108 UpwardsMemoryQuery Q(MU->getMemoryInst(), MU);
2109 Cache.remove(MU, Q.StartingLoc, Q.IsCall);
Geoff Berry9fe26e62016-04-22 14:44:10 +00002110 } else {
2111 // 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 +00002112 Cache.clear();
Geoff Berry9fe26e62016-04-22 14:44:10 +00002113 }
2114
Filipe Cabecinhas0da99372016-04-29 15:22:48 +00002115#ifdef EXPENSIVE_CHECKS
Geoff Berry9fe26e62016-04-22 14:44:10 +00002116 verifyRemoved(MA);
2117#endif
Daniel Berlin83fc77b2016-03-01 18:46:54 +00002118}
2119
George Burgess IVe1100f52016-02-02 22:46:49 +00002120/// \brief Walk the use-def chains starting at \p MA and find
2121/// the MemoryAccess that actually clobbers Loc.
2122///
2123/// \returns our clobbering memory access
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002124MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
2125 MemoryAccess *StartingAccess, UpwardsMemoryQuery &Q) {
George Burgess IV5f308972016-07-19 01:29:15 +00002126 MemoryAccess *New = Walker.findClobber(StartingAccess, Q);
2127#ifdef EXPENSIVE_CHECKS
2128 MemoryAccess *NewNoCache =
2129 Walker.findClobber(StartingAccess, Q, /*UseWalkerCache=*/false);
2130 assert(NewNoCache == New && "Cache made us hand back a different result?");
2131#endif
2132 if (AutoResetWalker)
2133 resetClobberWalker();
2134 return New;
George Burgess IVe1100f52016-02-02 22:46:49 +00002135}
2136
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002137MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
2138 MemoryAccess *StartingAccess, MemoryLocation &Loc) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002139 if (isa<MemoryPhi>(StartingAccess))
2140 return StartingAccess;
2141
2142 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
2143 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
2144 return StartingUseOrDef;
2145
2146 Instruction *I = StartingUseOrDef->getMemoryInst();
2147
2148 // Conservatively, fences are always clobbers, so don't perform the walk if we
2149 // hit a fence.
David Majnemera940f362016-07-15 17:19:24 +00002150 if (!ImmutableCallSite(I) && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002151 return StartingUseOrDef;
2152
2153 UpwardsMemoryQuery Q;
2154 Q.OriginalAccess = StartingUseOrDef;
2155 Q.StartingLoc = Loc;
George Burgess IV5f308972016-07-19 01:29:15 +00002156 Q.Inst = I;
George Burgess IVe1100f52016-02-02 22:46:49 +00002157 Q.IsCall = false;
George Burgess IVe1100f52016-02-02 22:46:49 +00002158
George Burgess IV5f308972016-07-19 01:29:15 +00002159 if (auto *CacheResult = Cache.lookup(StartingUseOrDef, Loc, Q.IsCall))
George Burgess IVe1100f52016-02-02 22:46:49 +00002160 return CacheResult;
2161
2162 // Unlike the other function, do not walk to the def of a def, because we are
2163 // handed something we already believe is the clobbering access.
2164 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
2165 ? StartingUseOrDef->getDefiningAccess()
2166 : StartingUseOrDef;
2167
2168 MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00002169 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2170 DEBUG(dbgs() << *StartingUseOrDef << "\n");
2171 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2172 DEBUG(dbgs() << *Clobber << "\n");
2173 return Clobber;
2174}
2175
2176MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002177MemorySSA::CachingWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
2178 auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
2179 // If this is a MemoryPhi, we can't do anything.
2180 if (!StartingAccess)
2181 return MA;
George Burgess IVe1100f52016-02-02 22:46:49 +00002182
George Burgess IV400ae402016-07-20 19:51:34 +00002183 const Instruction *I = StartingAccess->getMemoryInst();
George Burgess IV5f308972016-07-19 01:29:15 +00002184 UpwardsMemoryQuery Q(I, StartingAccess);
David Majnemera940f362016-07-15 17:19:24 +00002185 // We can't sanely do anything with a fences, they conservatively
George Burgess IVe1100f52016-02-02 22:46:49 +00002186 // clobber all memory, and have no locations to get pointers from to
David Majnemera940f362016-07-15 17:19:24 +00002187 // try to disambiguate.
George Burgess IV5f308972016-07-19 01:29:15 +00002188 if (!Q.IsCall && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002189 return StartingAccess;
2190
George Burgess IV5f308972016-07-19 01:29:15 +00002191 if (auto *CacheResult = Cache.lookup(StartingAccess, Q.StartingLoc, Q.IsCall))
George Burgess IVe1100f52016-02-02 22:46:49 +00002192 return CacheResult;
2193
George Burgess IV024f3d22016-08-03 19:57:02 +00002194 if (isUseTriviallyOptimizableToLiveOnEntry(*MSSA->AA, I)) {
2195 MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef();
2196 Cache.insert(StartingAccess, LiveOnEntry, Q.StartingLoc, Q.IsCall);
2197 return LiveOnEntry;
2198 }
2199
George Burgess IVe1100f52016-02-02 22:46:49 +00002200 // Start with the thing we already think clobbers this location
2201 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
2202
2203 // At this point, DefiningAccess may be the live on entry def.
2204 // If it is, we will not get a better result.
2205 if (MSSA->isLiveOnEntryDef(DefiningAccess))
2206 return DefiningAccess;
2207
2208 MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00002209 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2210 DEBUG(dbgs() << *DefiningAccess << "\n");
2211 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2212 DEBUG(dbgs() << *Result << "\n");
2213
2214 return Result;
2215}
2216
Geoff Berry9fe26e62016-04-22 14:44:10 +00002217// Verify that MA doesn't exist in any of the caches.
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002218void MemorySSA::CachingWalker::verifyRemoved(MemoryAccess *MA) {
George Burgess IV5f308972016-07-19 01:29:15 +00002219 assert(!Cache.contains(MA) && "Found removed MemoryAccess in cache.");
Geoff Berry9fe26e62016-04-22 14:44:10 +00002220}
2221
George Burgess IVe1100f52016-02-02 22:46:49 +00002222MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002223DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002224 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
2225 return Use->getDefiningAccess();
2226 return MA;
2227}
2228
2229MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
2230 MemoryAccess *StartingAccess, MemoryLocation &) {
2231 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
2232 return Use->getDefiningAccess();
2233 return StartingAccess;
2234}
George Burgess IV5f308972016-07-19 01:29:15 +00002235} // namespace llvm