blob: 42119f450a61b1566868583f89ddff19f0bed831 [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()) {}
Sebastian Pop5068d7a2016-10-13 03:23:33 +0000108 MemoryLocOrCall(const MemoryUseOrDef *MUD)
109 : MemoryLocOrCall(MUD->getMemoryInst()) {}
Daniel Berlindff31de2016-08-02 21:57:52 +0000110
111 MemoryLocOrCall(Instruction *Inst) {
112 if (ImmutableCallSite(Inst)) {
113 IsCall = true;
114 CS = ImmutableCallSite(Inst);
115 } else {
116 IsCall = false;
117 // There is no such thing as a memorylocation for a fence inst, and it is
118 // unique in that regard.
119 if (!isa<FenceInst>(Inst))
120 Loc = MemoryLocation::get(Inst);
121 }
122 }
123
124 explicit MemoryLocOrCall(const MemoryLocation &Loc)
125 : IsCall(false), Loc(Loc) {}
126
127 bool IsCall;
128 ImmutableCallSite getCS() const {
129 assert(IsCall);
130 return CS;
131 }
132 MemoryLocation getLoc() const {
133 assert(!IsCall);
134 return Loc;
135 }
136
137 bool operator==(const MemoryLocOrCall &Other) const {
138 if (IsCall != Other.IsCall)
139 return false;
140
141 if (IsCall)
142 return CS.getCalledValue() == Other.CS.getCalledValue();
143 return Loc == Other.Loc;
144 }
145
146private:
Daniel Berlinf5361132016-10-22 04:15:41 +0000147 union {
Daniel Berlind602e042017-01-25 20:56:19 +0000148 ImmutableCallSite CS;
149 MemoryLocation Loc;
Daniel Berlinf5361132016-10-22 04:15:41 +0000150 };
Daniel Berlindff31de2016-08-02 21:57:52 +0000151};
152}
153
154namespace llvm {
155template <> struct DenseMapInfo<MemoryLocOrCall> {
156 static inline MemoryLocOrCall getEmptyKey() {
157 return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getEmptyKey());
158 }
159 static inline MemoryLocOrCall getTombstoneKey() {
160 return MemoryLocOrCall(DenseMapInfo<MemoryLocation>::getTombstoneKey());
161 }
162 static unsigned getHashValue(const MemoryLocOrCall &MLOC) {
163 if (MLOC.IsCall)
164 return hash_combine(MLOC.IsCall,
165 DenseMapInfo<const Value *>::getHashValue(
166 MLOC.getCS().getCalledValue()));
167 return hash_combine(
168 MLOC.IsCall, DenseMapInfo<MemoryLocation>::getHashValue(MLOC.getLoc()));
169 }
170 static bool isEqual(const MemoryLocOrCall &LHS, const MemoryLocOrCall &RHS) {
171 return LHS == RHS;
172 }
173};
Daniel Berlindf101192016-08-03 00:01:46 +0000174
George Burgess IVf7672852016-08-03 19:59:11 +0000175enum class Reorderability { Always, IfNoAlias, Never };
George Burgess IV82e355c2016-08-03 19:39:54 +0000176
177/// This does one-way checks to see if Use could theoretically be hoisted above
178/// MayClobber. This will not check the other way around.
179///
180/// This assumes that, for the purposes of MemorySSA, Use comes directly after
181/// MayClobber, with no potentially clobbering operations in between them.
182/// (Where potentially clobbering ops are memory barriers, aliased stores, etc.)
183static Reorderability getLoadReorderability(const LoadInst *Use,
184 const LoadInst *MayClobber) {
185 bool VolatileUse = Use->isVolatile();
186 bool VolatileClobber = MayClobber->isVolatile();
187 // Volatile operations may never be reordered with other volatile operations.
188 if (VolatileUse && VolatileClobber)
189 return Reorderability::Never;
190
191 // The lang ref allows reordering of volatile and non-volatile operations.
192 // Whether an aliasing nonvolatile load and volatile load can be reordered,
193 // though, is ambiguous. Because it may not be best to exploit this ambiguity,
194 // we only allow volatile/non-volatile reordering if the volatile and
195 // non-volatile operations don't alias.
196 Reorderability Result = VolatileUse || VolatileClobber
197 ? Reorderability::IfNoAlias
198 : Reorderability::Always;
199
200 // If a load is seq_cst, it cannot be moved above other loads. If its ordering
201 // is weaker, it can be moved above other loads. We just need to be sure that
202 // MayClobber isn't an acquire load, because loads can't be moved above
203 // acquire loads.
204 //
205 // Note that this explicitly *does* allow the free reordering of monotonic (or
206 // weaker) loads of the same address.
207 bool SeqCstUse = Use->getOrdering() == AtomicOrdering::SequentiallyConsistent;
208 bool MayClobberIsAcquire = isAtLeastOrStrongerThan(MayClobber->getOrdering(),
209 AtomicOrdering::Acquire);
210 if (SeqCstUse || MayClobberIsAcquire)
211 return Reorderability::Never;
212 return Result;
213}
214
Sebastian Popd57d93c2016-10-12 03:08:40 +0000215static bool instructionClobbersQuery(MemoryDef *MD,
216 const MemoryLocation &UseLoc,
217 const Instruction *UseInst,
218 AliasAnalysis &AA) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000219 Instruction *DefInst = MD->getMemoryInst();
220 assert(DefInst && "Defining instruction not actually an instruction");
George Burgess IV5f308972016-07-19 01:29:15 +0000221
Daniel Berlindf101192016-08-03 00:01:46 +0000222 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) {
223 // These intrinsics will show up as affecting memory, but they are just
224 // markers.
225 switch (II->getIntrinsicID()) {
226 case Intrinsic::lifetime_start:
227 case Intrinsic::lifetime_end:
228 case Intrinsic::invariant_start:
229 case Intrinsic::invariant_end:
230 case Intrinsic::assume:
231 return false;
232 default:
233 break;
234 }
235 }
236
Daniel Berlindff31de2016-08-02 21:57:52 +0000237 ImmutableCallSite UseCS(UseInst);
238 if (UseCS) {
239 ModRefInfo I = AA.getModRefInfo(DefInst, UseCS);
240 return I != MRI_NoModRef;
241 }
George Burgess IV82e355c2016-08-03 19:39:54 +0000242
243 if (auto *DefLoad = dyn_cast<LoadInst>(DefInst)) {
244 if (auto *UseLoad = dyn_cast<LoadInst>(UseInst)) {
245 switch (getLoadReorderability(UseLoad, DefLoad)) {
246 case Reorderability::Always:
247 return false;
248 case Reorderability::Never:
249 return true;
250 case Reorderability::IfNoAlias:
251 return !AA.isNoAlias(UseLoc, MemoryLocation::get(DefLoad));
252 }
253 }
254 }
255
Daniel Berlindff31de2016-08-02 21:57:52 +0000256 return AA.getModRefInfo(DefInst, UseLoc) & MRI_Mod;
257}
258
Sebastian Pop5068d7a2016-10-13 03:23:33 +0000259static bool instructionClobbersQuery(MemoryDef *MD, const MemoryUseOrDef *MU,
260 const MemoryLocOrCall &UseMLOC,
261 AliasAnalysis &AA) {
262 // FIXME: This is a temporary hack to allow a single instructionClobbersQuery
263 // to exist while MemoryLocOrCall is pushed through places.
264 if (UseMLOC.IsCall)
265 return instructionClobbersQuery(MD, MemoryLocation(), MU->getMemoryInst(),
266 AA);
267 return instructionClobbersQuery(MD, UseMLOC.getLoc(), MU->getMemoryInst(),
268 AA);
269}
270
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000271// Return true when MD may alias MU, return false otherwise.
Daniel Berlindcb004f2017-03-02 23:06:46 +0000272bool MemorySSAUtil::defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU,
273 AliasAnalysis &AA) {
Sebastian Pop5068d7a2016-10-13 03:23:33 +0000274 return instructionClobbersQuery(MD, MU, MemoryLocOrCall(MU), AA);
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000275}
276}
277
278namespace {
279struct UpwardsMemoryQuery {
280 // True if our original query started off as a call
281 bool IsCall;
282 // The pointer location we started the query with. This will be empty if
283 // IsCall is true.
284 MemoryLocation StartingLoc;
285 // This is the instruction we were querying about.
286 const Instruction *Inst;
287 // The MemoryAccess we actually got called with, used to test local domination
288 const MemoryAccess *OriginalAccess;
289
290 UpwardsMemoryQuery()
291 : IsCall(false), Inst(nullptr), OriginalAccess(nullptr) {}
292
293 UpwardsMemoryQuery(const Instruction *Inst, const MemoryAccess *Access)
294 : IsCall(ImmutableCallSite(Inst)), Inst(Inst), OriginalAccess(Access) {
295 if (!IsCall)
296 StartingLoc = MemoryLocation::get(Inst);
297 }
298};
299
300static bool lifetimeEndsAt(MemoryDef *MD, const MemoryLocation &Loc,
301 AliasAnalysis &AA) {
302 Instruction *Inst = MD->getMemoryInst();
303 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
304 switch (II->getIntrinsicID()) {
305 case Intrinsic::lifetime_start:
306 case Intrinsic::lifetime_end:
307 return AA.isMustAlias(MemoryLocation(II->getArgOperand(1)), Loc);
308 default:
309 return false;
310 }
311 }
312 return false;
313}
314
315static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysis &AA,
316 const Instruction *I) {
317 // If the memory can't be changed, then loads of the memory can't be
318 // clobbered.
319 //
320 // FIXME: We should handle invariant groups, as well. It's a bit harder,
321 // because we need to pay close attention to invariant group barriers.
322 return isa<LoadInst>(I) && (I->getMetadata(LLVMContext::MD_invariant_load) ||
323 AA.pointsToConstantMemory(I));
324}
325
George Burgess IV5f308972016-07-19 01:29:15 +0000326/// Cache for our caching MemorySSA walker.
327class WalkerCache {
328 DenseMap<ConstMemoryAccessPair, MemoryAccess *> Accesses;
329 DenseMap<const MemoryAccess *, MemoryAccess *> Calls;
330
331public:
332 MemoryAccess *lookup(const MemoryAccess *MA, const MemoryLocation &Loc,
333 bool IsCall) const {
334 ++NumClobberCacheLookups;
335 MemoryAccess *R = IsCall ? Calls.lookup(MA) : Accesses.lookup({MA, Loc});
336 if (R)
337 ++NumClobberCacheHits;
338 return R;
339 }
340
341 bool insert(const MemoryAccess *MA, MemoryAccess *To,
342 const MemoryLocation &Loc, bool IsCall) {
343 // This is fine for Phis, since there are times where we can't optimize
344 // them. Making a def its own clobber is never correct, though.
345 assert((MA != To || isa<MemoryPhi>(MA)) &&
346 "Something can't clobber itself!");
347
348 ++NumClobberCacheInserts;
349 bool Inserted;
350 if (IsCall)
351 Inserted = Calls.insert({MA, To}).second;
352 else
353 Inserted = Accesses.insert({{MA, Loc}, To}).second;
354
355 return Inserted;
356 }
357
358 bool remove(const MemoryAccess *MA, const MemoryLocation &Loc, bool IsCall) {
359 return IsCall ? Calls.erase(MA) : Accesses.erase({MA, Loc});
360 }
361
362 void clear() {
363 Accesses.clear();
364 Calls.clear();
365 }
366
367 bool contains(const MemoryAccess *MA) const {
368 for (auto &P : Accesses)
369 if (P.first.first == MA || P.second == MA)
370 return true;
371 for (auto &P : Calls)
372 if (P.first == MA || P.second == MA)
373 return true;
374 return false;
375 }
376};
377
378/// Walks the defining uses of MemoryDefs. Stops after we hit something that has
379/// no defining use (e.g. a MemoryPhi or liveOnEntry). Note that, when comparing
380/// against a null def_chain_iterator, this will compare equal only after
381/// walking said Phi/liveOnEntry.
382struct def_chain_iterator
383 : public iterator_facade_base<def_chain_iterator, std::forward_iterator_tag,
384 MemoryAccess *> {
385 def_chain_iterator() : MA(nullptr) {}
386 def_chain_iterator(MemoryAccess *MA) : MA(MA) {}
387
388 MemoryAccess *operator*() const { return MA; }
389
390 def_chain_iterator &operator++() {
391 // N.B. liveOnEntry has a null defining access.
392 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
393 MA = MUD->getDefiningAccess();
394 else
395 MA = nullptr;
396 return *this;
397 }
398
399 bool operator==(const def_chain_iterator &O) const { return MA == O.MA; }
400
401private:
402 MemoryAccess *MA;
403};
404
405static iterator_range<def_chain_iterator>
406def_chain(MemoryAccess *MA, MemoryAccess *UpTo = nullptr) {
407#ifdef EXPENSIVE_CHECKS
408 assert((!UpTo || find(def_chain(MA), UpTo) != def_chain_iterator()) &&
409 "UpTo isn't in the def chain!");
410#endif
411 return make_range(def_chain_iterator(MA), def_chain_iterator(UpTo));
412}
413
414/// Verifies that `Start` is clobbered by `ClobberAt`, and that nothing
415/// inbetween `Start` and `ClobberAt` can clobbers `Start`.
416///
417/// This is meant to be as simple and self-contained as possible. Because it
418/// uses no cache, etc., it can be relatively expensive.
419///
420/// \param Start The MemoryAccess that we want to walk from.
421/// \param ClobberAt A clobber for Start.
422/// \param StartLoc The MemoryLocation for Start.
423/// \param MSSA The MemorySSA isntance that Start and ClobberAt belong to.
424/// \param Query The UpwardsMemoryQuery we used for our search.
425/// \param AA The AliasAnalysis we used for our search.
426static void LLVM_ATTRIBUTE_UNUSED
427checkClobberSanity(MemoryAccess *Start, MemoryAccess *ClobberAt,
428 const MemoryLocation &StartLoc, const MemorySSA &MSSA,
429 const UpwardsMemoryQuery &Query, AliasAnalysis &AA) {
430 assert(MSSA.dominates(ClobberAt, Start) && "Clobber doesn't dominate start?");
431
432 if (MSSA.isLiveOnEntryDef(Start)) {
433 assert(MSSA.isLiveOnEntryDef(ClobberAt) &&
434 "liveOnEntry must clobber itself");
435 return;
436 }
437
George Burgess IV5f308972016-07-19 01:29:15 +0000438 bool FoundClobber = false;
439 DenseSet<MemoryAccessPair> VisitedPhis;
440 SmallVector<MemoryAccessPair, 8> Worklist;
441 Worklist.emplace_back(Start, StartLoc);
442 // Walk all paths from Start to ClobberAt, while looking for clobbers. If one
443 // is found, complain.
444 while (!Worklist.empty()) {
445 MemoryAccessPair MAP = Worklist.pop_back_val();
446 // All we care about is that nothing from Start to ClobberAt clobbers Start.
447 // We learn nothing from revisiting nodes.
448 if (!VisitedPhis.insert(MAP).second)
449 continue;
450
451 for (MemoryAccess *MA : def_chain(MAP.first)) {
452 if (MA == ClobberAt) {
453 if (auto *MD = dyn_cast<MemoryDef>(MA)) {
454 // instructionClobbersQuery isn't essentially free, so don't use `|=`,
455 // since it won't let us short-circuit.
456 //
457 // Also, note that this can't be hoisted out of the `Worklist` loop,
458 // since MD may only act as a clobber for 1 of N MemoryLocations.
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000459 FoundClobber =
460 FoundClobber || MSSA.isLiveOnEntryDef(MD) ||
461 instructionClobbersQuery(MD, MAP.second, Query.Inst, AA);
George Burgess IV5f308972016-07-19 01:29:15 +0000462 }
463 break;
464 }
465
466 // We should never hit liveOnEntry, unless it's the clobber.
467 assert(!MSSA.isLiveOnEntryDef(MA) && "Hit liveOnEntry before clobber?");
468
469 if (auto *MD = dyn_cast<MemoryDef>(MA)) {
470 (void)MD;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000471 assert(!instructionClobbersQuery(MD, MAP.second, Query.Inst, AA) &&
George Burgess IV5f308972016-07-19 01:29:15 +0000472 "Found clobber before reaching ClobberAt!");
473 continue;
474 }
475
476 assert(isa<MemoryPhi>(MA));
477 Worklist.append(upward_defs_begin({MA, MAP.second}), upward_defs_end());
478 }
479 }
480
481 // If ClobberAt is a MemoryPhi, we can assume something above it acted as a
482 // clobber. Otherwise, `ClobberAt` should've acted as a clobber at some point.
483 assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&
484 "ClobberAt never acted as a clobber");
485}
486
487/// Our algorithm for walking (and trying to optimize) clobbers, all wrapped up
488/// in one class.
489class ClobberWalker {
490 /// Save a few bytes by using unsigned instead of size_t.
491 using ListIndex = unsigned;
492
493 /// Represents a span of contiguous MemoryDefs, potentially ending in a
494 /// MemoryPhi.
495 struct DefPath {
496 MemoryLocation Loc;
497 // Note that, because we always walk in reverse, Last will always dominate
498 // First. Also note that First and Last are inclusive.
499 MemoryAccess *First;
500 MemoryAccess *Last;
George Burgess IV5f308972016-07-19 01:29:15 +0000501 Optional<ListIndex> Previous;
502
503 DefPath(const MemoryLocation &Loc, MemoryAccess *First, MemoryAccess *Last,
504 Optional<ListIndex> Previous)
505 : Loc(Loc), First(First), Last(Last), Previous(Previous) {}
506
507 DefPath(const MemoryLocation &Loc, MemoryAccess *Init,
508 Optional<ListIndex> Previous)
509 : DefPath(Loc, Init, Init, Previous) {}
510 };
511
512 const MemorySSA &MSSA;
513 AliasAnalysis &AA;
514 DominatorTree &DT;
515 WalkerCache &WC;
516 UpwardsMemoryQuery *Query;
517 bool UseCache;
518
519 // Phi optimization bookkeeping
520 SmallVector<DefPath, 32> Paths;
521 DenseSet<ConstMemoryAccessPair> VisitedPhis;
George Burgess IV5f308972016-07-19 01:29:15 +0000522
523 void setUseCache(bool Use) { UseCache = Use; }
524 bool shouldIgnoreCache() const {
525 // UseCache will only be false when we're debugging, or when expensive
526 // checks are enabled. In either case, we don't care deeply about speed.
527 return LLVM_UNLIKELY(!UseCache);
528 }
529
530 void addCacheEntry(const MemoryAccess *What, MemoryAccess *To,
531 const MemoryLocation &Loc) const {
Daniel Berlin5c46b942016-07-19 22:49:43 +0000532// EXPENSIVE_CHECKS because most of these queries are redundant.
George Burgess IV5f308972016-07-19 01:29:15 +0000533#ifdef EXPENSIVE_CHECKS
534 assert(MSSA.dominates(To, What));
535#endif
536 if (shouldIgnoreCache())
537 return;
538 WC.insert(What, To, Loc, Query->IsCall);
539 }
540
541 MemoryAccess *lookupCache(const MemoryAccess *MA, const MemoryLocation &Loc) {
542 return shouldIgnoreCache() ? nullptr : WC.lookup(MA, Loc, Query->IsCall);
543 }
544
545 void cacheDefPath(const DefPath &DN, MemoryAccess *Target) const {
546 if (shouldIgnoreCache())
547 return;
548
549 for (MemoryAccess *MA : def_chain(DN.First, DN.Last))
550 addCacheEntry(MA, Target, DN.Loc);
551
552 // DefPaths only express the path we walked. So, DN.Last could either be a
553 // thing we want to cache, or not.
554 if (DN.Last != Target)
555 addCacheEntry(DN.Last, Target, DN.Loc);
556 }
557
558 /// Find the nearest def or phi that `From` can legally be optimized to.
Daniel Berlin7500c562017-04-01 08:59:45 +0000559 MemoryAccess *getWalkTarget(const MemoryPhi *From) const {
George Burgess IV5f308972016-07-19 01:29:15 +0000560 assert(From->getNumOperands() && "Phi with no operands?");
561
562 BasicBlock *BB = From->getBlock();
George Burgess IV5f308972016-07-19 01:29:15 +0000563 MemoryAccess *Result = MSSA.getLiveOnEntryDef();
564 DomTreeNode *Node = DT.getNode(BB);
565 while ((Node = Node->getIDom())) {
Daniel Berlin7500c562017-04-01 08:59:45 +0000566 auto *Defs = MSSA.getBlockDefs(Node->getBlock());
567 if (Defs)
568 return const_cast<MemoryAccess *>(&*Defs->rbegin());
George Burgess IV5f308972016-07-19 01:29:15 +0000569 }
George Burgess IV5f308972016-07-19 01:29:15 +0000570 return Result;
571 }
572
573 /// Result of calling walkToPhiOrClobber.
574 struct UpwardsWalkResult {
575 /// The "Result" of the walk. Either a clobber, the last thing we walked, or
576 /// both.
577 MemoryAccess *Result;
578 bool IsKnownClobber;
579 bool FromCache;
580 };
581
582 /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last.
583 /// This will update Desc.Last as it walks. It will (optionally) also stop at
584 /// StopAt.
585 ///
586 /// This does not test for whether StopAt is a clobber
587 UpwardsWalkResult walkToPhiOrClobber(DefPath &Desc,
588 MemoryAccess *StopAt = nullptr) {
589 assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");
590
591 for (MemoryAccess *Current : def_chain(Desc.Last)) {
592 Desc.Last = Current;
593 if (Current == StopAt)
594 return {Current, false, false};
595
596 if (auto *MD = dyn_cast<MemoryDef>(Current))
597 if (MSSA.isLiveOnEntryDef(MD) ||
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000598 instructionClobbersQuery(MD, Desc.Loc, Query->Inst, AA))
George Burgess IV5f308972016-07-19 01:29:15 +0000599 return {MD, true, false};
600
601 // Cache checks must be done last, because if Current is a clobber, the
602 // cache will contain the clobber for Current.
603 if (MemoryAccess *MA = lookupCache(Current, Desc.Loc))
604 return {MA, true, true};
605 }
606
607 assert(isa<MemoryPhi>(Desc.Last) &&
608 "Ended at a non-clobber that's not a phi?");
609 return {Desc.Last, false, false};
610 }
611
612 void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches,
613 ListIndex PriorNode) {
614 auto UpwardDefs = make_range(upward_defs_begin({Phi, Paths[PriorNode].Loc}),
615 upward_defs_end());
616 for (const MemoryAccessPair &P : UpwardDefs) {
617 PausedSearches.push_back(Paths.size());
618 Paths.emplace_back(P.second, P.first, PriorNode);
619 }
620 }
621
622 /// Represents a search that terminated after finding a clobber. This clobber
623 /// may or may not be present in the path of defs from LastNode..SearchStart,
624 /// since it may have been retrieved from cache.
625 struct TerminatedPath {
626 MemoryAccess *Clobber;
627 ListIndex LastNode;
628 };
629
630 /// Get an access that keeps us from optimizing to the given phi.
631 ///
632 /// PausedSearches is an array of indices into the Paths array. Its incoming
633 /// value is the indices of searches that stopped at the last phi optimization
634 /// target. It's left in an unspecified state.
635 ///
636 /// If this returns None, NewPaused is a vector of searches that terminated
637 /// at StopWhere. Otherwise, NewPaused is left in an unspecified state.
George Burgess IV14633b52016-08-03 01:22:19 +0000638 Optional<TerminatedPath>
George Burgess IV5f308972016-07-19 01:29:15 +0000639 getBlockingAccess(MemoryAccess *StopWhere,
640 SmallVectorImpl<ListIndex> &PausedSearches,
641 SmallVectorImpl<ListIndex> &NewPaused,
642 SmallVectorImpl<TerminatedPath> &Terminated) {
643 assert(!PausedSearches.empty() && "No searches to continue?");
644
645 // BFS vs DFS really doesn't make a difference here, so just do a DFS with
646 // PausedSearches as our stack.
647 while (!PausedSearches.empty()) {
648 ListIndex PathIndex = PausedSearches.pop_back_val();
649 DefPath &Node = Paths[PathIndex];
650
651 // If we've already visited this path with this MemoryLocation, we don't
652 // need to do so again.
653 //
654 // NOTE: That we just drop these paths on the ground makes caching
655 // behavior sporadic. e.g. given a diamond:
656 // A
657 // B C
658 // D
659 //
660 // ...If we walk D, B, A, C, we'll only cache the result of phi
661 // optimization for A, B, and D; C will be skipped because it dies here.
662 // This arguably isn't the worst thing ever, since:
663 // - We generally query things in a top-down order, so if we got below D
664 // without needing cache entries for {C, MemLoc}, then chances are
665 // that those cache entries would end up ultimately unused.
666 // - We still cache things for A, so C only needs to walk up a bit.
667 // If this behavior becomes problematic, we can fix without a ton of extra
668 // work.
669 if (!VisitedPhis.insert({Node.Last, Node.Loc}).second)
670 continue;
671
672 UpwardsWalkResult Res = walkToPhiOrClobber(Node, /*StopAt=*/StopWhere);
673 if (Res.IsKnownClobber) {
674 assert(Res.Result != StopWhere || Res.FromCache);
675 // If this wasn't a cache hit, we hit a clobber when walking. That's a
676 // failure.
George Burgess IV14633b52016-08-03 01:22:19 +0000677 TerminatedPath Term{Res.Result, PathIndex};
George Burgess IV5f308972016-07-19 01:29:15 +0000678 if (!Res.FromCache || !MSSA.dominates(Res.Result, StopWhere))
George Burgess IV14633b52016-08-03 01:22:19 +0000679 return Term;
George Burgess IV5f308972016-07-19 01:29:15 +0000680
681 // Otherwise, it's a valid thing to potentially optimize to.
George Burgess IV14633b52016-08-03 01:22:19 +0000682 Terminated.push_back(Term);
George Burgess IV5f308972016-07-19 01:29:15 +0000683 continue;
684 }
685
686 if (Res.Result == StopWhere) {
687 // We've hit our target. Save this path off for if we want to continue
688 // walking.
689 NewPaused.push_back(PathIndex);
690 continue;
691 }
692
693 assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");
694 addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
695 }
696
697 return None;
698 }
699
700 template <typename T, typename Walker>
701 struct generic_def_path_iterator
702 : public iterator_facade_base<generic_def_path_iterator<T, Walker>,
703 std::forward_iterator_tag, T *> {
704 generic_def_path_iterator() : W(nullptr), N(None) {}
705 generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}
706
707 T &operator*() const { return curNode(); }
708
709 generic_def_path_iterator &operator++() {
710 N = curNode().Previous;
711 return *this;
712 }
713
714 bool operator==(const generic_def_path_iterator &O) const {
715 if (N.hasValue() != O.N.hasValue())
716 return false;
717 return !N.hasValue() || *N == *O.N;
718 }
719
720 private:
721 T &curNode() const { return W->Paths[*N]; }
722
723 Walker *W;
724 Optional<ListIndex> N;
725 };
726
727 using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
728 using const_def_path_iterator =
729 generic_def_path_iterator<const DefPath, const ClobberWalker>;
730
731 iterator_range<def_path_iterator> def_path(ListIndex From) {
732 return make_range(def_path_iterator(this, From), def_path_iterator());
733 }
734
735 iterator_range<const_def_path_iterator> const_def_path(ListIndex From) const {
736 return make_range(const_def_path_iterator(this, From),
737 const_def_path_iterator());
738 }
739
740 struct OptznResult {
741 /// The path that contains our result.
742 TerminatedPath PrimaryClobber;
743 /// The paths that we can legally cache back from, but that aren't
744 /// necessarily the result of the Phi optimization.
745 SmallVector<TerminatedPath, 4> OtherClobbers;
746 };
747
748 ListIndex defPathIndex(const DefPath &N) const {
749 // The assert looks nicer if we don't need to do &N
750 const DefPath *NP = &N;
751 assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
752 "Out of bounds DefPath!");
753 return NP - &Paths.front();
754 }
755
756 /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths
757 /// that act as legal clobbers. Note that this won't return *all* clobbers.
758 ///
759 /// Phi optimization algorithm tl;dr:
760 /// - Find the earliest def/phi, A, we can optimize to
761 /// - Find if all paths from the starting memory access ultimately reach A
762 /// - If not, optimization isn't possible.
763 /// - Otherwise, walk from A to another clobber or phi, A'.
764 /// - If A' is a def, we're done.
765 /// - If A' is a phi, try to optimize it.
766 ///
767 /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path
768 /// terminates when a MemoryAccess that clobbers said MemoryLocation is found.
769 OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start,
770 const MemoryLocation &Loc) {
771 assert(Paths.empty() && VisitedPhis.empty() &&
772 "Reset the optimization state.");
773
774 Paths.emplace_back(Loc, Start, Phi, None);
775 // Stores how many "valid" optimization nodes we had prior to calling
776 // addSearches/getBlockingAccess. Necessary for caching if we had a blocker.
777 auto PriorPathsSize = Paths.size();
778
779 SmallVector<ListIndex, 16> PausedSearches;
780 SmallVector<ListIndex, 8> NewPaused;
781 SmallVector<TerminatedPath, 4> TerminatedPaths;
782
783 addSearches(Phi, PausedSearches, 0);
784
785 // Moves the TerminatedPath with the "most dominated" Clobber to the end of
786 // Paths.
787 auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
788 assert(!Paths.empty() && "Need a path to move");
George Burgess IV5f308972016-07-19 01:29:15 +0000789 auto Dom = Paths.begin();
790 for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I)
791 if (!MSSA.dominates(I->Clobber, Dom->Clobber))
792 Dom = I;
793 auto Last = Paths.end() - 1;
794 if (Last != Dom)
795 std::iter_swap(Last, Dom);
796 };
797
798 MemoryPhi *Current = Phi;
799 while (1) {
800 assert(!MSSA.isLiveOnEntryDef(Current) &&
801 "liveOnEntry wasn't treated as a clobber?");
802
803 MemoryAccess *Target = getWalkTarget(Current);
804 // If a TerminatedPath doesn't dominate Target, then it wasn't a legal
805 // optimization for the prior phi.
806 assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {
807 return MSSA.dominates(P.Clobber, Target);
808 }));
809
810 // FIXME: This is broken, because the Blocker may be reported to be
811 // liveOnEntry, and we'll happily wait for that to disappear (read: never)
George Burgess IV7f414b92016-08-22 23:40:01 +0000812 // For the moment, this is fine, since we do nothing with blocker info.
George Burgess IV14633b52016-08-03 01:22:19 +0000813 if (Optional<TerminatedPath> Blocker = getBlockingAccess(
George Burgess IV5f308972016-07-19 01:29:15 +0000814 Target, PausedSearches, NewPaused, TerminatedPaths)) {
George Burgess IV5f308972016-07-19 01:29:15 +0000815 // Cache our work on the blocking node, since we know that's correct.
George Burgess IV14633b52016-08-03 01:22:19 +0000816 cacheDefPath(Paths[Blocker->LastNode], Blocker->Clobber);
George Burgess IV5f308972016-07-19 01:29:15 +0000817
818 // Find the node we started at. We can't search based on N->Last, since
819 // we may have gone around a loop with a different MemoryLocation.
George Burgess IV14633b52016-08-03 01:22:19 +0000820 auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) {
George Burgess IV5f308972016-07-19 01:29:15 +0000821 return defPathIndex(N) < PriorPathsSize;
822 });
823 assert(Iter != def_path_iterator());
824
825 DefPath &CurNode = *Iter;
826 assert(CurNode.Last == Current);
George Burgess IV5f308972016-07-19 01:29:15 +0000827
828 // Two things:
829 // A. We can't reliably cache all of NewPaused back. Consider a case
830 // where we have two paths in NewPaused; one of which can't optimize
831 // above this phi, whereas the other can. If we cache the second path
832 // back, we'll end up with suboptimal cache entries. We can handle
833 // cases like this a bit better when we either try to find all
834 // clobbers that block phi optimization, or when our cache starts
835 // supporting unfinished searches.
836 // B. We can't reliably cache TerminatedPaths back here without doing
837 // extra checks; consider a case like:
838 // T
839 // / \
840 // D C
841 // \ /
842 // S
843 // Where T is our target, C is a node with a clobber on it, D is a
844 // diamond (with a clobber *only* on the left or right node, N), and
845 // S is our start. Say we walk to D, through the node opposite N
846 // (read: ignoring the clobber), and see a cache entry in the top
847 // node of D. That cache entry gets put into TerminatedPaths. We then
848 // walk up to C (N is later in our worklist), find the clobber, and
849 // quit. If we append TerminatedPaths to OtherClobbers, we'll cache
850 // the bottom part of D to the cached clobber, ignoring the clobber
851 // in N. Again, this problem goes away if we start tracking all
852 // blockers for a given phi optimization.
853 TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
854 return {Result, {}};
855 }
856
857 // If there's nothing left to search, then all paths led to valid clobbers
858 // that we got from our cache; pick the nearest to the start, and allow
859 // the rest to be cached back.
860 if (NewPaused.empty()) {
861 MoveDominatedPathToEnd(TerminatedPaths);
862 TerminatedPath Result = TerminatedPaths.pop_back_val();
863 return {Result, std::move(TerminatedPaths)};
864 }
865
866 MemoryAccess *DefChainEnd = nullptr;
867 SmallVector<TerminatedPath, 4> Clobbers;
868 for (ListIndex Paused : NewPaused) {
869 UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
870 if (WR.IsKnownClobber)
871 Clobbers.push_back({WR.Result, Paused});
872 else
873 // Micro-opt: If we hit the end of the chain, save it.
874 DefChainEnd = WR.Result;
875 }
876
877 if (!TerminatedPaths.empty()) {
878 // If we couldn't find the dominating phi/liveOnEntry in the above loop,
879 // do it now.
880 if (!DefChainEnd)
881 for (MemoryAccess *MA : def_chain(Target))
882 DefChainEnd = MA;
883
884 // If any of the terminated paths don't dominate the phi we'll try to
885 // optimize, we need to figure out what they are and quit.
886 const BasicBlock *ChainBB = DefChainEnd->getBlock();
887 for (const TerminatedPath &TP : TerminatedPaths) {
888 // Because we know that DefChainEnd is as "high" as we can go, we
889 // don't need local dominance checks; BB dominance is sufficient.
890 if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
891 Clobbers.push_back(TP);
892 }
893 }
894
895 // If we have clobbers in the def chain, find the one closest to Current
896 // and quit.
897 if (!Clobbers.empty()) {
898 MoveDominatedPathToEnd(Clobbers);
899 TerminatedPath Result = Clobbers.pop_back_val();
900 return {Result, std::move(Clobbers)};
901 }
902
903 assert(all_of(NewPaused,
904 [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
905
906 // Because liveOnEntry is a clobber, this must be a phi.
907 auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
908
909 PriorPathsSize = Paths.size();
910 PausedSearches.clear();
911 for (ListIndex I : NewPaused)
912 addSearches(DefChainPhi, PausedSearches, I);
913 NewPaused.clear();
914
915 Current = DefChainPhi;
916 }
917 }
918
919 /// Caches everything in an OptznResult.
920 void cacheOptResult(const OptznResult &R) {
921 if (R.OtherClobbers.empty()) {
922 // If we're not going to be caching OtherClobbers, don't bother with
923 // marking visited/etc.
924 for (const DefPath &N : const_def_path(R.PrimaryClobber.LastNode))
925 cacheDefPath(N, R.PrimaryClobber.Clobber);
926 return;
927 }
928
929 // PrimaryClobber is our answer. If we can cache anything back, we need to
930 // stop caching when we visit PrimaryClobber.
931 SmallBitVector Visited(Paths.size());
932 for (const DefPath &N : const_def_path(R.PrimaryClobber.LastNode)) {
933 Visited[defPathIndex(N)] = true;
934 cacheDefPath(N, R.PrimaryClobber.Clobber);
935 }
936
937 for (const TerminatedPath &P : R.OtherClobbers) {
938 for (const DefPath &N : const_def_path(P.LastNode)) {
939 ListIndex NIndex = defPathIndex(N);
940 if (Visited[NIndex])
941 break;
942 Visited[NIndex] = true;
943 cacheDefPath(N, P.Clobber);
944 }
945 }
946 }
947
948 void verifyOptResult(const OptznResult &R) const {
949 assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
950 return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
951 }));
952 }
953
954 void resetPhiOptznState() {
955 Paths.clear();
956 VisitedPhis.clear();
957 }
958
959public:
960 ClobberWalker(const MemorySSA &MSSA, AliasAnalysis &AA, DominatorTree &DT,
961 WalkerCache &WC)
962 : MSSA(MSSA), AA(AA), DT(DT), WC(WC), UseCache(true) {}
963
Daniel Berlin7500c562017-04-01 08:59:45 +0000964 void reset() {}
George Burgess IV5f308972016-07-19 01:29:15 +0000965
966 /// Finds the nearest clobber for the given query, optimizing phis if
967 /// possible.
968 MemoryAccess *findClobber(MemoryAccess *Start, UpwardsMemoryQuery &Q,
969 bool UseWalkerCache = true) {
970 setUseCache(UseWalkerCache);
971 Query = &Q;
972
973 MemoryAccess *Current = Start;
974 // This walker pretends uses don't exist. If we're handed one, silently grab
975 // its def. (This has the nice side-effect of ensuring we never cache uses)
976 if (auto *MU = dyn_cast<MemoryUse>(Start))
977 Current = MU->getDefiningAccess();
978
979 DefPath FirstDesc(Q.StartingLoc, Current, Current, None);
980 // Fast path for the overly-common case (no crazy phi optimization
981 // necessary)
982 UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
George Burgess IV93ea19b2016-07-24 07:03:49 +0000983 MemoryAccess *Result;
George Burgess IV5f308972016-07-19 01:29:15 +0000984 if (WalkResult.IsKnownClobber) {
985 cacheDefPath(FirstDesc, WalkResult.Result);
George Burgess IV93ea19b2016-07-24 07:03:49 +0000986 Result = WalkResult.Result;
987 } else {
988 OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
989 Current, Q.StartingLoc);
990 verifyOptResult(OptRes);
991 cacheOptResult(OptRes);
992 resetPhiOptznState();
993 Result = OptRes.PrimaryClobber.Clobber;
George Burgess IV5f308972016-07-19 01:29:15 +0000994 }
995
George Burgess IV5f308972016-07-19 01:29:15 +0000996#ifdef EXPENSIVE_CHECKS
George Burgess IV93ea19b2016-07-24 07:03:49 +0000997 checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, AA);
George Burgess IV5f308972016-07-19 01:29:15 +0000998#endif
George Burgess IV93ea19b2016-07-24 07:03:49 +0000999 return Result;
George Burgess IV5f308972016-07-19 01:29:15 +00001000 }
Geoff Berrycdf53332016-08-08 17:52:01 +00001001
1002 void verify(const MemorySSA *MSSA) { assert(MSSA == &this->MSSA); }
George Burgess IV5f308972016-07-19 01:29:15 +00001003};
1004
1005struct RenamePassData {
1006 DomTreeNode *DTN;
1007 DomTreeNode::const_iterator ChildIt;
1008 MemoryAccess *IncomingVal;
1009
1010 RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
1011 MemoryAccess *M)
1012 : DTN(D), ChildIt(It), IncomingVal(M) {}
1013 void swap(RenamePassData &RHS) {
1014 std::swap(DTN, RHS.DTN);
1015 std::swap(ChildIt, RHS.ChildIt);
1016 std::swap(IncomingVal, RHS.IncomingVal);
1017 }
1018};
1019} // anonymous namespace
1020
1021namespace llvm {
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001022/// \brief A MemorySSAWalker that does AA walks and caching of lookups to
1023/// disambiguate accesses.
1024///
1025/// FIXME: The current implementation of this can take quadratic space in rare
1026/// cases. This can be fixed, but it is something to note until it is fixed.
1027///
1028/// In order to trigger this behavior, you need to store to N distinct locations
1029/// (that AA can prove don't alias), perform M stores to other memory
1030/// locations that AA can prove don't alias any of the initial N locations, and
1031/// then load from all of the N locations. In this case, we insert M cache
1032/// entries for each of the N loads.
1033///
1034/// For example:
1035/// define i32 @foo() {
1036/// %a = alloca i32, align 4
1037/// %b = alloca i32, align 4
1038/// store i32 0, i32* %a, align 4
1039/// store i32 0, i32* %b, align 4
1040///
1041/// ; Insert M stores to other memory that doesn't alias %a or %b here
1042///
1043/// %c = load i32, i32* %a, align 4 ; Caches M entries in
1044/// ; CachedUpwardsClobberingAccess for the
1045/// ; MemoryLocation %a
1046/// %d = load i32, i32* %b, align 4 ; Caches M entries in
1047/// ; CachedUpwardsClobberingAccess for the
1048/// ; MemoryLocation %b
1049///
1050/// ; For completeness' sake, loading %a or %b again would not cache *another*
1051/// ; M entries.
1052/// %r = add i32 %c, %d
1053/// ret i32 %r
1054/// }
1055class MemorySSA::CachingWalker final : public MemorySSAWalker {
George Burgess IV5f308972016-07-19 01:29:15 +00001056 WalkerCache Cache;
1057 ClobberWalker Walker;
1058 bool AutoResetWalker;
1059
1060 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *, UpwardsMemoryQuery &);
1061 void verifyRemoved(MemoryAccess *);
1062
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001063public:
1064 CachingWalker(MemorySSA *, AliasAnalysis *, DominatorTree *);
1065 ~CachingWalker() override;
1066
George Burgess IV400ae402016-07-20 19:51:34 +00001067 using MemorySSAWalker::getClobberingMemoryAccess;
1068 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) override;
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001069 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
George Burgess IV013fd732016-10-28 19:22:46 +00001070 const MemoryLocation &) override;
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001071 void invalidateInfo(MemoryAccess *) override;
1072
George Burgess IV5f308972016-07-19 01:29:15 +00001073 /// Whether we call resetClobberWalker() after each time we *actually* walk to
1074 /// answer a clobber query.
1075 void setAutoResetWalker(bool AutoReset) { AutoResetWalker = AutoReset; }
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001076
Daniel Berlin7500c562017-04-01 08:59:45 +00001077 /// Drop the walker's persistent data structures.
George Burgess IV5f308972016-07-19 01:29:15 +00001078 void resetClobberWalker() { Walker.reset(); }
Geoff Berrycdf53332016-08-08 17:52:01 +00001079
1080 void verify(const MemorySSA *MSSA) override {
1081 MemorySSAWalker::verify(MSSA);
1082 Walker.verify(MSSA);
1083 }
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001084};
George Burgess IVe1100f52016-02-02 22:46:49 +00001085
Daniel Berlin78cbd282017-02-20 22:26:03 +00001086void MemorySSA::renameSuccessorPhis(BasicBlock *BB, MemoryAccess *IncomingVal,
1087 bool RenameAllUses) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001088 // Pass through values to our successors
1089 for (const BasicBlock *S : successors(BB)) {
1090 auto It = PerBlockAccesses.find(S);
1091 // Rename the phi nodes in our successor block
1092 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1093 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +00001094 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001095 auto *Phi = cast<MemoryPhi>(&Accesses->front());
Daniel Berlin78cbd282017-02-20 22:26:03 +00001096 if (RenameAllUses) {
1097 int PhiIndex = Phi->getBasicBlockIndex(BB);
1098 assert(PhiIndex != -1 && "Incomplete phi during partial rename");
1099 Phi->setIncomingValue(PhiIndex, IncomingVal);
1100 } else
1101 Phi->addIncoming(IncomingVal, BB);
George Burgess IVe1100f52016-02-02 22:46:49 +00001102 }
Daniel Berlin78cbd282017-02-20 22:26:03 +00001103}
George Burgess IVe1100f52016-02-02 22:46:49 +00001104
Daniel Berlin78cbd282017-02-20 22:26:03 +00001105/// \brief Rename a single basic block into MemorySSA form.
1106/// Uses the standard SSA renaming algorithm.
1107/// \returns The new incoming value.
1108MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB, MemoryAccess *IncomingVal,
1109 bool RenameAllUses) {
1110 auto It = PerBlockAccesses.find(BB);
1111 // Skip most processing if the list is empty.
1112 if (It != PerBlockAccesses.end()) {
1113 AccessList *Accesses = It->second.get();
1114 for (MemoryAccess &L : *Accesses) {
1115 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&L)) {
1116 if (MUD->getDefiningAccess() == nullptr || RenameAllUses)
1117 MUD->setDefiningAccess(IncomingVal);
1118 if (isa<MemoryDef>(&L))
1119 IncomingVal = &L;
1120 } else {
1121 IncomingVal = &L;
1122 }
1123 }
1124 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001125 return IncomingVal;
1126}
1127
1128/// \brief This is the standard SSA renaming algorithm.
1129///
1130/// We walk the dominator tree in preorder, renaming accesses, and then filling
1131/// in phi nodes in our successors.
1132void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
Daniel Berlin78cbd282017-02-20 22:26:03 +00001133 SmallPtrSetImpl<BasicBlock *> &Visited,
1134 bool SkipVisited, bool RenameAllUses) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001135 SmallVector<RenamePassData, 32> WorkStack;
Daniel Berlin78cbd282017-02-20 22:26:03 +00001136 // Skip everything if we already renamed this block and we are skipping.
1137 // Note: You can't sink this into the if, because we need it to occur
1138 // regardless of whether we skip blocks or not.
1139 bool AlreadyVisited = !Visited.insert(Root->getBlock()).second;
1140 if (SkipVisited && AlreadyVisited)
1141 return;
1142
1143 IncomingVal = renameBlock(Root->getBlock(), IncomingVal, RenameAllUses);
1144 renameSuccessorPhis(Root->getBlock(), IncomingVal, RenameAllUses);
George Burgess IVe1100f52016-02-02 22:46:49 +00001145 WorkStack.push_back({Root, Root->begin(), IncomingVal});
George Burgess IVe1100f52016-02-02 22:46:49 +00001146
1147 while (!WorkStack.empty()) {
1148 DomTreeNode *Node = WorkStack.back().DTN;
1149 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
1150 IncomingVal = WorkStack.back().IncomingVal;
1151
1152 if (ChildIt == Node->end()) {
1153 WorkStack.pop_back();
1154 } else {
1155 DomTreeNode *Child = *ChildIt;
1156 ++WorkStack.back().ChildIt;
1157 BasicBlock *BB = Child->getBlock();
Daniel Berlin78cbd282017-02-20 22:26:03 +00001158 // Note: You can't sink this into the if, because we need it to occur
1159 // regardless of whether we skip blocks or not.
1160 AlreadyVisited = !Visited.insert(BB).second;
1161 if (SkipVisited && AlreadyVisited) {
1162 // We already visited this during our renaming, which can happen when
1163 // being asked to rename multiple blocks. Figure out the incoming val,
1164 // which is the last def.
1165 // Incoming value can only change if there is a block def, and in that
1166 // case, it's the last block def in the list.
1167 if (auto *BlockDefs = getWritableBlockDefs(BB))
1168 IncomingVal = &*BlockDefs->rbegin();
1169 } else
1170 IncomingVal = renameBlock(BB, IncomingVal, RenameAllUses);
1171 renameSuccessorPhis(BB, IncomingVal, RenameAllUses);
George Burgess IVe1100f52016-02-02 22:46:49 +00001172 WorkStack.push_back({Child, Child->begin(), IncomingVal});
1173 }
1174 }
1175}
1176
1177/// \brief Compute dominator levels, used by the phi insertion algorithm above.
1178void MemorySSA::computeDomLevels(DenseMap<DomTreeNode *, unsigned> &DomLevels) {
1179 for (auto DFI = df_begin(DT->getRootNode()), DFE = df_end(DT->getRootNode());
1180 DFI != DFE; ++DFI)
1181 DomLevels[*DFI] = DFI.getPathLength() - 1;
1182}
1183
George Burgess IVa362b092016-07-06 00:28:43 +00001184/// \brief This handles unreachable block accesses by deleting phi nodes in
George Burgess IVe1100f52016-02-02 22:46:49 +00001185/// unreachable blocks, and marking all other unreachable MemoryAccess's as
1186/// being uses of the live on entry definition.
1187void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
1188 assert(!DT->isReachableFromEntry(BB) &&
1189 "Reachable block found while handling unreachable blocks");
1190
Daniel Berlinfc7e6512016-07-06 05:32:05 +00001191 // Make sure phi nodes in our reachable successors end up with a
1192 // LiveOnEntryDef for our incoming edge, even though our block is forward
1193 // unreachable. We could just disconnect these blocks from the CFG fully,
1194 // but we do not right now.
1195 for (const BasicBlock *S : successors(BB)) {
1196 if (!DT->isReachableFromEntry(S))
1197 continue;
1198 auto It = PerBlockAccesses.find(S);
1199 // Rename the phi nodes in our successor block
1200 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1201 continue;
1202 AccessList *Accesses = It->second.get();
1203 auto *Phi = cast<MemoryPhi>(&Accesses->front());
1204 Phi->addIncoming(LiveOnEntryDef.get(), BB);
1205 }
1206
George Burgess IVe1100f52016-02-02 22:46:49 +00001207 auto It = PerBlockAccesses.find(BB);
1208 if (It == PerBlockAccesses.end())
1209 return;
1210
1211 auto &Accesses = It->second;
1212 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1213 auto Next = std::next(AI);
1214 // If we have a phi, just remove it. We are going to replace all
1215 // users with live on entry.
1216 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1217 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1218 else
1219 Accesses->erase(AI);
1220 AI = Next;
1221 }
1222}
1223
Geoff Berryb96d3b22016-06-01 21:30:40 +00001224MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
1225 : AA(AA), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
Daniel Berlincd2deac2016-10-20 20:13:45 +00001226 NextID(INVALID_MEMORYACCESS_ID) {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001227 buildMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001228}
1229
George Burgess IVe1100f52016-02-02 22:46:49 +00001230MemorySSA::~MemorySSA() {
1231 // Drop all our references
1232 for (const auto &Pair : PerBlockAccesses)
1233 for (MemoryAccess &MA : *Pair.second)
1234 MA.dropAllReferences();
1235}
1236
Daniel Berlin14300262016-06-21 18:39:20 +00001237MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001238 auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
1239
1240 if (Res.second)
Daniel Berlinada263d2016-06-20 20:21:33 +00001241 Res.first->second = make_unique<AccessList>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001242 return Res.first->second.get();
1243}
Daniel Berlind602e042017-01-25 20:56:19 +00001244MemorySSA::DefsList *MemorySSA::getOrCreateDefsList(const BasicBlock *BB) {
1245 auto Res = PerBlockDefs.insert(std::make_pair(BB, nullptr));
1246
1247 if (Res.second)
1248 Res.first->second = make_unique<DefsList>();
1249 return Res.first->second.get();
1250}
George Burgess IVe1100f52016-02-02 22:46:49 +00001251
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001252/// This class is a batch walker of all MemoryUse's in the program, and points
1253/// their defining access at the thing that actually clobbers them. Because it
1254/// is a batch walker that touches everything, it does not operate like the
1255/// other walkers. This walker is basically performing a top-down SSA renaming
1256/// pass, where the version stack is used as the cache. This enables it to be
1257/// significantly more time and memory efficient than using the regular walker,
1258/// which is walking bottom-up.
1259class MemorySSA::OptimizeUses {
1260public:
1261 OptimizeUses(MemorySSA *MSSA, MemorySSAWalker *Walker, AliasAnalysis *AA,
1262 DominatorTree *DT)
1263 : MSSA(MSSA), Walker(Walker), AA(AA), DT(DT) {
1264 Walker = MSSA->getWalker();
1265 }
1266
1267 void optimizeUses();
1268
1269private:
1270 /// This represents where a given memorylocation is in the stack.
1271 struct MemlocStackInfo {
1272 // This essentially is keeping track of versions of the stack. Whenever
1273 // the stack changes due to pushes or pops, these versions increase.
1274 unsigned long StackEpoch;
1275 unsigned long PopEpoch;
1276 // This is the lower bound of places on the stack to check. It is equal to
1277 // the place the last stack walk ended.
1278 // Note: Correctness depends on this being initialized to 0, which densemap
1279 // does
1280 unsigned long LowerBound;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001281 const BasicBlock *LowerBoundBlock;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001282 // This is where the last walk for this memory location ended.
1283 unsigned long LastKill;
1284 bool LastKillValid;
1285 };
1286 void optimizeUsesInBlock(const BasicBlock *, unsigned long &, unsigned long &,
1287 SmallVectorImpl<MemoryAccess *> &,
1288 DenseMap<MemoryLocOrCall, MemlocStackInfo> &);
1289 MemorySSA *MSSA;
1290 MemorySSAWalker *Walker;
1291 AliasAnalysis *AA;
1292 DominatorTree *DT;
1293};
1294
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001295/// Optimize the uses in a given block This is basically the SSA renaming
1296/// algorithm, with one caveat: We are able to use a single stack for all
1297/// MemoryUses. This is because the set of *possible* reaching MemoryDefs is
1298/// the same for every MemoryUse. The *actual* clobbering MemoryDef is just
1299/// going to be some position in that stack of possible ones.
1300///
1301/// We track the stack positions that each MemoryLocation needs
1302/// to check, and last ended at. This is because we only want to check the
1303/// things that changed since last time. The same MemoryLocation should
1304/// get clobbered by the same store (getModRefInfo does not use invariantness or
1305/// things like this, and if they start, we can modify MemoryLocOrCall to
1306/// include relevant data)
1307void MemorySSA::OptimizeUses::optimizeUsesInBlock(
1308 const BasicBlock *BB, unsigned long &StackEpoch, unsigned long &PopEpoch,
1309 SmallVectorImpl<MemoryAccess *> &VersionStack,
1310 DenseMap<MemoryLocOrCall, MemlocStackInfo> &LocStackInfo) {
1311
1312 /// If no accesses, nothing to do.
1313 MemorySSA::AccessList *Accesses = MSSA->getWritableBlockAccesses(BB);
1314 if (Accesses == nullptr)
1315 return;
1316
1317 // Pop everything that doesn't dominate the current block off the stack,
1318 // increment the PopEpoch to account for this.
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001319 while (true) {
1320 assert(
1321 !VersionStack.empty() &&
1322 "Version stack should have liveOnEntry sentinel dominating everything");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001323 BasicBlock *BackBlock = VersionStack.back()->getBlock();
1324 if (DT->dominates(BackBlock, BB))
1325 break;
1326 while (VersionStack.back()->getBlock() == BackBlock)
1327 VersionStack.pop_back();
1328 ++PopEpoch;
1329 }
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001330
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001331 for (MemoryAccess &MA : *Accesses) {
1332 auto *MU = dyn_cast<MemoryUse>(&MA);
1333 if (!MU) {
1334 VersionStack.push_back(&MA);
1335 ++StackEpoch;
1336 continue;
1337 }
1338
George Burgess IV024f3d22016-08-03 19:57:02 +00001339 if (isUseTriviallyOptimizableToLiveOnEntry(*AA, MU->getMemoryInst())) {
Daniel Berlincd2deac2016-10-20 20:13:45 +00001340 MU->setDefiningAccess(MSSA->getLiveOnEntryDef(), true);
George Burgess IV024f3d22016-08-03 19:57:02 +00001341 continue;
1342 }
1343
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001344 MemoryLocOrCall UseMLOC(MU);
1345 auto &LocInfo = LocStackInfo[UseMLOC];
Daniel Berlin26fcea92016-08-02 20:02:21 +00001346 // If the pop epoch changed, it means we've removed stuff from top of
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001347 // stack due to changing blocks. We may have to reset the lower bound or
1348 // last kill info.
1349 if (LocInfo.PopEpoch != PopEpoch) {
1350 LocInfo.PopEpoch = PopEpoch;
1351 LocInfo.StackEpoch = StackEpoch;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001352 // If the lower bound was in something that no longer dominates us, we
1353 // have to reset it.
1354 // We can't simply track stack size, because the stack may have had
1355 // pushes/pops in the meantime.
1356 // XXX: This is non-optimal, but only is slower cases with heavily
1357 // branching dominator trees. To get the optimal number of queries would
1358 // be to make lowerbound and lastkill a per-loc stack, and pop it until
1359 // the top of that stack dominates us. This does not seem worth it ATM.
1360 // A much cheaper optimization would be to always explore the deepest
1361 // branch of the dominator tree first. This will guarantee this resets on
1362 // the smallest set of blocks.
1363 if (LocInfo.LowerBoundBlock && LocInfo.LowerBoundBlock != BB &&
Daniel Berlin1e98c042016-09-26 17:22:54 +00001364 !DT->dominates(LocInfo.LowerBoundBlock, BB)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001365 // Reset the lower bound of things to check.
1366 // TODO: Some day we should be able to reset to last kill, rather than
1367 // 0.
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001368 LocInfo.LowerBound = 0;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001369 LocInfo.LowerBoundBlock = VersionStack[0]->getBlock();
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001370 LocInfo.LastKillValid = false;
1371 }
1372 } else if (LocInfo.StackEpoch != StackEpoch) {
1373 // If all that has changed is the StackEpoch, we only have to check the
1374 // new things on the stack, because we've checked everything before. In
1375 // this case, the lower bound of things to check remains the same.
1376 LocInfo.PopEpoch = PopEpoch;
1377 LocInfo.StackEpoch = StackEpoch;
1378 }
1379 if (!LocInfo.LastKillValid) {
1380 LocInfo.LastKill = VersionStack.size() - 1;
1381 LocInfo.LastKillValid = true;
1382 }
1383
1384 // At this point, we should have corrected last kill and LowerBound to be
1385 // in bounds.
1386 assert(LocInfo.LowerBound < VersionStack.size() &&
1387 "Lower bound out of range");
1388 assert(LocInfo.LastKill < VersionStack.size() &&
1389 "Last kill info out of range");
1390 // In any case, the new upper bound is the top of the stack.
1391 unsigned long UpperBound = VersionStack.size() - 1;
1392
1393 if (UpperBound - LocInfo.LowerBound > MaxCheckLimit) {
Daniel Berlin26fcea92016-08-02 20:02:21 +00001394 DEBUG(dbgs() << "MemorySSA skipping optimization of " << *MU << " ("
1395 << *(MU->getMemoryInst()) << ")"
1396 << " because there are " << UpperBound - LocInfo.LowerBound
1397 << " stores to disambiguate\n");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001398 // Because we did not walk, LastKill is no longer valid, as this may
1399 // have been a kill.
1400 LocInfo.LastKillValid = false;
1401 continue;
1402 }
1403 bool FoundClobberResult = false;
1404 while (UpperBound > LocInfo.LowerBound) {
1405 if (isa<MemoryPhi>(VersionStack[UpperBound])) {
1406 // For phis, use the walker, see where we ended up, go there
1407 Instruction *UseInst = MU->getMemoryInst();
1408 MemoryAccess *Result = Walker->getClobberingMemoryAccess(UseInst);
1409 // We are guaranteed to find it or something is wrong
1410 while (VersionStack[UpperBound] != Result) {
1411 assert(UpperBound != 0);
1412 --UpperBound;
1413 }
1414 FoundClobberResult = true;
1415 break;
1416 }
1417
1418 MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]);
Daniel Berlindf101192016-08-03 00:01:46 +00001419 // If the lifetime of the pointer ends at this instruction, it's live on
1420 // entry.
1421 if (!UseMLOC.IsCall && lifetimeEndsAt(MD, UseMLOC.getLoc(), *AA)) {
1422 // Reset UpperBound to liveOnEntryDef's place in the stack
1423 UpperBound = 0;
1424 FoundClobberResult = true;
1425 break;
1426 }
Daniel Berlindff31de2016-08-02 21:57:52 +00001427 if (instructionClobbersQuery(MD, MU, UseMLOC, *AA)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001428 FoundClobberResult = true;
1429 break;
1430 }
1431 --UpperBound;
1432 }
1433 // At the end of this loop, UpperBound is either a clobber, or lower bound
1434 // PHI walking may cause it to be < LowerBound, and in fact, < LastKill.
1435 if (FoundClobberResult || UpperBound < LocInfo.LastKill) {
Daniel Berlincd2deac2016-10-20 20:13:45 +00001436 MU->setDefiningAccess(VersionStack[UpperBound], true);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001437 // We were last killed now by where we got to
1438 LocInfo.LastKill = UpperBound;
1439 } else {
1440 // Otherwise, we checked all the new ones, and now we know we can get to
1441 // LastKill.
Daniel Berlincd2deac2016-10-20 20:13:45 +00001442 MU->setDefiningAccess(VersionStack[LocInfo.LastKill], true);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001443 }
1444 LocInfo.LowerBound = VersionStack.size() - 1;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001445 LocInfo.LowerBoundBlock = BB;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001446 }
1447}
1448
1449/// Optimize uses to point to their actual clobbering definitions.
1450void MemorySSA::OptimizeUses::optimizeUses() {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001451 SmallVector<MemoryAccess *, 16> VersionStack;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001452 DenseMap<MemoryLocOrCall, MemlocStackInfo> LocStackInfo;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001453 VersionStack.push_back(MSSA->getLiveOnEntryDef());
1454
1455 unsigned long StackEpoch = 1;
1456 unsigned long PopEpoch = 1;
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001457 // We perform a non-recursive top-down dominator tree walk.
Daniel Berlin7ac3d742016-08-05 22:09:14 +00001458 for (const auto *DomNode : depth_first(DT->getRootNode()))
1459 optimizeUsesInBlock(DomNode->getBlock(), StackEpoch, PopEpoch, VersionStack,
1460 LocStackInfo);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001461}
1462
Daniel Berlin3d512a22016-08-22 19:14:30 +00001463void MemorySSA::placePHINodes(
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001464 const SmallPtrSetImpl<BasicBlock *> &DefiningBlocks,
1465 const DenseMap<const BasicBlock *, unsigned int> &BBNumbers) {
Daniel Berlin3d512a22016-08-22 19:14:30 +00001466 // Determine where our MemoryPhi's should go
1467 ForwardIDFCalculator IDFs(*DT);
1468 IDFs.setDefiningBlocks(DefiningBlocks);
Daniel Berlin3d512a22016-08-22 19:14:30 +00001469 SmallVector<BasicBlock *, 32> IDFBlocks;
1470 IDFs.calculate(IDFBlocks);
1471
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001472 std::sort(IDFBlocks.begin(), IDFBlocks.end(),
1473 [&BBNumbers](const BasicBlock *A, const BasicBlock *B) {
1474 return BBNumbers.lookup(A) < BBNumbers.lookup(B);
1475 });
1476
Daniel Berlin3d512a22016-08-22 19:14:30 +00001477 // Now place MemoryPhi nodes.
Daniel Berlind602e042017-01-25 20:56:19 +00001478 for (auto &BB : IDFBlocks)
1479 createMemoryPhi(BB);
Daniel Berlin3d512a22016-08-22 19:14:30 +00001480}
1481
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001482void MemorySSA::buildMemorySSA() {
George Burgess IVe1100f52016-02-02 22:46:49 +00001483 // We create an access to represent "live on entry", for things like
1484 // arguments or users of globals, where the memory they use is defined before
1485 // the beginning of the function. We do not actually insert it into the IR.
1486 // We do not define a live on exit for the immediate uses, and thus our
1487 // semantics do *not* imply that something with no immediate uses can simply
1488 // be removed.
1489 BasicBlock &StartingPoint = F.getEntryBlock();
1490 LiveOnEntryDef = make_unique<MemoryDef>(F.getContext(), nullptr, nullptr,
1491 &StartingPoint, NextID++);
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001492 DenseMap<const BasicBlock *, unsigned int> BBNumbers;
1493 unsigned NextBBNum = 0;
George Burgess IVe1100f52016-02-02 22:46:49 +00001494
1495 // We maintain lists of memory accesses per-block, trading memory for time. We
1496 // could just look up the memory access for every possible instruction in the
1497 // stream.
1498 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001499 SmallPtrSet<BasicBlock *, 32> DefUseBlocks;
George Burgess IVe1100f52016-02-02 22:46:49 +00001500 // Go through each block, figure out where defs occur, and chain together all
1501 // the accesses.
1502 for (BasicBlock &B : F) {
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001503 BBNumbers[&B] = NextBBNum++;
Daniel Berlin7898ca62016-02-07 01:52:15 +00001504 bool InsertIntoDef = false;
Daniel Berlinada263d2016-06-20 20:21:33 +00001505 AccessList *Accesses = nullptr;
Daniel Berlind602e042017-01-25 20:56:19 +00001506 DefsList *Defs = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +00001507 for (Instruction &I : B) {
Peter Collingbourneffecb142016-05-26 01:19:17 +00001508 MemoryUseOrDef *MUD = createNewAccess(&I);
George Burgess IVb42b7622016-03-11 19:34:03 +00001509 if (!MUD)
George Burgess IVe1100f52016-02-02 22:46:49 +00001510 continue;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001511
George Burgess IVe1100f52016-02-02 22:46:49 +00001512 if (!Accesses)
1513 Accesses = getOrCreateAccessList(&B);
George Burgess IVb42b7622016-03-11 19:34:03 +00001514 Accesses->push_back(MUD);
Daniel Berlind602e042017-01-25 20:56:19 +00001515 if (isa<MemoryDef>(MUD)) {
1516 InsertIntoDef = true;
1517 if (!Defs)
1518 Defs = getOrCreateDefsList(&B);
1519 Defs->push_back(*MUD);
1520 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001521 }
Daniel Berlin7898ca62016-02-07 01:52:15 +00001522 if (InsertIntoDef)
1523 DefiningBlocks.insert(&B);
George Burgess IV3887a412016-03-21 21:25:39 +00001524 if (Accesses)
Daniel Berlin1b51a292016-02-07 01:52:19 +00001525 DefUseBlocks.insert(&B);
1526 }
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001527 placePHINodes(DefiningBlocks, BBNumbers);
George Burgess IVe1100f52016-02-02 22:46:49 +00001528
1529 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
1530 // filled in with all blocks.
1531 SmallPtrSet<BasicBlock *, 16> Visited;
1532 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1533
George Burgess IV5f308972016-07-19 01:29:15 +00001534 CachingWalker *Walker = getWalkerImpl();
1535
1536 // We're doing a batch of updates; don't drop useful caches between them.
1537 Walker->setAutoResetWalker(false);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001538 OptimizeUses(this, Walker, AA, DT).optimizeUses();
George Burgess IV5f308972016-07-19 01:29:15 +00001539 Walker->setAutoResetWalker(true);
1540 Walker->resetClobberWalker();
1541
George Burgess IVe1100f52016-02-02 22:46:49 +00001542 // Mark the uses in unreachable blocks as live on entry, so that they go
1543 // somewhere.
1544 for (auto &BB : F)
1545 if (!Visited.count(&BB))
1546 markUnreachableAsLiveOnEntry(&BB);
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001547}
George Burgess IVe1100f52016-02-02 22:46:49 +00001548
George Burgess IV5f308972016-07-19 01:29:15 +00001549MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
1550
1551MemorySSA::CachingWalker *MemorySSA::getWalkerImpl() {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001552 if (Walker)
1553 return Walker.get();
1554
1555 Walker = make_unique<CachingWalker>(this, AA, DT);
Geoff Berryb96d3b22016-06-01 21:30:40 +00001556 return Walker.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001557}
1558
Daniel Berlind602e042017-01-25 20:56:19 +00001559// This is a helper function used by the creation routines. It places NewAccess
1560// into the access and defs lists for a given basic block, at the given
1561// insertion point.
1562void MemorySSA::insertIntoListsForBlock(MemoryAccess *NewAccess,
1563 const BasicBlock *BB,
1564 InsertionPlace Point) {
1565 auto *Accesses = getOrCreateAccessList(BB);
1566 if (Point == Beginning) {
1567 // If it's a phi node, it goes first, otherwise, it goes after any phi
1568 // nodes.
1569 if (isa<MemoryPhi>(NewAccess)) {
1570 Accesses->push_front(NewAccess);
1571 auto *Defs = getOrCreateDefsList(BB);
1572 Defs->push_front(*NewAccess);
1573 } else {
1574 auto AI = find_if_not(
1575 *Accesses, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1576 Accesses->insert(AI, NewAccess);
1577 if (!isa<MemoryUse>(NewAccess)) {
1578 auto *Defs = getOrCreateDefsList(BB);
1579 auto DI = find_if_not(
1580 *Defs, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1581 Defs->insert(DI, *NewAccess);
1582 }
1583 }
1584 } else {
1585 Accesses->push_back(NewAccess);
1586 if (!isa<MemoryUse>(NewAccess)) {
1587 auto *Defs = getOrCreateDefsList(BB);
1588 Defs->push_back(*NewAccess);
1589 }
1590 }
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001591 BlockNumberingValid.erase(BB);
Daniel Berlind602e042017-01-25 20:56:19 +00001592}
1593
1594void MemorySSA::insertIntoListsBefore(MemoryAccess *What, const BasicBlock *BB,
1595 AccessList::iterator InsertPt) {
1596 auto *Accesses = getWritableBlockAccesses(BB);
1597 bool WasEnd = InsertPt == Accesses->end();
1598 Accesses->insert(AccessList::iterator(InsertPt), What);
1599 if (!isa<MemoryUse>(What)) {
1600 auto *Defs = getOrCreateDefsList(BB);
1601 // If we got asked to insert at the end, we have an easy job, just shove it
1602 // at the end. If we got asked to insert before an existing def, we also get
1603 // an terator. If we got asked to insert before a use, we have to hunt for
1604 // the next def.
1605 if (WasEnd) {
1606 Defs->push_back(*What);
1607 } else if (isa<MemoryDef>(InsertPt)) {
1608 Defs->insert(InsertPt->getDefsIterator(), *What);
1609 } else {
1610 while (InsertPt != Accesses->end() && !isa<MemoryDef>(InsertPt))
1611 ++InsertPt;
1612 // Either we found a def, or we are inserting at the end
1613 if (InsertPt == Accesses->end())
1614 Defs->push_back(*What);
1615 else
1616 Defs->insert(InsertPt->getDefsIterator(), *What);
1617 }
1618 }
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001619 BlockNumberingValid.erase(BB);
Daniel Berlind602e042017-01-25 20:56:19 +00001620}
1621
Daniel Berlin60ead052017-01-28 01:23:13 +00001622// Move What before Where in the IR. The end result is taht What will belong to
1623// the right lists and have the right Block set, but will not otherwise be
1624// correct. It will not have the right defining access, and if it is a def,
1625// things below it will not properly be updated.
1626void MemorySSA::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
1627 AccessList::iterator Where) {
1628 // Keep it in the lookup tables, remove from the lists
1629 removeFromLists(What, false);
1630 What->setBlock(BB);
1631 insertIntoListsBefore(What, BB, Where);
1632}
1633
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001634void MemorySSA::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
1635 InsertionPlace Point) {
1636 removeFromLists(What, false);
1637 What->setBlock(BB);
1638 insertIntoListsForBlock(What, BB, Point);
1639}
1640
Daniel Berlin14300262016-06-21 18:39:20 +00001641MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
1642 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
Daniel Berlin14300262016-06-21 18:39:20 +00001643 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001644 // Phi's always are placed at the front of the block.
Daniel Berlind602e042017-01-25 20:56:19 +00001645 insertIntoListsForBlock(Phi, BB, Beginning);
Daniel Berlin5130cc82016-07-31 21:08:20 +00001646 ValueToMemoryAccess[BB] = Phi;
Daniel Berlin14300262016-06-21 18:39:20 +00001647 return Phi;
1648}
1649
1650MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
1651 MemoryAccess *Definition) {
1652 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
1653 MemoryUseOrDef *NewAccess = createNewAccess(I);
1654 assert(
1655 NewAccess != nullptr &&
1656 "Tried to create a memory access for a non-memory touching instruction");
1657 NewAccess->setDefiningAccess(Definition);
1658 return NewAccess;
1659}
1660
George Burgess IVe1100f52016-02-02 22:46:49 +00001661/// \brief Helper function to create new memory accesses
Peter Collingbourneffecb142016-05-26 01:19:17 +00001662MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I) {
Peter Collingbourneb9aa1f42016-05-26 04:58:46 +00001663 // The assume intrinsic has a control dependency which we model by claiming
1664 // that it writes arbitrarily. Ignore that fake memory dependency here.
1665 // FIXME: Replace this special casing with a more accurate modelling of
1666 // assume's control dependency.
1667 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1668 if (II->getIntrinsicID() == Intrinsic::assume)
1669 return nullptr;
1670
George Burgess IVe1100f52016-02-02 22:46:49 +00001671 // Find out what affect this instruction has on memory.
1672 ModRefInfo ModRef = AA->getModRefInfo(I);
1673 bool Def = bool(ModRef & MRI_Mod);
1674 bool Use = bool(ModRef & MRI_Ref);
1675
1676 // It's possible for an instruction to not modify memory at all. During
1677 // construction, we ignore them.
Peter Collingbourneffecb142016-05-26 01:19:17 +00001678 if (!Def && !Use)
George Burgess IVe1100f52016-02-02 22:46:49 +00001679 return nullptr;
1680
1681 assert((Def || Use) &&
1682 "Trying to create a memory access with a non-memory instruction");
1683
George Burgess IVb42b7622016-03-11 19:34:03 +00001684 MemoryUseOrDef *MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001685 if (Def)
George Burgess IVb42b7622016-03-11 19:34:03 +00001686 MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
George Burgess IVe1100f52016-02-02 22:46:49 +00001687 else
George Burgess IVb42b7622016-03-11 19:34:03 +00001688 MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
Daniel Berlin5130cc82016-07-31 21:08:20 +00001689 ValueToMemoryAccess[I] = MUD;
George Burgess IVb42b7622016-03-11 19:34:03 +00001690 return MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001691}
1692
George Burgess IVe1100f52016-02-02 22:46:49 +00001693/// \brief Returns true if \p Replacer dominates \p Replacee .
1694bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
1695 const MemoryAccess *Replacee) const {
1696 if (isa<MemoryUseOrDef>(Replacee))
1697 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
1698 const auto *MP = cast<MemoryPhi>(Replacee);
1699 // For a phi node, the use occurs in the predecessor block of the phi node.
1700 // Since we may occur multiple times in the phi node, we have to check each
1701 // operand to ensure Replacer dominates each operand where Replacee occurs.
1702 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +00001703 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +00001704 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
1705 return false;
1706 }
1707 return true;
1708}
1709
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001710/// \brief Properly remove \p MA from all of MemorySSA's lookup tables.
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001711void MemorySSA::removeFromLookups(MemoryAccess *MA) {
1712 assert(MA->use_empty() &&
1713 "Trying to remove memory access that still has uses");
Daniel Berlin5c46b942016-07-19 22:49:43 +00001714 BlockNumbering.erase(MA);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001715 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA))
1716 MUD->setDefiningAccess(nullptr);
1717 // Invalidate our walker's cache if necessary
1718 if (!isa<MemoryUse>(MA))
1719 Walker->invalidateInfo(MA);
1720 // The call below to erase will destroy MA, so we can't change the order we
1721 // are doing things here
1722 Value *MemoryInst;
1723 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
1724 MemoryInst = MUD->getMemoryInst();
1725 } else {
1726 MemoryInst = MA->getBlock();
1727 }
Daniel Berlin5130cc82016-07-31 21:08:20 +00001728 auto VMA = ValueToMemoryAccess.find(MemoryInst);
1729 if (VMA->second == MA)
1730 ValueToMemoryAccess.erase(VMA);
Daniel Berlin60ead052017-01-28 01:23:13 +00001731}
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001732
Daniel Berlin60ead052017-01-28 01:23:13 +00001733/// \brief Properly remove \p MA from all of MemorySSA's lists.
1734///
1735/// Because of the way the intrusive list and use lists work, it is important to
1736/// do removal in the right order.
1737/// ShouldDelete defaults to true, and will cause the memory access to also be
1738/// deleted, not just removed.
1739void MemorySSA::removeFromLists(MemoryAccess *MA, bool ShouldDelete) {
Daniel Berlind602e042017-01-25 20:56:19 +00001740 // The access list owns the reference, so we erase it from the non-owning list
1741 // first.
1742 if (!isa<MemoryUse>(MA)) {
1743 auto DefsIt = PerBlockDefs.find(MA->getBlock());
1744 std::unique_ptr<DefsList> &Defs = DefsIt->second;
1745 Defs->remove(*MA);
1746 if (Defs->empty())
1747 PerBlockDefs.erase(DefsIt);
1748 }
1749
Daniel Berlin60ead052017-01-28 01:23:13 +00001750 // The erase call here will delete it. If we don't want it deleted, we call
1751 // remove instead.
George Burgess IVe0e6e482016-03-02 02:35:04 +00001752 auto AccessIt = PerBlockAccesses.find(MA->getBlock());
Daniel Berlinada263d2016-06-20 20:21:33 +00001753 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
Daniel Berlin60ead052017-01-28 01:23:13 +00001754 if (ShouldDelete)
1755 Accesses->erase(MA);
1756 else
1757 Accesses->remove(MA);
1758
George Burgess IVe0e6e482016-03-02 02:35:04 +00001759 if (Accesses->empty())
1760 PerBlockAccesses.erase(AccessIt);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001761}
1762
George Burgess IVe1100f52016-02-02 22:46:49 +00001763void MemorySSA::print(raw_ostream &OS) const {
1764 MemorySSAAnnotatedWriter Writer(this);
1765 F.print(OS, &Writer);
1766}
1767
Matthias Braun8c209aa2017-01-28 02:02:38 +00001768#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Daniel Berlin78cbd282017-02-20 22:26:03 +00001769LLVM_DUMP_METHOD void MemorySSA::dump() const { print(dbgs()); }
Matthias Braun8c209aa2017-01-28 02:02:38 +00001770#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001771
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001772void MemorySSA::verifyMemorySSA() const {
1773 verifyDefUses(F);
1774 verifyDomination(F);
Daniel Berlin14300262016-06-21 18:39:20 +00001775 verifyOrdering(F);
Geoff Berrycdf53332016-08-08 17:52:01 +00001776 Walker->verify(this);
Daniel Berlin14300262016-06-21 18:39:20 +00001777}
1778
1779/// \brief Verify that the order and existence of MemoryAccesses matches the
1780/// order and existence of memory affecting instructions.
1781void MemorySSA::verifyOrdering(Function &F) const {
1782 // Walk all the blocks, comparing what the lookups think and what the access
1783 // lists think, as well as the order in the blocks vs the order in the access
1784 // lists.
1785 SmallVector<MemoryAccess *, 32> ActualAccesses;
Daniel Berlind602e042017-01-25 20:56:19 +00001786 SmallVector<MemoryAccess *, 32> ActualDefs;
Daniel Berlin14300262016-06-21 18:39:20 +00001787 for (BasicBlock &B : F) {
1788 const AccessList *AL = getBlockAccesses(&B);
Daniel Berlind602e042017-01-25 20:56:19 +00001789 const auto *DL = getBlockDefs(&B);
Daniel Berlin14300262016-06-21 18:39:20 +00001790 MemoryAccess *Phi = getMemoryAccess(&B);
Daniel Berlind602e042017-01-25 20:56:19 +00001791 if (Phi) {
Daniel Berlin14300262016-06-21 18:39:20 +00001792 ActualAccesses.push_back(Phi);
Daniel Berlind602e042017-01-25 20:56:19 +00001793 ActualDefs.push_back(Phi);
1794 }
1795
Daniel Berlin14300262016-06-21 18:39:20 +00001796 for (Instruction &I : B) {
1797 MemoryAccess *MA = getMemoryAccess(&I);
Daniel Berlind602e042017-01-25 20:56:19 +00001798 assert((!MA || (AL && (isa<MemoryUse>(MA) || DL))) &&
1799 "We have memory affecting instructions "
1800 "in this block but they are not in the "
1801 "access list or defs list");
1802 if (MA) {
Daniel Berlin14300262016-06-21 18:39:20 +00001803 ActualAccesses.push_back(MA);
Daniel Berlind602e042017-01-25 20:56:19 +00001804 if (isa<MemoryDef>(MA))
1805 ActualDefs.push_back(MA);
1806 }
Daniel Berlin14300262016-06-21 18:39:20 +00001807 }
1808 // Either we hit the assert, really have no accesses, or we have both
Daniel Berlind602e042017-01-25 20:56:19 +00001809 // accesses and an access list.
1810 // Same with defs.
1811 if (!AL && !DL)
Daniel Berlin14300262016-06-21 18:39:20 +00001812 continue;
1813 assert(AL->size() == ActualAccesses.size() &&
1814 "We don't have the same number of accesses in the block as on the "
1815 "access list");
Davide Italiano6c77de02017-01-30 03:16:43 +00001816 assert((DL || ActualDefs.size() == 0) &&
1817 "Either we should have a defs list, or we should have no defs");
Daniel Berlind602e042017-01-25 20:56:19 +00001818 assert((!DL || DL->size() == ActualDefs.size()) &&
1819 "We don't have the same number of defs in the block as on the "
1820 "def list");
Daniel Berlin14300262016-06-21 18:39:20 +00001821 auto ALI = AL->begin();
1822 auto AAI = ActualAccesses.begin();
1823 while (ALI != AL->end() && AAI != ActualAccesses.end()) {
1824 assert(&*ALI == *AAI && "Not the same accesses in the same order");
1825 ++ALI;
1826 ++AAI;
1827 }
1828 ActualAccesses.clear();
Daniel Berlind602e042017-01-25 20:56:19 +00001829 if (DL) {
1830 auto DLI = DL->begin();
1831 auto ADI = ActualDefs.begin();
1832 while (DLI != DL->end() && ADI != ActualDefs.end()) {
1833 assert(&*DLI == *ADI && "Not the same defs in the same order");
1834 ++DLI;
1835 ++ADI;
1836 }
1837 }
1838 ActualDefs.clear();
Daniel Berlin14300262016-06-21 18:39:20 +00001839 }
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001840}
1841
George Burgess IVe1100f52016-02-02 22:46:49 +00001842/// \brief Verify the domination properties of MemorySSA by checking that each
1843/// definition dominates all of its uses.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001844void MemorySSA::verifyDomination(Function &F) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001845#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001846 for (BasicBlock &B : F) {
1847 // Phi nodes are attached to basic blocks
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001848 if (MemoryPhi *MP = getMemoryAccess(&B))
1849 for (const Use &U : MP->uses())
1850 assert(dominates(MP, U) && "Memory PHI does not dominate it's uses");
Daniel Berlin7af95872016-08-05 21:47:20 +00001851
George Burgess IVe1100f52016-02-02 22:46:49 +00001852 for (Instruction &I : B) {
1853 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
1854 if (!MD)
1855 continue;
1856
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001857 for (const Use &U : MD->uses())
1858 assert(dominates(MD, U) && "Memory Def does not dominate it's uses");
George Burgess IVe1100f52016-02-02 22:46:49 +00001859 }
1860 }
Daniel Berlin7af95872016-08-05 21:47:20 +00001861#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001862}
1863
1864/// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use
1865/// appears in the use list of \p Def.
Daniel Berlin7af95872016-08-05 21:47:20 +00001866
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001867void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001868#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001869 // The live on entry use may cause us to get a NULL def here
Daniel Berlin7af95872016-08-05 21:47:20 +00001870 if (!Def)
1871 assert(isLiveOnEntryDef(Use) &&
1872 "Null def but use not point to live on entry def");
1873 else
Daniel Berlinda2f38e2016-08-11 21:26:50 +00001874 assert(is_contained(Def->users(), Use) &&
Daniel Berlin7af95872016-08-05 21:47:20 +00001875 "Did not find use in def's use list");
1876#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001877}
1878
1879/// \brief Verify the immediate use information, by walking all the memory
1880/// accesses and verifying that, for each use, it appears in the
1881/// appropriate def's use list
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001882void MemorySSA::verifyDefUses(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001883 for (BasicBlock &B : F) {
1884 // Phi nodes are attached to basic blocks
Daniel Berlin14300262016-06-21 18:39:20 +00001885 if (MemoryPhi *Phi = getMemoryAccess(&B)) {
David Majnemer580e7542016-06-25 00:04:06 +00001886 assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
1887 pred_begin(&B), pred_end(&B))) &&
Daniel Berlin14300262016-06-21 18:39:20 +00001888 "Incomplete MemoryPhi Node");
George Burgess IVe1100f52016-02-02 22:46:49 +00001889 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
1890 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
Daniel Berlin14300262016-06-21 18:39:20 +00001891 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001892
1893 for (Instruction &I : B) {
George Burgess IV66837ab2016-11-01 21:17:46 +00001894 if (MemoryUseOrDef *MA = getMemoryAccess(&I)) {
1895 verifyUseInDefs(MA->getDefiningAccess(), MA);
George Burgess IVe1100f52016-02-02 22:46:49 +00001896 }
1897 }
1898 }
1899}
1900
George Burgess IV66837ab2016-11-01 21:17:46 +00001901MemoryUseOrDef *MemorySSA::getMemoryAccess(const Instruction *I) const {
1902 return cast_or_null<MemoryUseOrDef>(ValueToMemoryAccess.lookup(I));
George Burgess IVe1100f52016-02-02 22:46:49 +00001903}
1904
1905MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const {
George Burgess IV66837ab2016-11-01 21:17:46 +00001906 return cast_or_null<MemoryPhi>(ValueToMemoryAccess.lookup(cast<Value>(BB)));
George Burgess IVe1100f52016-02-02 22:46:49 +00001907}
1908
Daniel Berlin5c46b942016-07-19 22:49:43 +00001909/// Perform a local numbering on blocks so that instruction ordering can be
1910/// determined in constant time.
1911/// TODO: We currently just number in order. If we numbered by N, we could
1912/// allow at least N-1 sequences of insertBefore or insertAfter (and at least
1913/// log2(N) sequences of mixed before and after) without needing to invalidate
1914/// the numbering.
1915void MemorySSA::renumberBlock(const BasicBlock *B) const {
1916 // The pre-increment ensures the numbers really start at 1.
1917 unsigned long CurrentNumber = 0;
1918 const AccessList *AL = getBlockAccesses(B);
1919 assert(AL != nullptr && "Asking to renumber an empty block");
1920 for (const auto &I : *AL)
1921 BlockNumbering[&I] = ++CurrentNumber;
1922 BlockNumberingValid.insert(B);
1923}
1924
George Burgess IVe1100f52016-02-02 22:46:49 +00001925/// \brief Determine, for two memory accesses in the same block,
1926/// whether \p Dominator dominates \p Dominatee.
1927/// \returns True if \p Dominator dominates \p Dominatee.
1928bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
1929 const MemoryAccess *Dominatee) const {
Sebastian Pope1f60b12016-06-10 21:36:41 +00001930
Daniel Berlin5c46b942016-07-19 22:49:43 +00001931 const BasicBlock *DominatorBlock = Dominator->getBlock();
Daniel Berlin5c46b942016-07-19 22:49:43 +00001932
Daniel Berlin19860302016-07-19 23:08:08 +00001933 assert((DominatorBlock == Dominatee->getBlock()) &&
Daniel Berlin5c46b942016-07-19 22:49:43 +00001934 "Asking for local domination when accesses are in different blocks!");
Sebastian Pope1f60b12016-06-10 21:36:41 +00001935 // A node dominates itself.
1936 if (Dominatee == Dominator)
1937 return true;
1938
1939 // When Dominatee is defined on function entry, it is not dominated by another
1940 // memory access.
1941 if (isLiveOnEntryDef(Dominatee))
1942 return false;
1943
1944 // When Dominator is defined on function entry, it dominates the other memory
1945 // access.
1946 if (isLiveOnEntryDef(Dominator))
1947 return true;
1948
Daniel Berlin5c46b942016-07-19 22:49:43 +00001949 if (!BlockNumberingValid.count(DominatorBlock))
1950 renumberBlock(DominatorBlock);
George Burgess IVe1100f52016-02-02 22:46:49 +00001951
Daniel Berlin5c46b942016-07-19 22:49:43 +00001952 unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
1953 // All numbers start with 1
1954 assert(DominatorNum != 0 && "Block was not numbered properly");
1955 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
1956 assert(DominateeNum != 0 && "Block was not numbered properly");
1957 return DominatorNum < DominateeNum;
George Burgess IVe1100f52016-02-02 22:46:49 +00001958}
1959
George Burgess IV5f308972016-07-19 01:29:15 +00001960bool MemorySSA::dominates(const MemoryAccess *Dominator,
1961 const MemoryAccess *Dominatee) const {
1962 if (Dominator == Dominatee)
1963 return true;
1964
1965 if (isLiveOnEntryDef(Dominatee))
1966 return false;
1967
1968 if (Dominator->getBlock() != Dominatee->getBlock())
1969 return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
1970 return locallyDominates(Dominator, Dominatee);
1971}
1972
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001973bool MemorySSA::dominates(const MemoryAccess *Dominator,
1974 const Use &Dominatee) const {
1975 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Dominatee.getUser())) {
1976 BasicBlock *UseBB = MP->getIncomingBlock(Dominatee);
1977 // The def must dominate the incoming block of the phi.
1978 if (UseBB != Dominator->getBlock())
1979 return DT->dominates(Dominator->getBlock(), UseBB);
1980 // If the UseBB and the DefBB are the same, compare locally.
1981 return locallyDominates(Dominator, cast<MemoryAccess>(Dominatee));
1982 }
1983 // If it's not a PHI node use, the normal dominates can already handle it.
1984 return dominates(Dominator, cast<MemoryAccess>(Dominatee.getUser()));
1985}
1986
George Burgess IVe1100f52016-02-02 22:46:49 +00001987const static char LiveOnEntryStr[] = "liveOnEntry";
1988
1989void MemoryDef::print(raw_ostream &OS) const {
1990 MemoryAccess *UO = getDefiningAccess();
1991
1992 OS << getID() << " = MemoryDef(";
1993 if (UO && UO->getID())
1994 OS << UO->getID();
1995 else
1996 OS << LiveOnEntryStr;
1997 OS << ')';
1998}
1999
2000void MemoryPhi::print(raw_ostream &OS) const {
2001 bool First = true;
2002 OS << getID() << " = MemoryPhi(";
2003 for (const auto &Op : operands()) {
2004 BasicBlock *BB = getIncomingBlock(Op);
2005 MemoryAccess *MA = cast<MemoryAccess>(Op);
2006 if (!First)
2007 OS << ',';
2008 else
2009 First = false;
2010
2011 OS << '{';
2012 if (BB->hasName())
2013 OS << BB->getName();
2014 else
2015 BB->printAsOperand(OS, false);
2016 OS << ',';
2017 if (unsigned ID = MA->getID())
2018 OS << ID;
2019 else
2020 OS << LiveOnEntryStr;
2021 OS << '}';
2022 }
2023 OS << ')';
2024}
2025
2026MemoryAccess::~MemoryAccess() {}
2027
2028void MemoryUse::print(raw_ostream &OS) const {
2029 MemoryAccess *UO = getDefiningAccess();
2030 OS << "MemoryUse(";
2031 if (UO && UO->getID())
2032 OS << UO->getID();
2033 else
2034 OS << LiveOnEntryStr;
2035 OS << ')';
2036}
2037
2038void MemoryAccess::dump() const {
Daniel Berlin78cbd282017-02-20 22:26:03 +00002039// Cannot completely remove virtual function even in release mode.
Matthias Braun8c209aa2017-01-28 02:02:38 +00002040#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
George Burgess IVe1100f52016-02-02 22:46:49 +00002041 print(dbgs());
2042 dbgs() << "\n";
Matthias Braun8c209aa2017-01-28 02:02:38 +00002043#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00002044}
2045
Chad Rosier232e29e2016-07-06 21:20:47 +00002046char MemorySSAPrinterLegacyPass::ID = 0;
2047
2048MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) {
2049 initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
2050}
2051
2052void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
2053 AU.setPreservesAll();
2054 AU.addRequired<MemorySSAWrapperPass>();
2055 AU.addPreserved<MemorySSAWrapperPass>();
2056}
2057
2058bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) {
2059 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
2060 MSSA.print(dbgs());
2061 if (VerifyMemorySSA)
2062 MSSA.verifyMemorySSA();
2063 return false;
2064}
2065
Chandler Carruthdab4eae2016-11-23 17:53:26 +00002066AnalysisKey MemorySSAAnalysis::Key;
George Burgess IVe1100f52016-02-02 22:46:49 +00002067
Daniel Berlin1e98c042016-09-26 17:22:54 +00002068MemorySSAAnalysis::Result MemorySSAAnalysis::run(Function &F,
2069 FunctionAnalysisManager &AM) {
Geoff Berryb96d3b22016-06-01 21:30:40 +00002070 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2071 auto &AA = AM.getResult<AAManager>(F);
Geoff Berry290a13e2016-08-08 18:27:22 +00002072 return MemorySSAAnalysis::Result(make_unique<MemorySSA>(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00002073}
2074
Geoff Berryb96d3b22016-06-01 21:30:40 +00002075PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
2076 FunctionAnalysisManager &AM) {
2077 OS << "MemorySSA for function: " << F.getName() << "\n";
Geoff Berry290a13e2016-08-08 18:27:22 +00002078 AM.getResult<MemorySSAAnalysis>(F).getMSSA().print(OS);
Geoff Berryb96d3b22016-06-01 21:30:40 +00002079
2080 return PreservedAnalyses::all();
George Burgess IVe1100f52016-02-02 22:46:49 +00002081}
2082
Geoff Berryb96d3b22016-06-01 21:30:40 +00002083PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
2084 FunctionAnalysisManager &AM) {
Geoff Berry290a13e2016-08-08 18:27:22 +00002085 AM.getResult<MemorySSAAnalysis>(F).getMSSA().verifyMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00002086
2087 return PreservedAnalyses::all();
2088}
2089
2090char MemorySSAWrapperPass::ID = 0;
2091
2092MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
2093 initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
2094}
2095
2096void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
2097
2098void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00002099 AU.setPreservesAll();
Geoff Berryb96d3b22016-06-01 21:30:40 +00002100 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
2101 AU.addRequiredTransitive<AAResultsWrapperPass>();
George Burgess IVe1100f52016-02-02 22:46:49 +00002102}
2103
Geoff Berryb96d3b22016-06-01 21:30:40 +00002104bool MemorySSAWrapperPass::runOnFunction(Function &F) {
2105 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2106 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2107 MSSA.reset(new MemorySSA(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00002108 return false;
2109}
2110
Geoff Berryb96d3b22016-06-01 21:30:40 +00002111void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); }
George Burgess IVe1100f52016-02-02 22:46:49 +00002112
Geoff Berryb96d3b22016-06-01 21:30:40 +00002113void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00002114 MSSA->print(OS);
2115}
2116
George Burgess IVe1100f52016-02-02 22:46:49 +00002117MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
2118
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002119MemorySSA::CachingWalker::CachingWalker(MemorySSA *M, AliasAnalysis *A,
2120 DominatorTree *D)
Daniel Berlin5c46b942016-07-19 22:49:43 +00002121 : MemorySSAWalker(M), Walker(*M, *A, *D, Cache), AutoResetWalker(true) {}
George Burgess IVe1100f52016-02-02 22:46:49 +00002122
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002123MemorySSA::CachingWalker::~CachingWalker() {}
George Burgess IVe1100f52016-02-02 22:46:49 +00002124
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002125void MemorySSA::CachingWalker::invalidateInfo(MemoryAccess *MA) {
Daniel Berlin83fc77b2016-03-01 18:46:54 +00002126 // TODO: We can do much better cache invalidation with differently stored
2127 // caches. For now, for MemoryUses, we simply remove them
2128 // from the cache, and kill the entire call/non-call cache for everything
2129 // else. The problem is for phis or defs, currently we'd need to follow use
2130 // chains down and invalidate anything below us in the chain that currently
2131 // terminates at this access.
2132
2133 // See if this is a MemoryUse, if so, just remove the cached info. MemoryUse
2134 // is by definition never a barrier, so nothing in the cache could point to
2135 // this use. In that case, we only need invalidate the info for the use
2136 // itself.
2137
2138 if (MemoryUse *MU = dyn_cast<MemoryUse>(MA)) {
George Burgess IV5f308972016-07-19 01:29:15 +00002139 UpwardsMemoryQuery Q(MU->getMemoryInst(), MU);
2140 Cache.remove(MU, Q.StartingLoc, Q.IsCall);
Daniel Berlincd2deac2016-10-20 20:13:45 +00002141 MU->resetOptimized();
Geoff Berry9fe26e62016-04-22 14:44:10 +00002142 } else {
2143 // 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 +00002144 Cache.clear();
Geoff Berry9fe26e62016-04-22 14:44:10 +00002145 }
2146
Filipe Cabecinhas0da99372016-04-29 15:22:48 +00002147#ifdef EXPENSIVE_CHECKS
Geoff Berry9fe26e62016-04-22 14:44:10 +00002148 verifyRemoved(MA);
2149#endif
Daniel Berlin83fc77b2016-03-01 18:46:54 +00002150}
2151
George Burgess IVe1100f52016-02-02 22:46:49 +00002152/// \brief Walk the use-def chains starting at \p MA and find
2153/// the MemoryAccess that actually clobbers Loc.
2154///
2155/// \returns our clobbering memory access
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002156MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
2157 MemoryAccess *StartingAccess, UpwardsMemoryQuery &Q) {
George Burgess IV5f308972016-07-19 01:29:15 +00002158 MemoryAccess *New = Walker.findClobber(StartingAccess, Q);
2159#ifdef EXPENSIVE_CHECKS
2160 MemoryAccess *NewNoCache =
2161 Walker.findClobber(StartingAccess, Q, /*UseWalkerCache=*/false);
2162 assert(NewNoCache == New && "Cache made us hand back a different result?");
2163#endif
2164 if (AutoResetWalker)
2165 resetClobberWalker();
2166 return New;
George Burgess IVe1100f52016-02-02 22:46:49 +00002167}
2168
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002169MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
George Burgess IV013fd732016-10-28 19:22:46 +00002170 MemoryAccess *StartingAccess, const MemoryLocation &Loc) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002171 if (isa<MemoryPhi>(StartingAccess))
2172 return StartingAccess;
2173
2174 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
2175 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
2176 return StartingUseOrDef;
2177
2178 Instruction *I = StartingUseOrDef->getMemoryInst();
2179
2180 // Conservatively, fences are always clobbers, so don't perform the walk if we
2181 // hit a fence.
David Majnemera940f362016-07-15 17:19:24 +00002182 if (!ImmutableCallSite(I) && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002183 return StartingUseOrDef;
2184
2185 UpwardsMemoryQuery Q;
2186 Q.OriginalAccess = StartingUseOrDef;
2187 Q.StartingLoc = Loc;
George Burgess IV5f308972016-07-19 01:29:15 +00002188 Q.Inst = I;
George Burgess IVe1100f52016-02-02 22:46:49 +00002189 Q.IsCall = false;
George Burgess IVe1100f52016-02-02 22:46:49 +00002190
George Burgess IV5f308972016-07-19 01:29:15 +00002191 if (auto *CacheResult = Cache.lookup(StartingUseOrDef, Loc, Q.IsCall))
George Burgess IVe1100f52016-02-02 22:46:49 +00002192 return CacheResult;
2193
2194 // Unlike the other function, do not walk to the def of a def, because we are
2195 // handed something we already believe is the clobbering access.
2196 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
2197 ? StartingUseOrDef->getDefiningAccess()
2198 : StartingUseOrDef;
2199
2200 MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00002201 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2202 DEBUG(dbgs() << *StartingUseOrDef << "\n");
2203 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2204 DEBUG(dbgs() << *Clobber << "\n");
2205 return Clobber;
2206}
2207
2208MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002209MemorySSA::CachingWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
2210 auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
2211 // If this is a MemoryPhi, we can't do anything.
2212 if (!StartingAccess)
2213 return MA;
George Burgess IVe1100f52016-02-02 22:46:49 +00002214
Daniel Berlincd2deac2016-10-20 20:13:45 +00002215 // If this is an already optimized use or def, return the optimized result.
2216 // Note: Currently, we do not store the optimized def result because we'd need
2217 // a separate field, since we can't use it as the defining access.
2218 if (MemoryUse *MU = dyn_cast<MemoryUse>(StartingAccess))
2219 if (MU->isOptimized())
2220 return MU->getDefiningAccess();
2221
George Burgess IV400ae402016-07-20 19:51:34 +00002222 const Instruction *I = StartingAccess->getMemoryInst();
George Burgess IV5f308972016-07-19 01:29:15 +00002223 UpwardsMemoryQuery Q(I, StartingAccess);
David Majnemera940f362016-07-15 17:19:24 +00002224 // We can't sanely do anything with a fences, they conservatively
George Burgess IVe1100f52016-02-02 22:46:49 +00002225 // clobber all memory, and have no locations to get pointers from to
David Majnemera940f362016-07-15 17:19:24 +00002226 // try to disambiguate.
George Burgess IV5f308972016-07-19 01:29:15 +00002227 if (!Q.IsCall && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002228 return StartingAccess;
2229
George Burgess IV5f308972016-07-19 01:29:15 +00002230 if (auto *CacheResult = Cache.lookup(StartingAccess, Q.StartingLoc, Q.IsCall))
George Burgess IVe1100f52016-02-02 22:46:49 +00002231 return CacheResult;
2232
George Burgess IV024f3d22016-08-03 19:57:02 +00002233 if (isUseTriviallyOptimizableToLiveOnEntry(*MSSA->AA, I)) {
2234 MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef();
2235 Cache.insert(StartingAccess, LiveOnEntry, Q.StartingLoc, Q.IsCall);
Daniel Berlincd2deac2016-10-20 20:13:45 +00002236 if (MemoryUse *MU = dyn_cast<MemoryUse>(StartingAccess))
2237 MU->setDefiningAccess(LiveOnEntry, true);
George Burgess IV024f3d22016-08-03 19:57:02 +00002238 return LiveOnEntry;
2239 }
2240
George Burgess IVe1100f52016-02-02 22:46:49 +00002241 // Start with the thing we already think clobbers this location
2242 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
2243
2244 // At this point, DefiningAccess may be the live on entry def.
2245 // If it is, we will not get a better result.
2246 if (MSSA->isLiveOnEntryDef(DefiningAccess))
2247 return DefiningAccess;
2248
2249 MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00002250 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2251 DEBUG(dbgs() << *DefiningAccess << "\n");
2252 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2253 DEBUG(dbgs() << *Result << "\n");
Daniel Berlincd2deac2016-10-20 20:13:45 +00002254 if (MemoryUse *MU = dyn_cast<MemoryUse>(StartingAccess))
2255 MU->setDefiningAccess(Result, true);
George Burgess IVe1100f52016-02-02 22:46:49 +00002256
2257 return Result;
2258}
2259
Geoff Berry9fe26e62016-04-22 14:44:10 +00002260// Verify that MA doesn't exist in any of the caches.
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002261void MemorySSA::CachingWalker::verifyRemoved(MemoryAccess *MA) {
George Burgess IV5f308972016-07-19 01:29:15 +00002262 assert(!Cache.contains(MA) && "Found removed MemoryAccess in cache.");
Geoff Berry9fe26e62016-04-22 14:44:10 +00002263}
2264
George Burgess IVe1100f52016-02-02 22:46:49 +00002265MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002266DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002267 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
2268 return Use->getDefiningAccess();
2269 return MA;
2270}
2271
2272MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
George Burgess IV013fd732016-10-28 19:22:46 +00002273 MemoryAccess *StartingAccess, const MemoryLocation &) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002274 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
2275 return Use->getDefiningAccess();
2276 return StartingAccess;
2277}
George Burgess IV5f308972016-07-19 01:29:15 +00002278} // namespace llvm