blob: 35a63bf9d3dfe62bc5042279fef253e13174ec48 [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
Daniel Berlind0420312017-04-01 09:01:12 +0000541 MemoryAccess *lookupCache(const MemoryAccess *MA,
542 const MemoryLocation &Loc) const {
George Burgess IV5f308972016-07-19 01:29:15 +0000543 return shouldIgnoreCache() ? nullptr : WC.lookup(MA, Loc, Query->IsCall);
544 }
545
546 void cacheDefPath(const DefPath &DN, MemoryAccess *Target) const {
547 if (shouldIgnoreCache())
548 return;
549
550 for (MemoryAccess *MA : def_chain(DN.First, DN.Last))
551 addCacheEntry(MA, Target, DN.Loc);
552
553 // DefPaths only express the path we walked. So, DN.Last could either be a
554 // thing we want to cache, or not.
555 if (DN.Last != Target)
556 addCacheEntry(DN.Last, Target, DN.Loc);
557 }
558
559 /// Find the nearest def or phi that `From` can legally be optimized to.
Daniel Berlind0420312017-04-01 09:01:12 +0000560 const MemoryAccess *getWalkTarget(const MemoryPhi *From) const {
George Burgess IV5f308972016-07-19 01:29:15 +0000561 assert(From->getNumOperands() && "Phi with no operands?");
562
563 BasicBlock *BB = From->getBlock();
George Burgess IV5f308972016-07-19 01:29:15 +0000564 MemoryAccess *Result = MSSA.getLiveOnEntryDef();
565 DomTreeNode *Node = DT.getNode(BB);
566 while ((Node = Node->getIDom())) {
Daniel Berlin7500c562017-04-01 08:59:45 +0000567 auto *Defs = MSSA.getBlockDefs(Node->getBlock());
568 if (Defs)
Daniel Berlind0420312017-04-01 09:01:12 +0000569 return &*Defs->rbegin();
George Burgess IV5f308972016-07-19 01:29:15 +0000570 }
George Burgess IV5f308972016-07-19 01:29:15 +0000571 return Result;
572 }
573
574 /// Result of calling walkToPhiOrClobber.
575 struct UpwardsWalkResult {
576 /// The "Result" of the walk. Either a clobber, the last thing we walked, or
577 /// both.
578 MemoryAccess *Result;
579 bool IsKnownClobber;
580 bool FromCache;
581 };
582
583 /// Walk to the next Phi or Clobber in the def chain starting at Desc.Last.
584 /// This will update Desc.Last as it walks. It will (optionally) also stop at
585 /// StopAt.
586 ///
587 /// This does not test for whether StopAt is a clobber
Daniel Berlind0420312017-04-01 09:01:12 +0000588 UpwardsWalkResult
589 walkToPhiOrClobber(DefPath &Desc,
590 const MemoryAccess *StopAt = nullptr) const {
George Burgess IV5f308972016-07-19 01:29:15 +0000591 assert(!isa<MemoryUse>(Desc.Last) && "Uses don't exist in my world");
592
593 for (MemoryAccess *Current : def_chain(Desc.Last)) {
594 Desc.Last = Current;
595 if (Current == StopAt)
596 return {Current, false, false};
597
598 if (auto *MD = dyn_cast<MemoryDef>(Current))
599 if (MSSA.isLiveOnEntryDef(MD) ||
Daniel Berlinc43aa5a2016-08-02 16:24:03 +0000600 instructionClobbersQuery(MD, Desc.Loc, Query->Inst, AA))
George Burgess IV5f308972016-07-19 01:29:15 +0000601 return {MD, true, false};
602
603 // Cache checks must be done last, because if Current is a clobber, the
604 // cache will contain the clobber for Current.
605 if (MemoryAccess *MA = lookupCache(Current, Desc.Loc))
606 return {MA, true, true};
607 }
608
609 assert(isa<MemoryPhi>(Desc.Last) &&
610 "Ended at a non-clobber that's not a phi?");
611 return {Desc.Last, false, false};
612 }
613
614 void addSearches(MemoryPhi *Phi, SmallVectorImpl<ListIndex> &PausedSearches,
615 ListIndex PriorNode) {
616 auto UpwardDefs = make_range(upward_defs_begin({Phi, Paths[PriorNode].Loc}),
617 upward_defs_end());
618 for (const MemoryAccessPair &P : UpwardDefs) {
619 PausedSearches.push_back(Paths.size());
620 Paths.emplace_back(P.second, P.first, PriorNode);
621 }
622 }
623
624 /// Represents a search that terminated after finding a clobber. This clobber
625 /// may or may not be present in the path of defs from LastNode..SearchStart,
626 /// since it may have been retrieved from cache.
627 struct TerminatedPath {
628 MemoryAccess *Clobber;
629 ListIndex LastNode;
630 };
631
632 /// Get an access that keeps us from optimizing to the given phi.
633 ///
634 /// PausedSearches is an array of indices into the Paths array. Its incoming
635 /// value is the indices of searches that stopped at the last phi optimization
636 /// target. It's left in an unspecified state.
637 ///
638 /// If this returns None, NewPaused is a vector of searches that terminated
639 /// at StopWhere. Otherwise, NewPaused is left in an unspecified state.
George Burgess IV14633b52016-08-03 01:22:19 +0000640 Optional<TerminatedPath>
Daniel Berlind0420312017-04-01 09:01:12 +0000641 getBlockingAccess(const MemoryAccess *StopWhere,
George Burgess IV5f308972016-07-19 01:29:15 +0000642 SmallVectorImpl<ListIndex> &PausedSearches,
643 SmallVectorImpl<ListIndex> &NewPaused,
644 SmallVectorImpl<TerminatedPath> &Terminated) {
645 assert(!PausedSearches.empty() && "No searches to continue?");
646
647 // BFS vs DFS really doesn't make a difference here, so just do a DFS with
648 // PausedSearches as our stack.
649 while (!PausedSearches.empty()) {
650 ListIndex PathIndex = PausedSearches.pop_back_val();
651 DefPath &Node = Paths[PathIndex];
652
653 // If we've already visited this path with this MemoryLocation, we don't
654 // need to do so again.
655 //
656 // NOTE: That we just drop these paths on the ground makes caching
657 // behavior sporadic. e.g. given a diamond:
658 // A
659 // B C
660 // D
661 //
662 // ...If we walk D, B, A, C, we'll only cache the result of phi
663 // optimization for A, B, and D; C will be skipped because it dies here.
664 // This arguably isn't the worst thing ever, since:
665 // - We generally query things in a top-down order, so if we got below D
666 // without needing cache entries for {C, MemLoc}, then chances are
667 // that those cache entries would end up ultimately unused.
668 // - We still cache things for A, so C only needs to walk up a bit.
669 // If this behavior becomes problematic, we can fix without a ton of extra
670 // work.
671 if (!VisitedPhis.insert({Node.Last, Node.Loc}).second)
672 continue;
673
674 UpwardsWalkResult Res = walkToPhiOrClobber(Node, /*StopAt=*/StopWhere);
675 if (Res.IsKnownClobber) {
676 assert(Res.Result != StopWhere || Res.FromCache);
677 // If this wasn't a cache hit, we hit a clobber when walking. That's a
678 // failure.
George Burgess IV14633b52016-08-03 01:22:19 +0000679 TerminatedPath Term{Res.Result, PathIndex};
George Burgess IV5f308972016-07-19 01:29:15 +0000680 if (!Res.FromCache || !MSSA.dominates(Res.Result, StopWhere))
George Burgess IV14633b52016-08-03 01:22:19 +0000681 return Term;
George Burgess IV5f308972016-07-19 01:29:15 +0000682
683 // Otherwise, it's a valid thing to potentially optimize to.
George Burgess IV14633b52016-08-03 01:22:19 +0000684 Terminated.push_back(Term);
George Burgess IV5f308972016-07-19 01:29:15 +0000685 continue;
686 }
687
688 if (Res.Result == StopWhere) {
689 // We've hit our target. Save this path off for if we want to continue
690 // walking.
691 NewPaused.push_back(PathIndex);
692 continue;
693 }
694
695 assert(!MSSA.isLiveOnEntryDef(Res.Result) && "liveOnEntry is a clobber");
696 addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
697 }
698
699 return None;
700 }
701
702 template <typename T, typename Walker>
703 struct generic_def_path_iterator
704 : public iterator_facade_base<generic_def_path_iterator<T, Walker>,
705 std::forward_iterator_tag, T *> {
706 generic_def_path_iterator() : W(nullptr), N(None) {}
707 generic_def_path_iterator(Walker *W, ListIndex N) : W(W), N(N) {}
708
709 T &operator*() const { return curNode(); }
710
711 generic_def_path_iterator &operator++() {
712 N = curNode().Previous;
713 return *this;
714 }
715
716 bool operator==(const generic_def_path_iterator &O) const {
717 if (N.hasValue() != O.N.hasValue())
718 return false;
719 return !N.hasValue() || *N == *O.N;
720 }
721
722 private:
723 T &curNode() const { return W->Paths[*N]; }
724
725 Walker *W;
726 Optional<ListIndex> N;
727 };
728
729 using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
730 using const_def_path_iterator =
731 generic_def_path_iterator<const DefPath, const ClobberWalker>;
732
733 iterator_range<def_path_iterator> def_path(ListIndex From) {
734 return make_range(def_path_iterator(this, From), def_path_iterator());
735 }
736
737 iterator_range<const_def_path_iterator> const_def_path(ListIndex From) const {
738 return make_range(const_def_path_iterator(this, From),
739 const_def_path_iterator());
740 }
741
742 struct OptznResult {
743 /// The path that contains our result.
744 TerminatedPath PrimaryClobber;
745 /// The paths that we can legally cache back from, but that aren't
746 /// necessarily the result of the Phi optimization.
747 SmallVector<TerminatedPath, 4> OtherClobbers;
748 };
749
750 ListIndex defPathIndex(const DefPath &N) const {
751 // The assert looks nicer if we don't need to do &N
752 const DefPath *NP = &N;
753 assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
754 "Out of bounds DefPath!");
755 return NP - &Paths.front();
756 }
757
758 /// Try to optimize a phi as best as we can. Returns a SmallVector of Paths
759 /// that act as legal clobbers. Note that this won't return *all* clobbers.
760 ///
761 /// Phi optimization algorithm tl;dr:
762 /// - Find the earliest def/phi, A, we can optimize to
763 /// - Find if all paths from the starting memory access ultimately reach A
764 /// - If not, optimization isn't possible.
765 /// - Otherwise, walk from A to another clobber or phi, A'.
766 /// - If A' is a def, we're done.
767 /// - If A' is a phi, try to optimize it.
768 ///
769 /// A path is a series of {MemoryAccess, MemoryLocation} pairs. A path
770 /// terminates when a MemoryAccess that clobbers said MemoryLocation is found.
771 OptznResult tryOptimizePhi(MemoryPhi *Phi, MemoryAccess *Start,
772 const MemoryLocation &Loc) {
773 assert(Paths.empty() && VisitedPhis.empty() &&
774 "Reset the optimization state.");
775
776 Paths.emplace_back(Loc, Start, Phi, None);
777 // Stores how many "valid" optimization nodes we had prior to calling
778 // addSearches/getBlockingAccess. Necessary for caching if we had a blocker.
779 auto PriorPathsSize = Paths.size();
780
781 SmallVector<ListIndex, 16> PausedSearches;
782 SmallVector<ListIndex, 8> NewPaused;
783 SmallVector<TerminatedPath, 4> TerminatedPaths;
784
785 addSearches(Phi, PausedSearches, 0);
786
787 // Moves the TerminatedPath with the "most dominated" Clobber to the end of
788 // Paths.
789 auto MoveDominatedPathToEnd = [&](SmallVectorImpl<TerminatedPath> &Paths) {
790 assert(!Paths.empty() && "Need a path to move");
George Burgess IV5f308972016-07-19 01:29:15 +0000791 auto Dom = Paths.begin();
792 for (auto I = std::next(Dom), E = Paths.end(); I != E; ++I)
793 if (!MSSA.dominates(I->Clobber, Dom->Clobber))
794 Dom = I;
795 auto Last = Paths.end() - 1;
796 if (Last != Dom)
797 std::iter_swap(Last, Dom);
798 };
799
800 MemoryPhi *Current = Phi;
801 while (1) {
802 assert(!MSSA.isLiveOnEntryDef(Current) &&
803 "liveOnEntry wasn't treated as a clobber?");
804
Daniel Berlind0420312017-04-01 09:01:12 +0000805 const auto *Target = getWalkTarget(Current);
George Burgess IV5f308972016-07-19 01:29:15 +0000806 // If a TerminatedPath doesn't dominate Target, then it wasn't a legal
807 // optimization for the prior phi.
808 assert(all_of(TerminatedPaths, [&](const TerminatedPath &P) {
809 return MSSA.dominates(P.Clobber, Target);
810 }));
811
812 // FIXME: This is broken, because the Blocker may be reported to be
813 // liveOnEntry, and we'll happily wait for that to disappear (read: never)
George Burgess IV7f414b92016-08-22 23:40:01 +0000814 // For the moment, this is fine, since we do nothing with blocker info.
George Burgess IV14633b52016-08-03 01:22:19 +0000815 if (Optional<TerminatedPath> Blocker = getBlockingAccess(
George Burgess IV5f308972016-07-19 01:29:15 +0000816 Target, PausedSearches, NewPaused, TerminatedPaths)) {
George Burgess IV5f308972016-07-19 01:29:15 +0000817 // Cache our work on the blocking node, since we know that's correct.
George Burgess IV14633b52016-08-03 01:22:19 +0000818 cacheDefPath(Paths[Blocker->LastNode], Blocker->Clobber);
George Burgess IV5f308972016-07-19 01:29:15 +0000819
820 // Find the node we started at. We can't search based on N->Last, since
821 // we may have gone around a loop with a different MemoryLocation.
George Burgess IV14633b52016-08-03 01:22:19 +0000822 auto Iter = find_if(def_path(Blocker->LastNode), [&](const DefPath &N) {
George Burgess IV5f308972016-07-19 01:29:15 +0000823 return defPathIndex(N) < PriorPathsSize;
824 });
825 assert(Iter != def_path_iterator());
826
827 DefPath &CurNode = *Iter;
828 assert(CurNode.Last == Current);
George Burgess IV5f308972016-07-19 01:29:15 +0000829
830 // Two things:
831 // A. We can't reliably cache all of NewPaused back. Consider a case
832 // where we have two paths in NewPaused; one of which can't optimize
833 // above this phi, whereas the other can. If we cache the second path
834 // back, we'll end up with suboptimal cache entries. We can handle
835 // cases like this a bit better when we either try to find all
836 // clobbers that block phi optimization, or when our cache starts
837 // supporting unfinished searches.
838 // B. We can't reliably cache TerminatedPaths back here without doing
839 // extra checks; consider a case like:
840 // T
841 // / \
842 // D C
843 // \ /
844 // S
845 // Where T is our target, C is a node with a clobber on it, D is a
846 // diamond (with a clobber *only* on the left or right node, N), and
847 // S is our start. Say we walk to D, through the node opposite N
848 // (read: ignoring the clobber), and see a cache entry in the top
849 // node of D. That cache entry gets put into TerminatedPaths. We then
850 // walk up to C (N is later in our worklist), find the clobber, and
851 // quit. If we append TerminatedPaths to OtherClobbers, we'll cache
852 // the bottom part of D to the cached clobber, ignoring the clobber
853 // in N. Again, this problem goes away if we start tracking all
854 // blockers for a given phi optimization.
855 TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
856 return {Result, {}};
857 }
858
859 // If there's nothing left to search, then all paths led to valid clobbers
860 // that we got from our cache; pick the nearest to the start, and allow
861 // the rest to be cached back.
862 if (NewPaused.empty()) {
863 MoveDominatedPathToEnd(TerminatedPaths);
864 TerminatedPath Result = TerminatedPaths.pop_back_val();
865 return {Result, std::move(TerminatedPaths)};
866 }
867
868 MemoryAccess *DefChainEnd = nullptr;
869 SmallVector<TerminatedPath, 4> Clobbers;
870 for (ListIndex Paused : NewPaused) {
871 UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
872 if (WR.IsKnownClobber)
873 Clobbers.push_back({WR.Result, Paused});
874 else
875 // Micro-opt: If we hit the end of the chain, save it.
876 DefChainEnd = WR.Result;
877 }
878
879 if (!TerminatedPaths.empty()) {
880 // If we couldn't find the dominating phi/liveOnEntry in the above loop,
881 // do it now.
882 if (!DefChainEnd)
Daniel Berlind0420312017-04-01 09:01:12 +0000883 for (auto *MA : def_chain(const_cast<MemoryAccess *>(Target)))
George Burgess IV5f308972016-07-19 01:29:15 +0000884 DefChainEnd = MA;
885
886 // If any of the terminated paths don't dominate the phi we'll try to
887 // optimize, we need to figure out what they are and quit.
888 const BasicBlock *ChainBB = DefChainEnd->getBlock();
889 for (const TerminatedPath &TP : TerminatedPaths) {
890 // Because we know that DefChainEnd is as "high" as we can go, we
891 // don't need local dominance checks; BB dominance is sufficient.
892 if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
893 Clobbers.push_back(TP);
894 }
895 }
896
897 // If we have clobbers in the def chain, find the one closest to Current
898 // and quit.
899 if (!Clobbers.empty()) {
900 MoveDominatedPathToEnd(Clobbers);
901 TerminatedPath Result = Clobbers.pop_back_val();
902 return {Result, std::move(Clobbers)};
903 }
904
905 assert(all_of(NewPaused,
906 [&](ListIndex I) { return Paths[I].Last == DefChainEnd; }));
907
908 // Because liveOnEntry is a clobber, this must be a phi.
909 auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
910
911 PriorPathsSize = Paths.size();
912 PausedSearches.clear();
913 for (ListIndex I : NewPaused)
914 addSearches(DefChainPhi, PausedSearches, I);
915 NewPaused.clear();
916
917 Current = DefChainPhi;
918 }
919 }
920
921 /// Caches everything in an OptznResult.
922 void cacheOptResult(const OptznResult &R) {
923 if (R.OtherClobbers.empty()) {
924 // If we're not going to be caching OtherClobbers, don't bother with
925 // marking visited/etc.
926 for (const DefPath &N : const_def_path(R.PrimaryClobber.LastNode))
927 cacheDefPath(N, R.PrimaryClobber.Clobber);
928 return;
929 }
930
931 // PrimaryClobber is our answer. If we can cache anything back, we need to
932 // stop caching when we visit PrimaryClobber.
933 SmallBitVector Visited(Paths.size());
934 for (const DefPath &N : const_def_path(R.PrimaryClobber.LastNode)) {
935 Visited[defPathIndex(N)] = true;
936 cacheDefPath(N, R.PrimaryClobber.Clobber);
937 }
938
939 for (const TerminatedPath &P : R.OtherClobbers) {
940 for (const DefPath &N : const_def_path(P.LastNode)) {
941 ListIndex NIndex = defPathIndex(N);
942 if (Visited[NIndex])
943 break;
944 Visited[NIndex] = true;
945 cacheDefPath(N, P.Clobber);
946 }
947 }
948 }
949
950 void verifyOptResult(const OptznResult &R) const {
951 assert(all_of(R.OtherClobbers, [&](const TerminatedPath &P) {
952 return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
953 }));
954 }
955
956 void resetPhiOptznState() {
957 Paths.clear();
958 VisitedPhis.clear();
959 }
960
961public:
962 ClobberWalker(const MemorySSA &MSSA, AliasAnalysis &AA, DominatorTree &DT,
963 WalkerCache &WC)
964 : MSSA(MSSA), AA(AA), DT(DT), WC(WC), UseCache(true) {}
965
Daniel Berlin7500c562017-04-01 08:59:45 +0000966 void reset() {}
George Burgess IV5f308972016-07-19 01:29:15 +0000967
968 /// Finds the nearest clobber for the given query, optimizing phis if
969 /// possible.
970 MemoryAccess *findClobber(MemoryAccess *Start, UpwardsMemoryQuery &Q,
971 bool UseWalkerCache = true) {
972 setUseCache(UseWalkerCache);
973 Query = &Q;
974
975 MemoryAccess *Current = Start;
976 // This walker pretends uses don't exist. If we're handed one, silently grab
977 // its def. (This has the nice side-effect of ensuring we never cache uses)
978 if (auto *MU = dyn_cast<MemoryUse>(Start))
979 Current = MU->getDefiningAccess();
980
981 DefPath FirstDesc(Q.StartingLoc, Current, Current, None);
982 // Fast path for the overly-common case (no crazy phi optimization
983 // necessary)
984 UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
George Burgess IV93ea19b2016-07-24 07:03:49 +0000985 MemoryAccess *Result;
George Burgess IV5f308972016-07-19 01:29:15 +0000986 if (WalkResult.IsKnownClobber) {
987 cacheDefPath(FirstDesc, WalkResult.Result);
George Burgess IV93ea19b2016-07-24 07:03:49 +0000988 Result = WalkResult.Result;
989 } else {
990 OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
991 Current, Q.StartingLoc);
992 verifyOptResult(OptRes);
993 cacheOptResult(OptRes);
994 resetPhiOptznState();
995 Result = OptRes.PrimaryClobber.Clobber;
George Burgess IV5f308972016-07-19 01:29:15 +0000996 }
997
George Burgess IV5f308972016-07-19 01:29:15 +0000998#ifdef EXPENSIVE_CHECKS
George Burgess IV93ea19b2016-07-24 07:03:49 +0000999 checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, AA);
George Burgess IV5f308972016-07-19 01:29:15 +00001000#endif
George Burgess IV93ea19b2016-07-24 07:03:49 +00001001 return Result;
George Burgess IV5f308972016-07-19 01:29:15 +00001002 }
Geoff Berrycdf53332016-08-08 17:52:01 +00001003
1004 void verify(const MemorySSA *MSSA) { assert(MSSA == &this->MSSA); }
George Burgess IV5f308972016-07-19 01:29:15 +00001005};
1006
1007struct RenamePassData {
1008 DomTreeNode *DTN;
1009 DomTreeNode::const_iterator ChildIt;
1010 MemoryAccess *IncomingVal;
1011
1012 RenamePassData(DomTreeNode *D, DomTreeNode::const_iterator It,
1013 MemoryAccess *M)
1014 : DTN(D), ChildIt(It), IncomingVal(M) {}
1015 void swap(RenamePassData &RHS) {
1016 std::swap(DTN, RHS.DTN);
1017 std::swap(ChildIt, RHS.ChildIt);
1018 std::swap(IncomingVal, RHS.IncomingVal);
1019 }
1020};
1021} // anonymous namespace
1022
1023namespace llvm {
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001024/// \brief A MemorySSAWalker that does AA walks and caching of lookups to
1025/// disambiguate accesses.
1026///
1027/// FIXME: The current implementation of this can take quadratic space in rare
1028/// cases. This can be fixed, but it is something to note until it is fixed.
1029///
1030/// In order to trigger this behavior, you need to store to N distinct locations
1031/// (that AA can prove don't alias), perform M stores to other memory
1032/// locations that AA can prove don't alias any of the initial N locations, and
1033/// then load from all of the N locations. In this case, we insert M cache
1034/// entries for each of the N loads.
1035///
1036/// For example:
1037/// define i32 @foo() {
1038/// %a = alloca i32, align 4
1039/// %b = alloca i32, align 4
1040/// store i32 0, i32* %a, align 4
1041/// store i32 0, i32* %b, align 4
1042///
1043/// ; Insert M stores to other memory that doesn't alias %a or %b here
1044///
1045/// %c = load i32, i32* %a, align 4 ; Caches M entries in
1046/// ; CachedUpwardsClobberingAccess for the
1047/// ; MemoryLocation %a
1048/// %d = load i32, i32* %b, align 4 ; Caches M entries in
1049/// ; CachedUpwardsClobberingAccess for the
1050/// ; MemoryLocation %b
1051///
1052/// ; For completeness' sake, loading %a or %b again would not cache *another*
1053/// ; M entries.
1054/// %r = add i32 %c, %d
1055/// ret i32 %r
1056/// }
1057class MemorySSA::CachingWalker final : public MemorySSAWalker {
George Burgess IV5f308972016-07-19 01:29:15 +00001058 WalkerCache Cache;
1059 ClobberWalker Walker;
1060 bool AutoResetWalker;
1061
1062 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *, UpwardsMemoryQuery &);
1063 void verifyRemoved(MemoryAccess *);
1064
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001065public:
1066 CachingWalker(MemorySSA *, AliasAnalysis *, DominatorTree *);
1067 ~CachingWalker() override;
1068
George Burgess IV400ae402016-07-20 19:51:34 +00001069 using MemorySSAWalker::getClobberingMemoryAccess;
1070 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *) override;
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001071 MemoryAccess *getClobberingMemoryAccess(MemoryAccess *,
George Burgess IV013fd732016-10-28 19:22:46 +00001072 const MemoryLocation &) override;
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001073 void invalidateInfo(MemoryAccess *) override;
1074
George Burgess IV5f308972016-07-19 01:29:15 +00001075 /// Whether we call resetClobberWalker() after each time we *actually* walk to
1076 /// answer a clobber query.
1077 void setAutoResetWalker(bool AutoReset) { AutoResetWalker = AutoReset; }
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001078
Daniel Berlin7500c562017-04-01 08:59:45 +00001079 /// Drop the walker's persistent data structures.
George Burgess IV5f308972016-07-19 01:29:15 +00001080 void resetClobberWalker() { Walker.reset(); }
Geoff Berrycdf53332016-08-08 17:52:01 +00001081
1082 void verify(const MemorySSA *MSSA) override {
1083 MemorySSAWalker::verify(MSSA);
1084 Walker.verify(MSSA);
1085 }
George Burgess IVfd1f2f82016-06-24 21:02:12 +00001086};
George Burgess IVe1100f52016-02-02 22:46:49 +00001087
Daniel Berlin78cbd282017-02-20 22:26:03 +00001088void MemorySSA::renameSuccessorPhis(BasicBlock *BB, MemoryAccess *IncomingVal,
1089 bool RenameAllUses) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001090 // Pass through values to our successors
1091 for (const BasicBlock *S : successors(BB)) {
1092 auto It = PerBlockAccesses.find(S);
1093 // Rename the phi nodes in our successor block
1094 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1095 continue;
Daniel Berlinada263d2016-06-20 20:21:33 +00001096 AccessList *Accesses = It->second.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001097 auto *Phi = cast<MemoryPhi>(&Accesses->front());
Daniel Berlin78cbd282017-02-20 22:26:03 +00001098 if (RenameAllUses) {
1099 int PhiIndex = Phi->getBasicBlockIndex(BB);
1100 assert(PhiIndex != -1 && "Incomplete phi during partial rename");
1101 Phi->setIncomingValue(PhiIndex, IncomingVal);
1102 } else
1103 Phi->addIncoming(IncomingVal, BB);
George Burgess IVe1100f52016-02-02 22:46:49 +00001104 }
Daniel Berlin78cbd282017-02-20 22:26:03 +00001105}
George Burgess IVe1100f52016-02-02 22:46:49 +00001106
Daniel Berlin78cbd282017-02-20 22:26:03 +00001107/// \brief Rename a single basic block into MemorySSA form.
1108/// Uses the standard SSA renaming algorithm.
1109/// \returns The new incoming value.
1110MemoryAccess *MemorySSA::renameBlock(BasicBlock *BB, MemoryAccess *IncomingVal,
1111 bool RenameAllUses) {
1112 auto It = PerBlockAccesses.find(BB);
1113 // Skip most processing if the list is empty.
1114 if (It != PerBlockAccesses.end()) {
1115 AccessList *Accesses = It->second.get();
1116 for (MemoryAccess &L : *Accesses) {
1117 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&L)) {
1118 if (MUD->getDefiningAccess() == nullptr || RenameAllUses)
1119 MUD->setDefiningAccess(IncomingVal);
1120 if (isa<MemoryDef>(&L))
1121 IncomingVal = &L;
1122 } else {
1123 IncomingVal = &L;
1124 }
1125 }
1126 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001127 return IncomingVal;
1128}
1129
1130/// \brief This is the standard SSA renaming algorithm.
1131///
1132/// We walk the dominator tree in preorder, renaming accesses, and then filling
1133/// in phi nodes in our successors.
1134void MemorySSA::renamePass(DomTreeNode *Root, MemoryAccess *IncomingVal,
Daniel Berlin78cbd282017-02-20 22:26:03 +00001135 SmallPtrSetImpl<BasicBlock *> &Visited,
1136 bool SkipVisited, bool RenameAllUses) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001137 SmallVector<RenamePassData, 32> WorkStack;
Daniel Berlin78cbd282017-02-20 22:26:03 +00001138 // Skip everything if we already renamed this block and we are skipping.
1139 // Note: You can't sink this into the if, because we need it to occur
1140 // regardless of whether we skip blocks or not.
1141 bool AlreadyVisited = !Visited.insert(Root->getBlock()).second;
1142 if (SkipVisited && AlreadyVisited)
1143 return;
1144
1145 IncomingVal = renameBlock(Root->getBlock(), IncomingVal, RenameAllUses);
1146 renameSuccessorPhis(Root->getBlock(), IncomingVal, RenameAllUses);
George Burgess IVe1100f52016-02-02 22:46:49 +00001147 WorkStack.push_back({Root, Root->begin(), IncomingVal});
George Burgess IVe1100f52016-02-02 22:46:49 +00001148
1149 while (!WorkStack.empty()) {
1150 DomTreeNode *Node = WorkStack.back().DTN;
1151 DomTreeNode::const_iterator ChildIt = WorkStack.back().ChildIt;
1152 IncomingVal = WorkStack.back().IncomingVal;
1153
1154 if (ChildIt == Node->end()) {
1155 WorkStack.pop_back();
1156 } else {
1157 DomTreeNode *Child = *ChildIt;
1158 ++WorkStack.back().ChildIt;
1159 BasicBlock *BB = Child->getBlock();
Daniel Berlin78cbd282017-02-20 22:26:03 +00001160 // Note: You can't sink this into the if, because we need it to occur
1161 // regardless of whether we skip blocks or not.
1162 AlreadyVisited = !Visited.insert(BB).second;
1163 if (SkipVisited && AlreadyVisited) {
1164 // We already visited this during our renaming, which can happen when
1165 // being asked to rename multiple blocks. Figure out the incoming val,
1166 // which is the last def.
1167 // Incoming value can only change if there is a block def, and in that
1168 // case, it's the last block def in the list.
1169 if (auto *BlockDefs = getWritableBlockDefs(BB))
1170 IncomingVal = &*BlockDefs->rbegin();
1171 } else
1172 IncomingVal = renameBlock(BB, IncomingVal, RenameAllUses);
1173 renameSuccessorPhis(BB, IncomingVal, RenameAllUses);
George Burgess IVe1100f52016-02-02 22:46:49 +00001174 WorkStack.push_back({Child, Child->begin(), IncomingVal});
1175 }
1176 }
1177}
1178
1179/// \brief Compute dominator levels, used by the phi insertion algorithm above.
1180void MemorySSA::computeDomLevels(DenseMap<DomTreeNode *, unsigned> &DomLevels) {
1181 for (auto DFI = df_begin(DT->getRootNode()), DFE = df_end(DT->getRootNode());
1182 DFI != DFE; ++DFI)
1183 DomLevels[*DFI] = DFI.getPathLength() - 1;
1184}
1185
George Burgess IVa362b092016-07-06 00:28:43 +00001186/// \brief This handles unreachable block accesses by deleting phi nodes in
George Burgess IVe1100f52016-02-02 22:46:49 +00001187/// unreachable blocks, and marking all other unreachable MemoryAccess's as
1188/// being uses of the live on entry definition.
1189void MemorySSA::markUnreachableAsLiveOnEntry(BasicBlock *BB) {
1190 assert(!DT->isReachableFromEntry(BB) &&
1191 "Reachable block found while handling unreachable blocks");
1192
Daniel Berlinfc7e6512016-07-06 05:32:05 +00001193 // Make sure phi nodes in our reachable successors end up with a
1194 // LiveOnEntryDef for our incoming edge, even though our block is forward
1195 // unreachable. We could just disconnect these blocks from the CFG fully,
1196 // but we do not right now.
1197 for (const BasicBlock *S : successors(BB)) {
1198 if (!DT->isReachableFromEntry(S))
1199 continue;
1200 auto It = PerBlockAccesses.find(S);
1201 // Rename the phi nodes in our successor block
1202 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1203 continue;
1204 AccessList *Accesses = It->second.get();
1205 auto *Phi = cast<MemoryPhi>(&Accesses->front());
1206 Phi->addIncoming(LiveOnEntryDef.get(), BB);
1207 }
1208
George Burgess IVe1100f52016-02-02 22:46:49 +00001209 auto It = PerBlockAccesses.find(BB);
1210 if (It == PerBlockAccesses.end())
1211 return;
1212
1213 auto &Accesses = It->second;
1214 for (auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1215 auto Next = std::next(AI);
1216 // If we have a phi, just remove it. We are going to replace all
1217 // users with live on entry.
1218 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1219 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1220 else
1221 Accesses->erase(AI);
1222 AI = Next;
1223 }
1224}
1225
Geoff Berryb96d3b22016-06-01 21:30:40 +00001226MemorySSA::MemorySSA(Function &Func, AliasAnalysis *AA, DominatorTree *DT)
1227 : AA(AA), DT(DT), F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
Daniel Berlincd2deac2016-10-20 20:13:45 +00001228 NextID(INVALID_MEMORYACCESS_ID) {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001229 buildMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00001230}
1231
George Burgess IVe1100f52016-02-02 22:46:49 +00001232MemorySSA::~MemorySSA() {
1233 // Drop all our references
1234 for (const auto &Pair : PerBlockAccesses)
1235 for (MemoryAccess &MA : *Pair.second)
1236 MA.dropAllReferences();
1237}
1238
Daniel Berlin14300262016-06-21 18:39:20 +00001239MemorySSA::AccessList *MemorySSA::getOrCreateAccessList(const BasicBlock *BB) {
George Burgess IVe1100f52016-02-02 22:46:49 +00001240 auto Res = PerBlockAccesses.insert(std::make_pair(BB, nullptr));
1241
1242 if (Res.second)
Daniel Berlinada263d2016-06-20 20:21:33 +00001243 Res.first->second = make_unique<AccessList>();
George Burgess IVe1100f52016-02-02 22:46:49 +00001244 return Res.first->second.get();
1245}
Daniel Berlind602e042017-01-25 20:56:19 +00001246MemorySSA::DefsList *MemorySSA::getOrCreateDefsList(const BasicBlock *BB) {
1247 auto Res = PerBlockDefs.insert(std::make_pair(BB, nullptr));
1248
1249 if (Res.second)
1250 Res.first->second = make_unique<DefsList>();
1251 return Res.first->second.get();
1252}
George Burgess IVe1100f52016-02-02 22:46:49 +00001253
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001254/// This class is a batch walker of all MemoryUse's in the program, and points
1255/// their defining access at the thing that actually clobbers them. Because it
1256/// is a batch walker that touches everything, it does not operate like the
1257/// other walkers. This walker is basically performing a top-down SSA renaming
1258/// pass, where the version stack is used as the cache. This enables it to be
1259/// significantly more time and memory efficient than using the regular walker,
1260/// which is walking bottom-up.
1261class MemorySSA::OptimizeUses {
1262public:
1263 OptimizeUses(MemorySSA *MSSA, MemorySSAWalker *Walker, AliasAnalysis *AA,
1264 DominatorTree *DT)
1265 : MSSA(MSSA), Walker(Walker), AA(AA), DT(DT) {
1266 Walker = MSSA->getWalker();
1267 }
1268
1269 void optimizeUses();
1270
1271private:
1272 /// This represents where a given memorylocation is in the stack.
1273 struct MemlocStackInfo {
1274 // This essentially is keeping track of versions of the stack. Whenever
1275 // the stack changes due to pushes or pops, these versions increase.
1276 unsigned long StackEpoch;
1277 unsigned long PopEpoch;
1278 // This is the lower bound of places on the stack to check. It is equal to
1279 // the place the last stack walk ended.
1280 // Note: Correctness depends on this being initialized to 0, which densemap
1281 // does
1282 unsigned long LowerBound;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001283 const BasicBlock *LowerBoundBlock;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001284 // This is where the last walk for this memory location ended.
1285 unsigned long LastKill;
1286 bool LastKillValid;
1287 };
1288 void optimizeUsesInBlock(const BasicBlock *, unsigned long &, unsigned long &,
1289 SmallVectorImpl<MemoryAccess *> &,
1290 DenseMap<MemoryLocOrCall, MemlocStackInfo> &);
1291 MemorySSA *MSSA;
1292 MemorySSAWalker *Walker;
1293 AliasAnalysis *AA;
1294 DominatorTree *DT;
1295};
1296
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001297/// Optimize the uses in a given block This is basically the SSA renaming
1298/// algorithm, with one caveat: We are able to use a single stack for all
1299/// MemoryUses. This is because the set of *possible* reaching MemoryDefs is
1300/// the same for every MemoryUse. The *actual* clobbering MemoryDef is just
1301/// going to be some position in that stack of possible ones.
1302///
1303/// We track the stack positions that each MemoryLocation needs
1304/// to check, and last ended at. This is because we only want to check the
1305/// things that changed since last time. The same MemoryLocation should
1306/// get clobbered by the same store (getModRefInfo does not use invariantness or
1307/// things like this, and if they start, we can modify MemoryLocOrCall to
1308/// include relevant data)
1309void MemorySSA::OptimizeUses::optimizeUsesInBlock(
1310 const BasicBlock *BB, unsigned long &StackEpoch, unsigned long &PopEpoch,
1311 SmallVectorImpl<MemoryAccess *> &VersionStack,
1312 DenseMap<MemoryLocOrCall, MemlocStackInfo> &LocStackInfo) {
1313
1314 /// If no accesses, nothing to do.
1315 MemorySSA::AccessList *Accesses = MSSA->getWritableBlockAccesses(BB);
1316 if (Accesses == nullptr)
1317 return;
1318
1319 // Pop everything that doesn't dominate the current block off the stack,
1320 // increment the PopEpoch to account for this.
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001321 while (true) {
1322 assert(
1323 !VersionStack.empty() &&
1324 "Version stack should have liveOnEntry sentinel dominating everything");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001325 BasicBlock *BackBlock = VersionStack.back()->getBlock();
1326 if (DT->dominates(BackBlock, BB))
1327 break;
1328 while (VersionStack.back()->getBlock() == BackBlock)
1329 VersionStack.pop_back();
1330 ++PopEpoch;
1331 }
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001332
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001333 for (MemoryAccess &MA : *Accesses) {
1334 auto *MU = dyn_cast<MemoryUse>(&MA);
1335 if (!MU) {
1336 VersionStack.push_back(&MA);
1337 ++StackEpoch;
1338 continue;
1339 }
1340
George Burgess IV024f3d22016-08-03 19:57:02 +00001341 if (isUseTriviallyOptimizableToLiveOnEntry(*AA, MU->getMemoryInst())) {
Daniel Berlincd2deac2016-10-20 20:13:45 +00001342 MU->setDefiningAccess(MSSA->getLiveOnEntryDef(), true);
George Burgess IV024f3d22016-08-03 19:57:02 +00001343 continue;
1344 }
1345
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001346 MemoryLocOrCall UseMLOC(MU);
1347 auto &LocInfo = LocStackInfo[UseMLOC];
Daniel Berlin26fcea92016-08-02 20:02:21 +00001348 // If the pop epoch changed, it means we've removed stuff from top of
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001349 // stack due to changing blocks. We may have to reset the lower bound or
1350 // last kill info.
1351 if (LocInfo.PopEpoch != PopEpoch) {
1352 LocInfo.PopEpoch = PopEpoch;
1353 LocInfo.StackEpoch = StackEpoch;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001354 // If the lower bound was in something that no longer dominates us, we
1355 // have to reset it.
1356 // We can't simply track stack size, because the stack may have had
1357 // pushes/pops in the meantime.
1358 // XXX: This is non-optimal, but only is slower cases with heavily
1359 // branching dominator trees. To get the optimal number of queries would
1360 // be to make lowerbound and lastkill a per-loc stack, and pop it until
1361 // the top of that stack dominates us. This does not seem worth it ATM.
1362 // A much cheaper optimization would be to always explore the deepest
1363 // branch of the dominator tree first. This will guarantee this resets on
1364 // the smallest set of blocks.
1365 if (LocInfo.LowerBoundBlock && LocInfo.LowerBoundBlock != BB &&
Daniel Berlin1e98c042016-09-26 17:22:54 +00001366 !DT->dominates(LocInfo.LowerBoundBlock, BB)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001367 // Reset the lower bound of things to check.
1368 // TODO: Some day we should be able to reset to last kill, rather than
1369 // 0.
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001370 LocInfo.LowerBound = 0;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001371 LocInfo.LowerBoundBlock = VersionStack[0]->getBlock();
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001372 LocInfo.LastKillValid = false;
1373 }
1374 } else if (LocInfo.StackEpoch != StackEpoch) {
1375 // If all that has changed is the StackEpoch, we only have to check the
1376 // new things on the stack, because we've checked everything before. In
1377 // this case, the lower bound of things to check remains the same.
1378 LocInfo.PopEpoch = PopEpoch;
1379 LocInfo.StackEpoch = StackEpoch;
1380 }
1381 if (!LocInfo.LastKillValid) {
1382 LocInfo.LastKill = VersionStack.size() - 1;
1383 LocInfo.LastKillValid = true;
1384 }
1385
1386 // At this point, we should have corrected last kill and LowerBound to be
1387 // in bounds.
1388 assert(LocInfo.LowerBound < VersionStack.size() &&
1389 "Lower bound out of range");
1390 assert(LocInfo.LastKill < VersionStack.size() &&
1391 "Last kill info out of range");
1392 // In any case, the new upper bound is the top of the stack.
1393 unsigned long UpperBound = VersionStack.size() - 1;
1394
1395 if (UpperBound - LocInfo.LowerBound > MaxCheckLimit) {
Daniel Berlin26fcea92016-08-02 20:02:21 +00001396 DEBUG(dbgs() << "MemorySSA skipping optimization of " << *MU << " ("
1397 << *(MU->getMemoryInst()) << ")"
1398 << " because there are " << UpperBound - LocInfo.LowerBound
1399 << " stores to disambiguate\n");
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001400 // Because we did not walk, LastKill is no longer valid, as this may
1401 // have been a kill.
1402 LocInfo.LastKillValid = false;
1403 continue;
1404 }
1405 bool FoundClobberResult = false;
1406 while (UpperBound > LocInfo.LowerBound) {
1407 if (isa<MemoryPhi>(VersionStack[UpperBound])) {
1408 // For phis, use the walker, see where we ended up, go there
1409 Instruction *UseInst = MU->getMemoryInst();
1410 MemoryAccess *Result = Walker->getClobberingMemoryAccess(UseInst);
1411 // We are guaranteed to find it or something is wrong
1412 while (VersionStack[UpperBound] != Result) {
1413 assert(UpperBound != 0);
1414 --UpperBound;
1415 }
1416 FoundClobberResult = true;
1417 break;
1418 }
1419
1420 MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]);
Daniel Berlindf101192016-08-03 00:01:46 +00001421 // If the lifetime of the pointer ends at this instruction, it's live on
1422 // entry.
1423 if (!UseMLOC.IsCall && lifetimeEndsAt(MD, UseMLOC.getLoc(), *AA)) {
1424 // Reset UpperBound to liveOnEntryDef's place in the stack
1425 UpperBound = 0;
1426 FoundClobberResult = true;
1427 break;
1428 }
Daniel Berlindff31de2016-08-02 21:57:52 +00001429 if (instructionClobbersQuery(MD, MU, UseMLOC, *AA)) {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001430 FoundClobberResult = true;
1431 break;
1432 }
1433 --UpperBound;
1434 }
1435 // At the end of this loop, UpperBound is either a clobber, or lower bound
1436 // PHI walking may cause it to be < LowerBound, and in fact, < LastKill.
1437 if (FoundClobberResult || UpperBound < LocInfo.LastKill) {
Daniel Berlincd2deac2016-10-20 20:13:45 +00001438 MU->setDefiningAccess(VersionStack[UpperBound], true);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001439 // We were last killed now by where we got to
1440 LocInfo.LastKill = UpperBound;
1441 } else {
1442 // Otherwise, we checked all the new ones, and now we know we can get to
1443 // LastKill.
Daniel Berlincd2deac2016-10-20 20:13:45 +00001444 MU->setDefiningAccess(VersionStack[LocInfo.LastKill], true);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001445 }
1446 LocInfo.LowerBound = VersionStack.size() - 1;
Daniel Berlin4b4c7222016-08-08 04:44:53 +00001447 LocInfo.LowerBoundBlock = BB;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001448 }
1449}
1450
1451/// Optimize uses to point to their actual clobbering definitions.
1452void MemorySSA::OptimizeUses::optimizeUses() {
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001453 SmallVector<MemoryAccess *, 16> VersionStack;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001454 DenseMap<MemoryLocOrCall, MemlocStackInfo> LocStackInfo;
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001455 VersionStack.push_back(MSSA->getLiveOnEntryDef());
1456
1457 unsigned long StackEpoch = 1;
1458 unsigned long PopEpoch = 1;
Piotr Padlewskicc5868c12017-02-18 20:34:36 +00001459 // We perform a non-recursive top-down dominator tree walk.
Daniel Berlin7ac3d742016-08-05 22:09:14 +00001460 for (const auto *DomNode : depth_first(DT->getRootNode()))
1461 optimizeUsesInBlock(DomNode->getBlock(), StackEpoch, PopEpoch, VersionStack,
1462 LocStackInfo);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001463}
1464
Daniel Berlin3d512a22016-08-22 19:14:30 +00001465void MemorySSA::placePHINodes(
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001466 const SmallPtrSetImpl<BasicBlock *> &DefiningBlocks,
1467 const DenseMap<const BasicBlock *, unsigned int> &BBNumbers) {
Daniel Berlin3d512a22016-08-22 19:14:30 +00001468 // Determine where our MemoryPhi's should go
1469 ForwardIDFCalculator IDFs(*DT);
1470 IDFs.setDefiningBlocks(DefiningBlocks);
Daniel Berlin3d512a22016-08-22 19:14:30 +00001471 SmallVector<BasicBlock *, 32> IDFBlocks;
1472 IDFs.calculate(IDFBlocks);
1473
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001474 std::sort(IDFBlocks.begin(), IDFBlocks.end(),
1475 [&BBNumbers](const BasicBlock *A, const BasicBlock *B) {
1476 return BBNumbers.lookup(A) < BBNumbers.lookup(B);
1477 });
1478
Daniel Berlin3d512a22016-08-22 19:14:30 +00001479 // Now place MemoryPhi nodes.
Daniel Berlind602e042017-01-25 20:56:19 +00001480 for (auto &BB : IDFBlocks)
1481 createMemoryPhi(BB);
Daniel Berlin3d512a22016-08-22 19:14:30 +00001482}
1483
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001484void MemorySSA::buildMemorySSA() {
George Burgess IVe1100f52016-02-02 22:46:49 +00001485 // We create an access to represent "live on entry", for things like
1486 // arguments or users of globals, where the memory they use is defined before
1487 // the beginning of the function. We do not actually insert it into the IR.
1488 // We do not define a live on exit for the immediate uses, and thus our
1489 // semantics do *not* imply that something with no immediate uses can simply
1490 // be removed.
1491 BasicBlock &StartingPoint = F.getEntryBlock();
1492 LiveOnEntryDef = make_unique<MemoryDef>(F.getContext(), nullptr, nullptr,
1493 &StartingPoint, NextID++);
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001494 DenseMap<const BasicBlock *, unsigned int> BBNumbers;
1495 unsigned NextBBNum = 0;
George Burgess IVe1100f52016-02-02 22:46:49 +00001496
1497 // We maintain lists of memory accesses per-block, trading memory for time. We
1498 // could just look up the memory access for every possible instruction in the
1499 // stream.
1500 SmallPtrSet<BasicBlock *, 32> DefiningBlocks;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001501 SmallPtrSet<BasicBlock *, 32> DefUseBlocks;
George Burgess IVe1100f52016-02-02 22:46:49 +00001502 // Go through each block, figure out where defs occur, and chain together all
1503 // the accesses.
1504 for (BasicBlock &B : F) {
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001505 BBNumbers[&B] = NextBBNum++;
Daniel Berlin7898ca62016-02-07 01:52:15 +00001506 bool InsertIntoDef = false;
Daniel Berlinada263d2016-06-20 20:21:33 +00001507 AccessList *Accesses = nullptr;
Daniel Berlind602e042017-01-25 20:56:19 +00001508 DefsList *Defs = nullptr;
George Burgess IVe1100f52016-02-02 22:46:49 +00001509 for (Instruction &I : B) {
Peter Collingbourneffecb142016-05-26 01:19:17 +00001510 MemoryUseOrDef *MUD = createNewAccess(&I);
George Burgess IVb42b7622016-03-11 19:34:03 +00001511 if (!MUD)
George Burgess IVe1100f52016-02-02 22:46:49 +00001512 continue;
Daniel Berlin1b51a292016-02-07 01:52:19 +00001513
George Burgess IVe1100f52016-02-02 22:46:49 +00001514 if (!Accesses)
1515 Accesses = getOrCreateAccessList(&B);
George Burgess IVb42b7622016-03-11 19:34:03 +00001516 Accesses->push_back(MUD);
Daniel Berlind602e042017-01-25 20:56:19 +00001517 if (isa<MemoryDef>(MUD)) {
1518 InsertIntoDef = true;
1519 if (!Defs)
1520 Defs = getOrCreateDefsList(&B);
1521 Defs->push_back(*MUD);
1522 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001523 }
Daniel Berlin7898ca62016-02-07 01:52:15 +00001524 if (InsertIntoDef)
1525 DefiningBlocks.insert(&B);
George Burgess IV3887a412016-03-21 21:25:39 +00001526 if (Accesses)
Daniel Berlin1b51a292016-02-07 01:52:19 +00001527 DefUseBlocks.insert(&B);
1528 }
Mandeep Singh Grang73f00952016-11-21 19:33:02 +00001529 placePHINodes(DefiningBlocks, BBNumbers);
George Burgess IVe1100f52016-02-02 22:46:49 +00001530
1531 // Now do regular SSA renaming on the MemoryDef/MemoryUse. Visited will get
1532 // filled in with all blocks.
1533 SmallPtrSet<BasicBlock *, 16> Visited;
1534 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1535
George Burgess IV5f308972016-07-19 01:29:15 +00001536 CachingWalker *Walker = getWalkerImpl();
1537
1538 // We're doing a batch of updates; don't drop useful caches between them.
1539 Walker->setAutoResetWalker(false);
Daniel Berlinc43aa5a2016-08-02 16:24:03 +00001540 OptimizeUses(this, Walker, AA, DT).optimizeUses();
George Burgess IV5f308972016-07-19 01:29:15 +00001541 Walker->setAutoResetWalker(true);
1542 Walker->resetClobberWalker();
1543
George Burgess IVe1100f52016-02-02 22:46:49 +00001544 // Mark the uses in unreachable blocks as live on entry, so that they go
1545 // somewhere.
1546 for (auto &BB : F)
1547 if (!Visited.count(&BB))
1548 markUnreachableAsLiveOnEntry(&BB);
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001549}
George Burgess IVe1100f52016-02-02 22:46:49 +00001550
George Burgess IV5f308972016-07-19 01:29:15 +00001551MemorySSAWalker *MemorySSA::getWalker() { return getWalkerImpl(); }
1552
1553MemorySSA::CachingWalker *MemorySSA::getWalkerImpl() {
Daniel Berlin16ed57c2016-06-27 18:22:27 +00001554 if (Walker)
1555 return Walker.get();
1556
1557 Walker = make_unique<CachingWalker>(this, AA, DT);
Geoff Berryb96d3b22016-06-01 21:30:40 +00001558 return Walker.get();
George Burgess IVe1100f52016-02-02 22:46:49 +00001559}
1560
Daniel Berlind602e042017-01-25 20:56:19 +00001561// This is a helper function used by the creation routines. It places NewAccess
1562// into the access and defs lists for a given basic block, at the given
1563// insertion point.
1564void MemorySSA::insertIntoListsForBlock(MemoryAccess *NewAccess,
1565 const BasicBlock *BB,
1566 InsertionPlace Point) {
1567 auto *Accesses = getOrCreateAccessList(BB);
1568 if (Point == Beginning) {
1569 // If it's a phi node, it goes first, otherwise, it goes after any phi
1570 // nodes.
1571 if (isa<MemoryPhi>(NewAccess)) {
1572 Accesses->push_front(NewAccess);
1573 auto *Defs = getOrCreateDefsList(BB);
1574 Defs->push_front(*NewAccess);
1575 } else {
1576 auto AI = find_if_not(
1577 *Accesses, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1578 Accesses->insert(AI, NewAccess);
1579 if (!isa<MemoryUse>(NewAccess)) {
1580 auto *Defs = getOrCreateDefsList(BB);
1581 auto DI = find_if_not(
1582 *Defs, [](const MemoryAccess &MA) { return isa<MemoryPhi>(MA); });
1583 Defs->insert(DI, *NewAccess);
1584 }
1585 }
1586 } else {
1587 Accesses->push_back(NewAccess);
1588 if (!isa<MemoryUse>(NewAccess)) {
1589 auto *Defs = getOrCreateDefsList(BB);
1590 Defs->push_back(*NewAccess);
1591 }
1592 }
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001593 BlockNumberingValid.erase(BB);
Daniel Berlind602e042017-01-25 20:56:19 +00001594}
1595
1596void MemorySSA::insertIntoListsBefore(MemoryAccess *What, const BasicBlock *BB,
1597 AccessList::iterator InsertPt) {
1598 auto *Accesses = getWritableBlockAccesses(BB);
1599 bool WasEnd = InsertPt == Accesses->end();
1600 Accesses->insert(AccessList::iterator(InsertPt), What);
1601 if (!isa<MemoryUse>(What)) {
1602 auto *Defs = getOrCreateDefsList(BB);
1603 // If we got asked to insert at the end, we have an easy job, just shove it
1604 // at the end. If we got asked to insert before an existing def, we also get
1605 // an terator. If we got asked to insert before a use, we have to hunt for
1606 // the next def.
1607 if (WasEnd) {
1608 Defs->push_back(*What);
1609 } else if (isa<MemoryDef>(InsertPt)) {
1610 Defs->insert(InsertPt->getDefsIterator(), *What);
1611 } else {
1612 while (InsertPt != Accesses->end() && !isa<MemoryDef>(InsertPt))
1613 ++InsertPt;
1614 // Either we found a def, or we are inserting at the end
1615 if (InsertPt == Accesses->end())
1616 Defs->push_back(*What);
1617 else
1618 Defs->insert(InsertPt->getDefsIterator(), *What);
1619 }
1620 }
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001621 BlockNumberingValid.erase(BB);
Daniel Berlind602e042017-01-25 20:56:19 +00001622}
1623
Daniel Berlin60ead052017-01-28 01:23:13 +00001624// Move What before Where in the IR. The end result is taht What will belong to
1625// the right lists and have the right Block set, but will not otherwise be
1626// correct. It will not have the right defining access, and if it is a def,
1627// things below it will not properly be updated.
1628void MemorySSA::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
1629 AccessList::iterator Where) {
1630 // Keep it in the lookup tables, remove from the lists
1631 removeFromLists(What, false);
1632 What->setBlock(BB);
1633 insertIntoListsBefore(What, BB, Where);
1634}
1635
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001636void MemorySSA::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
1637 InsertionPlace Point) {
1638 removeFromLists(What, false);
1639 What->setBlock(BB);
1640 insertIntoListsForBlock(What, BB, Point);
1641}
1642
Daniel Berlin14300262016-06-21 18:39:20 +00001643MemoryPhi *MemorySSA::createMemoryPhi(BasicBlock *BB) {
1644 assert(!getMemoryAccess(BB) && "MemoryPhi already exists for this BB");
Daniel Berlin14300262016-06-21 18:39:20 +00001645 MemoryPhi *Phi = new MemoryPhi(BB->getContext(), BB, NextID++);
Daniel Berlin9d8a3352017-01-30 11:35:39 +00001646 // Phi's always are placed at the front of the block.
Daniel Berlind602e042017-01-25 20:56:19 +00001647 insertIntoListsForBlock(Phi, BB, Beginning);
Daniel Berlin5130cc82016-07-31 21:08:20 +00001648 ValueToMemoryAccess[BB] = Phi;
Daniel Berlin14300262016-06-21 18:39:20 +00001649 return Phi;
1650}
1651
1652MemoryUseOrDef *MemorySSA::createDefinedAccess(Instruction *I,
1653 MemoryAccess *Definition) {
1654 assert(!isa<PHINode>(I) && "Cannot create a defined access for a PHI");
1655 MemoryUseOrDef *NewAccess = createNewAccess(I);
1656 assert(
1657 NewAccess != nullptr &&
1658 "Tried to create a memory access for a non-memory touching instruction");
1659 NewAccess->setDefiningAccess(Definition);
1660 return NewAccess;
1661}
1662
George Burgess IVe1100f52016-02-02 22:46:49 +00001663/// \brief Helper function to create new memory accesses
Peter Collingbourneffecb142016-05-26 01:19:17 +00001664MemoryUseOrDef *MemorySSA::createNewAccess(Instruction *I) {
Peter Collingbourneb9aa1f42016-05-26 04:58:46 +00001665 // The assume intrinsic has a control dependency which we model by claiming
1666 // that it writes arbitrarily. Ignore that fake memory dependency here.
1667 // FIXME: Replace this special casing with a more accurate modelling of
1668 // assume's control dependency.
1669 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1670 if (II->getIntrinsicID() == Intrinsic::assume)
1671 return nullptr;
1672
George Burgess IVe1100f52016-02-02 22:46:49 +00001673 // Find out what affect this instruction has on memory.
1674 ModRefInfo ModRef = AA->getModRefInfo(I);
1675 bool Def = bool(ModRef & MRI_Mod);
1676 bool Use = bool(ModRef & MRI_Ref);
1677
1678 // It's possible for an instruction to not modify memory at all. During
1679 // construction, we ignore them.
Peter Collingbourneffecb142016-05-26 01:19:17 +00001680 if (!Def && !Use)
George Burgess IVe1100f52016-02-02 22:46:49 +00001681 return nullptr;
1682
1683 assert((Def || Use) &&
1684 "Trying to create a memory access with a non-memory instruction");
1685
George Burgess IVb42b7622016-03-11 19:34:03 +00001686 MemoryUseOrDef *MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001687 if (Def)
George Burgess IVb42b7622016-03-11 19:34:03 +00001688 MUD = new MemoryDef(I->getContext(), nullptr, I, I->getParent(), NextID++);
George Burgess IVe1100f52016-02-02 22:46:49 +00001689 else
George Burgess IVb42b7622016-03-11 19:34:03 +00001690 MUD = new MemoryUse(I->getContext(), nullptr, I, I->getParent());
Daniel Berlin5130cc82016-07-31 21:08:20 +00001691 ValueToMemoryAccess[I] = MUD;
George Burgess IVb42b7622016-03-11 19:34:03 +00001692 return MUD;
George Burgess IVe1100f52016-02-02 22:46:49 +00001693}
1694
George Burgess IVe1100f52016-02-02 22:46:49 +00001695/// \brief Returns true if \p Replacer dominates \p Replacee .
1696bool MemorySSA::dominatesUse(const MemoryAccess *Replacer,
1697 const MemoryAccess *Replacee) const {
1698 if (isa<MemoryUseOrDef>(Replacee))
1699 return DT->dominates(Replacer->getBlock(), Replacee->getBlock());
1700 const auto *MP = cast<MemoryPhi>(Replacee);
1701 // For a phi node, the use occurs in the predecessor block of the phi node.
1702 // Since we may occur multiple times in the phi node, we have to check each
1703 // operand to ensure Replacer dominates each operand where Replacee occurs.
1704 for (const Use &Arg : MP->operands()) {
George Burgess IVb5a229f2016-02-02 23:15:26 +00001705 if (Arg.get() != Replacee &&
George Burgess IVe1100f52016-02-02 22:46:49 +00001706 !DT->dominates(Replacer->getBlock(), MP->getIncomingBlock(Arg)))
1707 return false;
1708 }
1709 return true;
1710}
1711
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001712/// \brief Properly remove \p MA from all of MemorySSA's lookup tables.
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001713void MemorySSA::removeFromLookups(MemoryAccess *MA) {
1714 assert(MA->use_empty() &&
1715 "Trying to remove memory access that still has uses");
Daniel Berlin5c46b942016-07-19 22:49:43 +00001716 BlockNumbering.erase(MA);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001717 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA))
1718 MUD->setDefiningAccess(nullptr);
1719 // Invalidate our walker's cache if necessary
1720 if (!isa<MemoryUse>(MA))
1721 Walker->invalidateInfo(MA);
1722 // The call below to erase will destroy MA, so we can't change the order we
1723 // are doing things here
1724 Value *MemoryInst;
1725 if (MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
1726 MemoryInst = MUD->getMemoryInst();
1727 } else {
1728 MemoryInst = MA->getBlock();
1729 }
Daniel Berlin5130cc82016-07-31 21:08:20 +00001730 auto VMA = ValueToMemoryAccess.find(MemoryInst);
1731 if (VMA->second == MA)
1732 ValueToMemoryAccess.erase(VMA);
Daniel Berlin60ead052017-01-28 01:23:13 +00001733}
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001734
Daniel Berlin60ead052017-01-28 01:23:13 +00001735/// \brief Properly remove \p MA from all of MemorySSA's lists.
1736///
1737/// Because of the way the intrusive list and use lists work, it is important to
1738/// do removal in the right order.
1739/// ShouldDelete defaults to true, and will cause the memory access to also be
1740/// deleted, not just removed.
1741void MemorySSA::removeFromLists(MemoryAccess *MA, bool ShouldDelete) {
Daniel Berlind602e042017-01-25 20:56:19 +00001742 // The access list owns the reference, so we erase it from the non-owning list
1743 // first.
1744 if (!isa<MemoryUse>(MA)) {
1745 auto DefsIt = PerBlockDefs.find(MA->getBlock());
1746 std::unique_ptr<DefsList> &Defs = DefsIt->second;
1747 Defs->remove(*MA);
1748 if (Defs->empty())
1749 PerBlockDefs.erase(DefsIt);
1750 }
1751
Daniel Berlin60ead052017-01-28 01:23:13 +00001752 // The erase call here will delete it. If we don't want it deleted, we call
1753 // remove instead.
George Burgess IVe0e6e482016-03-02 02:35:04 +00001754 auto AccessIt = PerBlockAccesses.find(MA->getBlock());
Daniel Berlinada263d2016-06-20 20:21:33 +00001755 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
Daniel Berlin60ead052017-01-28 01:23:13 +00001756 if (ShouldDelete)
1757 Accesses->erase(MA);
1758 else
1759 Accesses->remove(MA);
1760
George Burgess IVe0e6e482016-03-02 02:35:04 +00001761 if (Accesses->empty())
1762 PerBlockAccesses.erase(AccessIt);
Daniel Berlin83fc77b2016-03-01 18:46:54 +00001763}
1764
George Burgess IVe1100f52016-02-02 22:46:49 +00001765void MemorySSA::print(raw_ostream &OS) const {
1766 MemorySSAAnnotatedWriter Writer(this);
1767 F.print(OS, &Writer);
1768}
1769
Matthias Braun8c209aa2017-01-28 02:02:38 +00001770#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Daniel Berlin78cbd282017-02-20 22:26:03 +00001771LLVM_DUMP_METHOD void MemorySSA::dump() const { print(dbgs()); }
Matthias Braun8c209aa2017-01-28 02:02:38 +00001772#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001773
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001774void MemorySSA::verifyMemorySSA() const {
1775 verifyDefUses(F);
1776 verifyDomination(F);
Daniel Berlin14300262016-06-21 18:39:20 +00001777 verifyOrdering(F);
Geoff Berrycdf53332016-08-08 17:52:01 +00001778 Walker->verify(this);
Daniel Berlin14300262016-06-21 18:39:20 +00001779}
1780
1781/// \brief Verify that the order and existence of MemoryAccesses matches the
1782/// order and existence of memory affecting instructions.
1783void MemorySSA::verifyOrdering(Function &F) const {
1784 // Walk all the blocks, comparing what the lookups think and what the access
1785 // lists think, as well as the order in the blocks vs the order in the access
1786 // lists.
1787 SmallVector<MemoryAccess *, 32> ActualAccesses;
Daniel Berlind602e042017-01-25 20:56:19 +00001788 SmallVector<MemoryAccess *, 32> ActualDefs;
Daniel Berlin14300262016-06-21 18:39:20 +00001789 for (BasicBlock &B : F) {
1790 const AccessList *AL = getBlockAccesses(&B);
Daniel Berlind602e042017-01-25 20:56:19 +00001791 const auto *DL = getBlockDefs(&B);
Daniel Berlin14300262016-06-21 18:39:20 +00001792 MemoryAccess *Phi = getMemoryAccess(&B);
Daniel Berlind602e042017-01-25 20:56:19 +00001793 if (Phi) {
Daniel Berlin14300262016-06-21 18:39:20 +00001794 ActualAccesses.push_back(Phi);
Daniel Berlind602e042017-01-25 20:56:19 +00001795 ActualDefs.push_back(Phi);
1796 }
1797
Daniel Berlin14300262016-06-21 18:39:20 +00001798 for (Instruction &I : B) {
1799 MemoryAccess *MA = getMemoryAccess(&I);
Daniel Berlind602e042017-01-25 20:56:19 +00001800 assert((!MA || (AL && (isa<MemoryUse>(MA) || DL))) &&
1801 "We have memory affecting instructions "
1802 "in this block but they are not in the "
1803 "access list or defs list");
1804 if (MA) {
Daniel Berlin14300262016-06-21 18:39:20 +00001805 ActualAccesses.push_back(MA);
Daniel Berlind602e042017-01-25 20:56:19 +00001806 if (isa<MemoryDef>(MA))
1807 ActualDefs.push_back(MA);
1808 }
Daniel Berlin14300262016-06-21 18:39:20 +00001809 }
1810 // Either we hit the assert, really have no accesses, or we have both
Daniel Berlind602e042017-01-25 20:56:19 +00001811 // accesses and an access list.
1812 // Same with defs.
1813 if (!AL && !DL)
Daniel Berlin14300262016-06-21 18:39:20 +00001814 continue;
1815 assert(AL->size() == ActualAccesses.size() &&
1816 "We don't have the same number of accesses in the block as on the "
1817 "access list");
Davide Italiano6c77de02017-01-30 03:16:43 +00001818 assert((DL || ActualDefs.size() == 0) &&
1819 "Either we should have a defs list, or we should have no defs");
Daniel Berlind602e042017-01-25 20:56:19 +00001820 assert((!DL || DL->size() == ActualDefs.size()) &&
1821 "We don't have the same number of defs in the block as on the "
1822 "def list");
Daniel Berlin14300262016-06-21 18:39:20 +00001823 auto ALI = AL->begin();
1824 auto AAI = ActualAccesses.begin();
1825 while (ALI != AL->end() && AAI != ActualAccesses.end()) {
1826 assert(&*ALI == *AAI && "Not the same accesses in the same order");
1827 ++ALI;
1828 ++AAI;
1829 }
1830 ActualAccesses.clear();
Daniel Berlind602e042017-01-25 20:56:19 +00001831 if (DL) {
1832 auto DLI = DL->begin();
1833 auto ADI = ActualDefs.begin();
1834 while (DLI != DL->end() && ADI != ActualDefs.end()) {
1835 assert(&*DLI == *ADI && "Not the same defs in the same order");
1836 ++DLI;
1837 ++ADI;
1838 }
1839 }
1840 ActualDefs.clear();
Daniel Berlin14300262016-06-21 18:39:20 +00001841 }
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001842}
1843
George Burgess IVe1100f52016-02-02 22:46:49 +00001844/// \brief Verify the domination properties of MemorySSA by checking that each
1845/// definition dominates all of its uses.
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001846void MemorySSA::verifyDomination(Function &F) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001847#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001848 for (BasicBlock &B : F) {
1849 // Phi nodes are attached to basic blocks
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001850 if (MemoryPhi *MP = getMemoryAccess(&B))
1851 for (const Use &U : MP->uses())
1852 assert(dominates(MP, U) && "Memory PHI does not dominate it's uses");
Daniel Berlin7af95872016-08-05 21:47:20 +00001853
George Burgess IVe1100f52016-02-02 22:46:49 +00001854 for (Instruction &I : B) {
1855 MemoryAccess *MD = dyn_cast_or_null<MemoryDef>(getMemoryAccess(&I));
1856 if (!MD)
1857 continue;
1858
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001859 for (const Use &U : MD->uses())
1860 assert(dominates(MD, U) && "Memory Def does not dominate it's uses");
George Burgess IVe1100f52016-02-02 22:46:49 +00001861 }
1862 }
Daniel Berlin7af95872016-08-05 21:47:20 +00001863#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001864}
1865
1866/// \brief Verify the def-use lists in MemorySSA, by verifying that \p Use
1867/// appears in the use list of \p Def.
Daniel Berlin7af95872016-08-05 21:47:20 +00001868
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001869void MemorySSA::verifyUseInDefs(MemoryAccess *Def, MemoryAccess *Use) const {
Daniel Berlin7af95872016-08-05 21:47:20 +00001870#ifndef NDEBUG
George Burgess IVe1100f52016-02-02 22:46:49 +00001871 // The live on entry use may cause us to get a NULL def here
Daniel Berlin7af95872016-08-05 21:47:20 +00001872 if (!Def)
1873 assert(isLiveOnEntryDef(Use) &&
1874 "Null def but use not point to live on entry def");
1875 else
Daniel Berlinda2f38e2016-08-11 21:26:50 +00001876 assert(is_contained(Def->users(), Use) &&
Daniel Berlin7af95872016-08-05 21:47:20 +00001877 "Did not find use in def's use list");
1878#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00001879}
1880
1881/// \brief Verify the immediate use information, by walking all the memory
1882/// accesses and verifying that, for each use, it appears in the
1883/// appropriate def's use list
Daniel Berlin932b4cb2016-02-10 17:39:43 +00001884void MemorySSA::verifyDefUses(Function &F) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00001885 for (BasicBlock &B : F) {
1886 // Phi nodes are attached to basic blocks
Daniel Berlin14300262016-06-21 18:39:20 +00001887 if (MemoryPhi *Phi = getMemoryAccess(&B)) {
David Majnemer580e7542016-06-25 00:04:06 +00001888 assert(Phi->getNumOperands() == static_cast<unsigned>(std::distance(
1889 pred_begin(&B), pred_end(&B))) &&
Daniel Berlin14300262016-06-21 18:39:20 +00001890 "Incomplete MemoryPhi Node");
George Burgess IVe1100f52016-02-02 22:46:49 +00001891 for (unsigned I = 0, E = Phi->getNumIncomingValues(); I != E; ++I)
1892 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
Daniel Berlin14300262016-06-21 18:39:20 +00001893 }
George Burgess IVe1100f52016-02-02 22:46:49 +00001894
1895 for (Instruction &I : B) {
George Burgess IV66837ab2016-11-01 21:17:46 +00001896 if (MemoryUseOrDef *MA = getMemoryAccess(&I)) {
1897 verifyUseInDefs(MA->getDefiningAccess(), MA);
George Burgess IVe1100f52016-02-02 22:46:49 +00001898 }
1899 }
1900 }
1901}
1902
George Burgess IV66837ab2016-11-01 21:17:46 +00001903MemoryUseOrDef *MemorySSA::getMemoryAccess(const Instruction *I) const {
1904 return cast_or_null<MemoryUseOrDef>(ValueToMemoryAccess.lookup(I));
George Burgess IVe1100f52016-02-02 22:46:49 +00001905}
1906
1907MemoryPhi *MemorySSA::getMemoryAccess(const BasicBlock *BB) const {
George Burgess IV66837ab2016-11-01 21:17:46 +00001908 return cast_or_null<MemoryPhi>(ValueToMemoryAccess.lookup(cast<Value>(BB)));
George Burgess IVe1100f52016-02-02 22:46:49 +00001909}
1910
Daniel Berlin5c46b942016-07-19 22:49:43 +00001911/// Perform a local numbering on blocks so that instruction ordering can be
1912/// determined in constant time.
1913/// TODO: We currently just number in order. If we numbered by N, we could
1914/// allow at least N-1 sequences of insertBefore or insertAfter (and at least
1915/// log2(N) sequences of mixed before and after) without needing to invalidate
1916/// the numbering.
1917void MemorySSA::renumberBlock(const BasicBlock *B) const {
1918 // The pre-increment ensures the numbers really start at 1.
1919 unsigned long CurrentNumber = 0;
1920 const AccessList *AL = getBlockAccesses(B);
1921 assert(AL != nullptr && "Asking to renumber an empty block");
1922 for (const auto &I : *AL)
1923 BlockNumbering[&I] = ++CurrentNumber;
1924 BlockNumberingValid.insert(B);
1925}
1926
George Burgess IVe1100f52016-02-02 22:46:49 +00001927/// \brief Determine, for two memory accesses in the same block,
1928/// whether \p Dominator dominates \p Dominatee.
1929/// \returns True if \p Dominator dominates \p Dominatee.
1930bool MemorySSA::locallyDominates(const MemoryAccess *Dominator,
1931 const MemoryAccess *Dominatee) const {
Sebastian Pope1f60b12016-06-10 21:36:41 +00001932
Daniel Berlin5c46b942016-07-19 22:49:43 +00001933 const BasicBlock *DominatorBlock = Dominator->getBlock();
Daniel Berlin5c46b942016-07-19 22:49:43 +00001934
Daniel Berlin19860302016-07-19 23:08:08 +00001935 assert((DominatorBlock == Dominatee->getBlock()) &&
Daniel Berlin5c46b942016-07-19 22:49:43 +00001936 "Asking for local domination when accesses are in different blocks!");
Sebastian Pope1f60b12016-06-10 21:36:41 +00001937 // A node dominates itself.
1938 if (Dominatee == Dominator)
1939 return true;
1940
1941 // When Dominatee is defined on function entry, it is not dominated by another
1942 // memory access.
1943 if (isLiveOnEntryDef(Dominatee))
1944 return false;
1945
1946 // When Dominator is defined on function entry, it dominates the other memory
1947 // access.
1948 if (isLiveOnEntryDef(Dominator))
1949 return true;
1950
Daniel Berlin5c46b942016-07-19 22:49:43 +00001951 if (!BlockNumberingValid.count(DominatorBlock))
1952 renumberBlock(DominatorBlock);
George Burgess IVe1100f52016-02-02 22:46:49 +00001953
Daniel Berlin5c46b942016-07-19 22:49:43 +00001954 unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
1955 // All numbers start with 1
1956 assert(DominatorNum != 0 && "Block was not numbered properly");
1957 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
1958 assert(DominateeNum != 0 && "Block was not numbered properly");
1959 return DominatorNum < DominateeNum;
George Burgess IVe1100f52016-02-02 22:46:49 +00001960}
1961
George Burgess IV5f308972016-07-19 01:29:15 +00001962bool MemorySSA::dominates(const MemoryAccess *Dominator,
1963 const MemoryAccess *Dominatee) const {
1964 if (Dominator == Dominatee)
1965 return true;
1966
1967 if (isLiveOnEntryDef(Dominatee))
1968 return false;
1969
1970 if (Dominator->getBlock() != Dominatee->getBlock())
1971 return DT->dominates(Dominator->getBlock(), Dominatee->getBlock());
1972 return locallyDominates(Dominator, Dominatee);
1973}
1974
Daniel Berlin2919b1c2016-08-05 21:46:52 +00001975bool MemorySSA::dominates(const MemoryAccess *Dominator,
1976 const Use &Dominatee) const {
1977 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(Dominatee.getUser())) {
1978 BasicBlock *UseBB = MP->getIncomingBlock(Dominatee);
1979 // The def must dominate the incoming block of the phi.
1980 if (UseBB != Dominator->getBlock())
1981 return DT->dominates(Dominator->getBlock(), UseBB);
1982 // If the UseBB and the DefBB are the same, compare locally.
1983 return locallyDominates(Dominator, cast<MemoryAccess>(Dominatee));
1984 }
1985 // If it's not a PHI node use, the normal dominates can already handle it.
1986 return dominates(Dominator, cast<MemoryAccess>(Dominatee.getUser()));
1987}
1988
George Burgess IVe1100f52016-02-02 22:46:49 +00001989const static char LiveOnEntryStr[] = "liveOnEntry";
1990
1991void MemoryDef::print(raw_ostream &OS) const {
1992 MemoryAccess *UO = getDefiningAccess();
1993
1994 OS << getID() << " = MemoryDef(";
1995 if (UO && UO->getID())
1996 OS << UO->getID();
1997 else
1998 OS << LiveOnEntryStr;
1999 OS << ')';
2000}
2001
2002void MemoryPhi::print(raw_ostream &OS) const {
2003 bool First = true;
2004 OS << getID() << " = MemoryPhi(";
2005 for (const auto &Op : operands()) {
2006 BasicBlock *BB = getIncomingBlock(Op);
2007 MemoryAccess *MA = cast<MemoryAccess>(Op);
2008 if (!First)
2009 OS << ',';
2010 else
2011 First = false;
2012
2013 OS << '{';
2014 if (BB->hasName())
2015 OS << BB->getName();
2016 else
2017 BB->printAsOperand(OS, false);
2018 OS << ',';
2019 if (unsigned ID = MA->getID())
2020 OS << ID;
2021 else
2022 OS << LiveOnEntryStr;
2023 OS << '}';
2024 }
2025 OS << ')';
2026}
2027
2028MemoryAccess::~MemoryAccess() {}
2029
2030void MemoryUse::print(raw_ostream &OS) const {
2031 MemoryAccess *UO = getDefiningAccess();
2032 OS << "MemoryUse(";
2033 if (UO && UO->getID())
2034 OS << UO->getID();
2035 else
2036 OS << LiveOnEntryStr;
2037 OS << ')';
2038}
2039
2040void MemoryAccess::dump() const {
Daniel Berlin78cbd282017-02-20 22:26:03 +00002041// Cannot completely remove virtual function even in release mode.
Matthias Braun8c209aa2017-01-28 02:02:38 +00002042#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
George Burgess IVe1100f52016-02-02 22:46:49 +00002043 print(dbgs());
2044 dbgs() << "\n";
Matthias Braun8c209aa2017-01-28 02:02:38 +00002045#endif
George Burgess IVe1100f52016-02-02 22:46:49 +00002046}
2047
Chad Rosier232e29e2016-07-06 21:20:47 +00002048char MemorySSAPrinterLegacyPass::ID = 0;
2049
2050MemorySSAPrinterLegacyPass::MemorySSAPrinterLegacyPass() : FunctionPass(ID) {
2051 initializeMemorySSAPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
2052}
2053
2054void MemorySSAPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
2055 AU.setPreservesAll();
2056 AU.addRequired<MemorySSAWrapperPass>();
2057 AU.addPreserved<MemorySSAWrapperPass>();
2058}
2059
2060bool MemorySSAPrinterLegacyPass::runOnFunction(Function &F) {
2061 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
2062 MSSA.print(dbgs());
2063 if (VerifyMemorySSA)
2064 MSSA.verifyMemorySSA();
2065 return false;
2066}
2067
Chandler Carruthdab4eae2016-11-23 17:53:26 +00002068AnalysisKey MemorySSAAnalysis::Key;
George Burgess IVe1100f52016-02-02 22:46:49 +00002069
Daniel Berlin1e98c042016-09-26 17:22:54 +00002070MemorySSAAnalysis::Result MemorySSAAnalysis::run(Function &F,
2071 FunctionAnalysisManager &AM) {
Geoff Berryb96d3b22016-06-01 21:30:40 +00002072 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
2073 auto &AA = AM.getResult<AAManager>(F);
Geoff Berry290a13e2016-08-08 18:27:22 +00002074 return MemorySSAAnalysis::Result(make_unique<MemorySSA>(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00002075}
2076
Geoff Berryb96d3b22016-06-01 21:30:40 +00002077PreservedAnalyses MemorySSAPrinterPass::run(Function &F,
2078 FunctionAnalysisManager &AM) {
2079 OS << "MemorySSA for function: " << F.getName() << "\n";
Geoff Berry290a13e2016-08-08 18:27:22 +00002080 AM.getResult<MemorySSAAnalysis>(F).getMSSA().print(OS);
Geoff Berryb96d3b22016-06-01 21:30:40 +00002081
2082 return PreservedAnalyses::all();
George Burgess IVe1100f52016-02-02 22:46:49 +00002083}
2084
Geoff Berryb96d3b22016-06-01 21:30:40 +00002085PreservedAnalyses MemorySSAVerifierPass::run(Function &F,
2086 FunctionAnalysisManager &AM) {
Geoff Berry290a13e2016-08-08 18:27:22 +00002087 AM.getResult<MemorySSAAnalysis>(F).getMSSA().verifyMemorySSA();
Geoff Berryb96d3b22016-06-01 21:30:40 +00002088
2089 return PreservedAnalyses::all();
2090}
2091
2092char MemorySSAWrapperPass::ID = 0;
2093
2094MemorySSAWrapperPass::MemorySSAWrapperPass() : FunctionPass(ID) {
2095 initializeMemorySSAWrapperPassPass(*PassRegistry::getPassRegistry());
2096}
2097
2098void MemorySSAWrapperPass::releaseMemory() { MSSA.reset(); }
2099
2100void MemorySSAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00002101 AU.setPreservesAll();
Geoff Berryb96d3b22016-06-01 21:30:40 +00002102 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
2103 AU.addRequiredTransitive<AAResultsWrapperPass>();
George Burgess IVe1100f52016-02-02 22:46:49 +00002104}
2105
Geoff Berryb96d3b22016-06-01 21:30:40 +00002106bool MemorySSAWrapperPass::runOnFunction(Function &F) {
2107 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2108 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2109 MSSA.reset(new MemorySSA(F, &AA, &DT));
George Burgess IVe1100f52016-02-02 22:46:49 +00002110 return false;
2111}
2112
Geoff Berryb96d3b22016-06-01 21:30:40 +00002113void MemorySSAWrapperPass::verifyAnalysis() const { MSSA->verifyMemorySSA(); }
George Burgess IVe1100f52016-02-02 22:46:49 +00002114
Geoff Berryb96d3b22016-06-01 21:30:40 +00002115void MemorySSAWrapperPass::print(raw_ostream &OS, const Module *M) const {
George Burgess IVe1100f52016-02-02 22:46:49 +00002116 MSSA->print(OS);
2117}
2118
George Burgess IVe1100f52016-02-02 22:46:49 +00002119MemorySSAWalker::MemorySSAWalker(MemorySSA *M) : MSSA(M) {}
2120
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002121MemorySSA::CachingWalker::CachingWalker(MemorySSA *M, AliasAnalysis *A,
2122 DominatorTree *D)
Daniel Berlin5c46b942016-07-19 22:49:43 +00002123 : MemorySSAWalker(M), Walker(*M, *A, *D, Cache), AutoResetWalker(true) {}
George Burgess IVe1100f52016-02-02 22:46:49 +00002124
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002125MemorySSA::CachingWalker::~CachingWalker() {}
George Burgess IVe1100f52016-02-02 22:46:49 +00002126
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002127void MemorySSA::CachingWalker::invalidateInfo(MemoryAccess *MA) {
Daniel Berlin83fc77b2016-03-01 18:46:54 +00002128 // TODO: We can do much better cache invalidation with differently stored
2129 // caches. For now, for MemoryUses, we simply remove them
2130 // from the cache, and kill the entire call/non-call cache for everything
2131 // else. The problem is for phis or defs, currently we'd need to follow use
2132 // chains down and invalidate anything below us in the chain that currently
2133 // terminates at this access.
2134
2135 // See if this is a MemoryUse, if so, just remove the cached info. MemoryUse
2136 // is by definition never a barrier, so nothing in the cache could point to
2137 // this use. In that case, we only need invalidate the info for the use
2138 // itself.
2139
2140 if (MemoryUse *MU = dyn_cast<MemoryUse>(MA)) {
George Burgess IV5f308972016-07-19 01:29:15 +00002141 UpwardsMemoryQuery Q(MU->getMemoryInst(), MU);
2142 Cache.remove(MU, Q.StartingLoc, Q.IsCall);
Daniel Berlincd2deac2016-10-20 20:13:45 +00002143 MU->resetOptimized();
Geoff Berry9fe26e62016-04-22 14:44:10 +00002144 } else {
2145 // 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 +00002146 Cache.clear();
Geoff Berry9fe26e62016-04-22 14:44:10 +00002147 }
2148
Filipe Cabecinhas0da99372016-04-29 15:22:48 +00002149#ifdef EXPENSIVE_CHECKS
Geoff Berry9fe26e62016-04-22 14:44:10 +00002150 verifyRemoved(MA);
2151#endif
Daniel Berlin83fc77b2016-03-01 18:46:54 +00002152}
2153
George Burgess IVe1100f52016-02-02 22:46:49 +00002154/// \brief Walk the use-def chains starting at \p MA and find
2155/// the MemoryAccess that actually clobbers Loc.
2156///
2157/// \returns our clobbering memory access
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002158MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
2159 MemoryAccess *StartingAccess, UpwardsMemoryQuery &Q) {
George Burgess IV5f308972016-07-19 01:29:15 +00002160 MemoryAccess *New = Walker.findClobber(StartingAccess, Q);
2161#ifdef EXPENSIVE_CHECKS
2162 MemoryAccess *NewNoCache =
2163 Walker.findClobber(StartingAccess, Q, /*UseWalkerCache=*/false);
2164 assert(NewNoCache == New && "Cache made us hand back a different result?");
2165#endif
2166 if (AutoResetWalker)
2167 resetClobberWalker();
2168 return New;
George Burgess IVe1100f52016-02-02 22:46:49 +00002169}
2170
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002171MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
George Burgess IV013fd732016-10-28 19:22:46 +00002172 MemoryAccess *StartingAccess, const MemoryLocation &Loc) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002173 if (isa<MemoryPhi>(StartingAccess))
2174 return StartingAccess;
2175
2176 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
2177 if (MSSA->isLiveOnEntryDef(StartingUseOrDef))
2178 return StartingUseOrDef;
2179
2180 Instruction *I = StartingUseOrDef->getMemoryInst();
2181
2182 // Conservatively, fences are always clobbers, so don't perform the walk if we
2183 // hit a fence.
David Majnemera940f362016-07-15 17:19:24 +00002184 if (!ImmutableCallSite(I) && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002185 return StartingUseOrDef;
2186
2187 UpwardsMemoryQuery Q;
2188 Q.OriginalAccess = StartingUseOrDef;
2189 Q.StartingLoc = Loc;
George Burgess IV5f308972016-07-19 01:29:15 +00002190 Q.Inst = I;
George Burgess IVe1100f52016-02-02 22:46:49 +00002191 Q.IsCall = false;
George Burgess IVe1100f52016-02-02 22:46:49 +00002192
George Burgess IV5f308972016-07-19 01:29:15 +00002193 if (auto *CacheResult = Cache.lookup(StartingUseOrDef, Loc, Q.IsCall))
George Burgess IVe1100f52016-02-02 22:46:49 +00002194 return CacheResult;
2195
2196 // Unlike the other function, do not walk to the def of a def, because we are
2197 // handed something we already believe is the clobbering access.
2198 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
2199 ? StartingUseOrDef->getDefiningAccess()
2200 : StartingUseOrDef;
2201
2202 MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00002203 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2204 DEBUG(dbgs() << *StartingUseOrDef << "\n");
2205 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2206 DEBUG(dbgs() << *Clobber << "\n");
2207 return Clobber;
2208}
2209
2210MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002211MemorySSA::CachingWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
2212 auto *StartingAccess = dyn_cast<MemoryUseOrDef>(MA);
2213 // If this is a MemoryPhi, we can't do anything.
2214 if (!StartingAccess)
2215 return MA;
George Burgess IVe1100f52016-02-02 22:46:49 +00002216
Daniel Berlincd2deac2016-10-20 20:13:45 +00002217 // If this is an already optimized use or def, return the optimized result.
2218 // Note: Currently, we do not store the optimized def result because we'd need
2219 // a separate field, since we can't use it as the defining access.
2220 if (MemoryUse *MU = dyn_cast<MemoryUse>(StartingAccess))
2221 if (MU->isOptimized())
2222 return MU->getDefiningAccess();
2223
George Burgess IV400ae402016-07-20 19:51:34 +00002224 const Instruction *I = StartingAccess->getMemoryInst();
George Burgess IV5f308972016-07-19 01:29:15 +00002225 UpwardsMemoryQuery Q(I, StartingAccess);
David Majnemera940f362016-07-15 17:19:24 +00002226 // We can't sanely do anything with a fences, they conservatively
George Burgess IVe1100f52016-02-02 22:46:49 +00002227 // clobber all memory, and have no locations to get pointers from to
David Majnemera940f362016-07-15 17:19:24 +00002228 // try to disambiguate.
George Burgess IV5f308972016-07-19 01:29:15 +00002229 if (!Q.IsCall && I->isFenceLike())
George Burgess IVe1100f52016-02-02 22:46:49 +00002230 return StartingAccess;
2231
George Burgess IV5f308972016-07-19 01:29:15 +00002232 if (auto *CacheResult = Cache.lookup(StartingAccess, Q.StartingLoc, Q.IsCall))
George Burgess IVe1100f52016-02-02 22:46:49 +00002233 return CacheResult;
2234
George Burgess IV024f3d22016-08-03 19:57:02 +00002235 if (isUseTriviallyOptimizableToLiveOnEntry(*MSSA->AA, I)) {
2236 MemoryAccess *LiveOnEntry = MSSA->getLiveOnEntryDef();
2237 Cache.insert(StartingAccess, LiveOnEntry, Q.StartingLoc, Q.IsCall);
Daniel Berlincd2deac2016-10-20 20:13:45 +00002238 if (MemoryUse *MU = dyn_cast<MemoryUse>(StartingAccess))
2239 MU->setDefiningAccess(LiveOnEntry, true);
George Burgess IV024f3d22016-08-03 19:57:02 +00002240 return LiveOnEntry;
2241 }
2242
George Burgess IVe1100f52016-02-02 22:46:49 +00002243 // Start with the thing we already think clobbers this location
2244 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
2245
2246 // At this point, DefiningAccess may be the live on entry def.
2247 // If it is, we will not get a better result.
2248 if (MSSA->isLiveOnEntryDef(DefiningAccess))
2249 return DefiningAccess;
2250
2251 MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q);
George Burgess IVe1100f52016-02-02 22:46:49 +00002252 DEBUG(dbgs() << "Starting Memory SSA clobber for " << *I << " is ");
2253 DEBUG(dbgs() << *DefiningAccess << "\n");
2254 DEBUG(dbgs() << "Final Memory SSA clobber for " << *I << " is ");
2255 DEBUG(dbgs() << *Result << "\n");
Daniel Berlincd2deac2016-10-20 20:13:45 +00002256 if (MemoryUse *MU = dyn_cast<MemoryUse>(StartingAccess))
2257 MU->setDefiningAccess(Result, true);
George Burgess IVe1100f52016-02-02 22:46:49 +00002258
2259 return Result;
2260}
2261
Geoff Berry9fe26e62016-04-22 14:44:10 +00002262// Verify that MA doesn't exist in any of the caches.
George Burgess IVfd1f2f82016-06-24 21:02:12 +00002263void MemorySSA::CachingWalker::verifyRemoved(MemoryAccess *MA) {
George Burgess IV5f308972016-07-19 01:29:15 +00002264 assert(!Cache.contains(MA) && "Found removed MemoryAccess in cache.");
Geoff Berry9fe26e62016-04-22 14:44:10 +00002265}
2266
George Burgess IVe1100f52016-02-02 22:46:49 +00002267MemoryAccess *
George Burgess IV400ae402016-07-20 19:51:34 +00002268DoNothingMemorySSAWalker::getClobberingMemoryAccess(MemoryAccess *MA) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002269 if (auto *Use = dyn_cast<MemoryUseOrDef>(MA))
2270 return Use->getDefiningAccess();
2271 return MA;
2272}
2273
2274MemoryAccess *DoNothingMemorySSAWalker::getClobberingMemoryAccess(
George Burgess IV013fd732016-10-28 19:22:46 +00002275 MemoryAccess *StartingAccess, const MemoryLocation &) {
George Burgess IVe1100f52016-02-02 22:46:49 +00002276 if (auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
2277 return Use->getDefiningAccess();
2278 return StartingAccess;
2279}
George Burgess IV5f308972016-07-19 01:29:15 +00002280} // namespace llvm