LLVM 24.0.0git
MemorySSA.h
Go to the documentation of this file.
1//===- MemorySSA.h - Build Memory SSA ---------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// This file exposes an interface to building/using memory SSA to
11/// walk memory instructions using a use/def graph.
12///
13/// Memory SSA class builds an SSA form that links together memory access
14/// instructions such as loads, stores, atomics, and calls. Additionally, it
15/// does a trivial form of "heap versioning" Every time the memory state changes
16/// in the program, we generate a new heap version. It generates
17/// MemoryDef/Uses/Phis that are overlayed on top of the existing instructions.
18///
19/// As a trivial example,
20/// define i32 @main() #0 {
21/// entry:
22/// %call = call noalias i8* @_Znwm(i64 4) #2
23/// %0 = bitcast i8* %call to i32*
24/// %call1 = call noalias i8* @_Znwm(i64 4) #2
25/// %1 = bitcast i8* %call1 to i32*
26/// store i32 5, i32* %0, align 4
27/// store i32 7, i32* %1, align 4
28/// %2 = load i32* %0, align 4
29/// %3 = load i32* %1, align 4
30/// %add = add nsw i32 %2, %3
31/// ret i32 %add
32/// }
33///
34/// Will become
35/// define i32 @main() #0 {
36/// entry:
37/// ; 1 = MemoryDef(0)
38/// %call = call noalias i8* @_Znwm(i64 4) #3
39/// %2 = bitcast i8* %call to i32*
40/// ; 2 = MemoryDef(1)
41/// %call1 = call noalias i8* @_Znwm(i64 4) #3
42/// %4 = bitcast i8* %call1 to i32*
43/// ; 3 = MemoryDef(2)
44/// store i32 5, i32* %2, align 4
45/// ; 4 = MemoryDef(3)
46/// store i32 7, i32* %4, align 4
47/// ; MemoryUse(4)
48/// %7 = load i32* %2, align 4
49/// ; MemoryUse(4)
50/// %8 = load i32* %4, align 4
51/// %add = add nsw i32 %7, %8
52/// ret i32 %add
53/// }
54///
55/// Given this form, all the stores that could ever effect the load at %8 can be
56/// gotten by using the MemoryUse associated with it, and walking from use to
57/// def until you hit the top of the function.
58///
59/// Each def also has a list of users associated with it, so you can walk from
60/// both def to users, and users to defs. MemoryUses are not disambiguated when
61/// MemorySSA is built: the defining access of a MemoryUse is the nearest
62/// dominating MemoryDef or MemoryPhi, which is why %7 above is a MemoryUse(4)
63/// even though only 3 may alias it. The walker disambiguates a MemoryUse on
64/// demand: getClobberingMemoryAccess() on %7 returns 3 and makes it the
65/// defining access, so %7 becomes a MemoryUse(3). Being disambiguated means
66/// that for a given store, all the optimized MemoryUses on its use lists are
67/// may-aliases of that store (but other MemoryUses and the MemoryDefs on its
68/// use list may not be).
69///
70/// MemoryDefs are not disambiguated because it would require multiple reaching
71/// definitions, which would require multiple phis, and multiple memoryaccesses
72/// per instruction.
73///
74/// In addition to the def/use graph described above, MemoryDefs also contain
75/// an "optimized" definition use. The "optimized" use points to some def
76/// reachable through the memory def chain. The optimized def *may* (but is
77/// not required to) alias the original MemoryDef, but no def *closer* to the
78/// source def may alias it. As the name implies, the purpose of the optimized
79/// use is to allow caching of clobber searches for memory defs. The optimized
80/// def may be nullptr, in which case clients must walk the defining access
81/// chain.
82///
83/// When iterating the uses of a MemoryDef, both defining uses and optimized
84/// uses will be encountered. If only one type is needed, the client must
85/// filter the use walk.
86//
87//===----------------------------------------------------------------------===//
88
89#ifndef LLVM_ANALYSIS_MEMORYSSA_H
90#define LLVM_ANALYSIS_MEMORYSSA_H
91
92#include "llvm/ADT/DenseMap.h"
95#include "llvm/ADT/ilist_node.h"
100#include "llvm/IR/DerivedUser.h"
101#include "llvm/IR/Dominators.h"
102#include "llvm/IR/Type.h"
103#include "llvm/IR/User.h"
104#include "llvm/Pass.h"
107#include <algorithm>
108#include <cassert>
109#include <cstddef>
110#include <iterator>
111#include <memory>
112#include <utility>
113
114namespace llvm {
115
116struct AnalysisOptions;
117template <class GraphType> struct GraphTraits;
118class Function;
119class Loop;
120class LLVMContext;
121class MemoryAccess;
122class MemorySSAWalker;
123class Module;
124class raw_ostream;
125
126namespace MSSAHelpers {
127
128struct AllAccessTag {};
129struct DefsOnlyTag {};
130
131} // end namespace MSSAHelpers
132
133enum : unsigned {
134 // Used to signify what the default invalid ID is for MemoryAccess's
135 // getID()
137};
138
139template <class T> class memoryaccess_def_iterator_base;
143
144// The base for all memory accesses. All memory accesses in a block are
145// linked together using an intrusive list.
147 : public DerivedUser,
148 public ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::AllAccessTag>>,
149 public ilist_node<MemoryAccess, ilist_tag<MSSAHelpers::DefsOnlyTag>> {
150public:
155
156 MemoryAccess(const MemoryAccess &) = delete;
158
159 void *operator new(size_t) = delete;
160
161 // Methods for support type inquiry through isa, cast, and
162 // dyn_cast
163 static bool classof(const Value *V) {
164 unsigned ID = V->getValueID();
165 return ID == MemoryUseVal || ID == MemoryPhiVal || ID == MemoryDefVal;
166 }
167
168 BasicBlock *getBlock() const { return Block; }
169
170 LLVM_ABI void print(raw_ostream &OS) const;
171 LLVM_ABI void dump() const;
172
173 /// The user iterators for a memory access
176
177 /// This iterator walks over all of the defs in a given
178 /// MemoryAccess. For MemoryPhi nodes, this walks arguments. For
179 /// MemoryUse/MemoryDef, this walks the defining access.
184
185 /// Get the iterators for the all access list and the defs only list
186 /// We default to the all access list.
211
212protected:
213 friend class MemoryDef;
214 friend class MemoryPhi;
215 friend class MemorySSA;
216 friend class MemoryUse;
217 friend class MemoryUseOrDef;
218
219 /// Used by MemorySSA to change the block of a MemoryAccess when it is
220 /// moved.
221 void setBlock(BasicBlock *BB) { Block = BB; }
222
223 /// Used for debugging and tracking things about MemoryAccesses.
224 /// Guaranteed unique among MemoryAccesses, no guarantees otherwise.
225 inline unsigned getID() const;
226
227 MemoryAccess(LLVMContext &C, unsigned Vty, DeleteValueTy DeleteValue,
229 : DerivedUser(Type::getVoidTy(C), Vty, AllocInfo, DeleteValue),
230 Block(BB) {}
231
232 // Use deleteValue() to delete a generic MemoryAccess.
233 ~MemoryAccess() = default;
234
235private:
236 BasicBlock *Block;
237};
238
239template <>
241 static void deleteNode(MemoryAccess *MA) { MA->deleteValue(); }
242};
243
245 MA.print(OS);
246 return OS;
247}
248
249/// Class that has the common methods + fields of memory uses/defs. It's
250/// a little awkward to have, but there are many cases where we want either a
251/// use or def, and there are many cases where uses are needed (defs aren't
252/// acceptable), and vice-versa.
253///
254/// This class should never be instantiated directly; make a MemoryUse or
255/// MemoryDef instead.
257public:
258 void *operator new(size_t) = delete;
259
261
262 /// Get the instruction that this MemoryUse represents.
263 Instruction *getMemoryInst() const { return MemoryInstruction; }
264
265 /// Get the access that produces the memory state used by this Use.
267
268 static bool classof(const Value *MA) {
269 return MA->getValueID() == MemoryUseVal || MA->getValueID() == MemoryDefVal;
270 }
271
272 /// Do we have an optimized use?
273 inline bool isOptimized() const;
274 /// Return the MemoryAccess associated with the optimized use, or nullptr.
275 inline MemoryAccess *getOptimized() const;
276 /// Sets the optimized use for a MemoryDef.
277 inline void setOptimized(MemoryAccess *);
278
279 /// Reset the ID of what this MemoryUse was optimized to, causing it to
280 /// be rewalked by the walker if necessary.
281 /// This really should only be called by tests.
282 inline void resetOptimized();
283
284protected:
285 friend class MemorySSA;
286 friend class MemorySSAUpdater;
287
289 DeleteValueTy DeleteValue, Instruction *MI, BasicBlock *BB,
291 : MemoryAccess(C, Vty, DeleteValue, BB, AllocInfo),
292 MemoryInstruction(MI) {
294 }
295
296 // Use deleteValue() to delete a generic MemoryUseOrDef.
297 ~MemoryUseOrDef() = default;
298
299 void setDefiningAccess(MemoryAccess *DMA, bool Optimized = false) {
300 if (!Optimized) {
301 setOperand(0, DMA);
302 return;
303 }
304 setOptimized(DMA);
305 }
306
307private:
308 Instruction *MemoryInstruction;
309};
310
311/// Represents read-only accesses to memory
312///
313/// In particular, the set of Instructions that will be represented by
314/// MemoryUse's is exactly the set of Instructions for which
315/// AliasAnalysis::getModRefInfo returns "Ref".
316class MemoryUse final : public MemoryUseOrDef {
317 constexpr static IntrusiveOperandsAllocMarker AllocMarker{1};
318
319public:
321
323 : MemoryUseOrDef(C, DMA, MemoryUseVal, deleteMe, MI, BB, AllocMarker) {}
324
325 static bool classof(const Value *MA) {
326 return MA->getValueID() == MemoryUseVal;
327 }
328
329 LLVM_ABI void print(raw_ostream &OS) const;
330
332 OptimizedID = DMA->getID();
333 setOperand(0, DMA);
334 }
335
336 /// Whether the MemoryUse is optimized. Uses are optimized lazily by the
337 /// walker; an update that changes the defining access clears this.
338 bool isOptimized() const {
339 return getDefiningAccess() && OptimizedID == getDefiningAccess()->getID();
340 }
341
343 return getDefiningAccess();
344 }
345
347 OptimizedID = INVALID_MEMORYACCESS_ID;
348 }
349
350protected:
351 friend class MemorySSA;
352
353private:
354 static void deleteMe(DerivedUser *Self);
355
356 unsigned OptimizedID = INVALID_MEMORYACCESS_ID;
357};
358
359template <>
360struct OperandTraits<MemoryUse> : public FixedNumOperandTraits<MemoryUse, 1> {};
362
363/// Represents a read-write access to memory, whether it is a must-alias,
364/// or a may-alias.
365///
366/// In particular, the set of Instructions that will be represented by
367/// MemoryDef's is exactly the set of Instructions for which
368/// AliasAnalysis::getModRefInfo returns "Mod" or "ModRef".
369/// Note that, in order to provide def-def chains, all defs also have a use
370/// associated with them. This use points to the nearest reaching
371/// MemoryDef/MemoryPhi.
372class MemoryDef final : public MemoryUseOrDef {
373 constexpr static IntrusiveOperandsAllocMarker AllocMarker{2};
374
375public:
376 friend class MemorySSA;
377
379
381 unsigned Ver)
382 : MemoryUseOrDef(C, DMA, MemoryDefVal, deleteMe, MI, BB, AllocMarker),
383 ID(Ver) {}
384
385 static bool classof(const Value *MA) {
386 return MA->getValueID() == MemoryDefVal;
387 }
388
390 setOperand(1, MA);
391 OptimizedID = MA->getID();
392 }
393
397
398 bool isOptimized() const {
399 return getOptimized() && OptimizedID == getOptimized()->getID();
400 }
401
403 OptimizedID = INVALID_MEMORYACCESS_ID;
404 setOperand(1, nullptr);
405 }
406
407 LLVM_ABI void print(raw_ostream &OS) const;
408
409 unsigned getID() const { return ID; }
410
411private:
412 static void deleteMe(DerivedUser *Self);
413
414 const unsigned ID;
415 unsigned OptimizedID = INVALID_MEMORYACCESS_ID;
416};
417
418template <>
419struct OperandTraits<MemoryDef> : public FixedNumOperandTraits<MemoryDef, 2> {};
421
422template <>
425 if (auto *MU = dyn_cast<MemoryUse>(MUD))
428 }
429
430 static Use *op_end(MemoryUseOrDef *MUD) {
431 if (auto *MU = dyn_cast<MemoryUse>(MUD))
434 }
435
436 static unsigned operands(const MemoryUseOrDef *MUD) {
437 if (const auto *MU = dyn_cast<MemoryUse>(MUD))
440 }
441};
442DEFINE_TRANSPARENT_OPERAND_ACCESSORS(MemoryUseOrDef, MemoryAccess)
443
444/// Represents phi nodes for memory accesses.
445///
446/// These have the same semantic as regular phi nodes, with the exception that
447/// only one phi will ever exist in a given basic block.
448/// Guaranteeing one phi per block means guaranteeing there is only ever one
449/// valid reaching MemoryDef/MemoryPHI along each path to the phi node.
450/// This is ensured by not allowing disambiguation of the RHS of a MemoryDef or
451/// a MemoryPhi's operands.
452/// That is, given
453/// if (a) {
454/// store %a
455/// store %b
456/// }
457/// it *must* be transformed into
458/// if (a) {
459/// 1 = MemoryDef(liveOnEntry)
460/// store %a
461/// 2 = MemoryDef(1)
462/// store %b
463/// }
464/// and *not*
465/// if (a) {
466/// 1 = MemoryDef(liveOnEntry)
467/// store %a
468/// 2 = MemoryDef(liveOnEntry)
469/// store %b
470/// }
471/// even if the two stores do not conflict. Otherwise, both 1 and 2 reach the
472/// end of the branch, and if there are not two phi nodes, one will be
473/// disconnected completely from the SSA graph below that point.
474/// Because MemoryUse's do not generate new definitions, they do not have this
475/// issue.
476class MemoryPhi final : public MemoryAccess {
477 constexpr static HungOffOperandsAllocMarker AllocMarker{};
478
479 // allocate space for exactly zero operands
480 void *operator new(size_t S) { return User::operator new(S, AllocMarker); }
481
482public:
483 void operator delete(void *Ptr) { User::operator delete(Ptr, AllocMarker); }
484
485 /// Provide fast operand accessors
487
488 MemoryPhi(LLVMContext &C, BasicBlock *BB, unsigned Ver, unsigned NumPreds = 0)
489 : MemoryAccess(C, MemoryPhiVal, deleteMe, BB, AllocMarker), ID(Ver),
490 ReservedSpace(NumPreds) {
491 allocHungoffUses(ReservedSpace);
492 }
493
494 // Block iterator interface. This provides access to the list of incoming
495 // basic blocks, which parallels the list of incoming values.
498
500 return reinterpret_cast<block_iterator>(op_begin() + ReservedSpace);
501 }
502
504 return reinterpret_cast<const_block_iterator>(op_begin() + ReservedSpace);
505 }
506
508
510 return block_begin() + getNumOperands();
511 }
512
516
520
522
524
525 /// Return the number of incoming edges
526 unsigned getNumIncomingValues() const { return getNumOperands(); }
527
528 /// Return incoming value number x
529 MemoryAccess *getIncomingValue(unsigned I) const { return getOperand(I); }
530 void setIncomingValue(unsigned I, MemoryAccess *V) {
531 assert(V && "PHI node got a null value!");
532 setOperand(I, V);
533 }
534
535 static unsigned getOperandNumForIncomingValue(unsigned I) { return I; }
536 static unsigned getIncomingValueNumForOperand(unsigned I) { return I; }
537
538 /// Return incoming basic block number @p i.
539 BasicBlock *getIncomingBlock(unsigned I) const { return block_begin()[I]; }
540
541 /// Return incoming basic block corresponding
542 /// to an operand of the PHI.
543 BasicBlock *getIncomingBlock(const Use &U) const {
544 assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
545 return getIncomingBlock(unsigned(&U - op_begin()));
546 }
547
548 /// Return incoming basic block corresponding
549 /// to value use iterator.
553
554 void setIncomingBlock(unsigned I, BasicBlock *BB) {
555 assert(BB && "PHI node got a null basic block!");
556 block_begin()[I] = BB;
557 }
558
559 /// Add an incoming value to the end of the PHI list
561 if (getNumOperands() == ReservedSpace)
562 growOperands(); // Get more space!
563 // Initialize some new operands.
567 }
568
569 /// Return the first index of the specified basic
570 /// block in the value list for this PHI. Returns -1 if no instance.
571 int getBasicBlockIndex(const BasicBlock *BB) const {
572 for (unsigned I = 0, E = getNumOperands(); I != E; ++I)
573 if (block_begin()[I] == BB)
574 return I;
575 return -1;
576 }
577
579 int Idx = getBasicBlockIndex(BB);
580 assert(Idx >= 0 && "Invalid basic block argument!");
581 return getIncomingValue(Idx);
582 }
583
584 // After deleting incoming position I, the order of incoming may be changed.
585 void unorderedDeleteIncoming(unsigned I) {
586 unsigned E = getNumOperands();
587 assert(I < E && "Cannot remove out of bounds Phi entry.");
588 // MemoryPhi must have at least two incoming values, otherwise the MemoryPhi
589 // itself should be deleted.
590 assert(E >= 2 && "Cannot only remove incoming values in MemoryPhis with "
591 "at least 2 values.");
594 setOperand(E - 1, nullptr);
595 block_begin()[E - 1] = nullptr;
597 }
598
599 // After deleting entries that satisfy Pred, remaining entries may have
600 // changed order.
601 template <typename Fn> void unorderedDeleteIncomingIf(Fn &&Pred) {
602 for (unsigned I = 0, E = getNumOperands(); I != E; ++I)
605 E = getNumOperands();
606 --I;
607 }
608 assert(getNumOperands() >= 1 &&
609 "Cannot remove all incoming blocks in a MemoryPhi.");
610 }
611
612 // After deleting incoming block BB, the incoming blocks order may be changed.
615 [&](const MemoryAccess *, const BasicBlock *B) { return BB == B; });
616 }
617
618 static bool classof(const Value *V) {
619 return V->getValueID() == MemoryPhiVal;
620 }
621
622 LLVM_ABI void print(raw_ostream &OS) const;
623
624 unsigned getID() const { return ID; }
625
626protected:
627 friend class MemorySSA;
628
629 /// this is more complicated than the generic
630 /// User::allocHungoffUses, because we have to allocate Uses for the incoming
631 /// values and pointers to the incoming blocks, all in one allocation.
632 void allocHungoffUses(unsigned N) {
633 User::allocHungoffUses(N, /* IsPhi */ true);
634 }
635
636private:
637 // For debugging only
638 const unsigned ID;
639 unsigned ReservedSpace;
640
641 /// This grows the operand list in response to a push_back style of
642 /// operation. This grows the number of ops by 1.5 times.
643 void growOperands() {
644 unsigned E = getNumOperands();
645 // 2 op PHI nodes are VERY common, so reserve at least enough for that.
646 ReservedSpace = std::max(E + E / 2, 2u);
647 growHungoffUses(ReservedSpace, /* IsPhi */ true);
648 }
649
650 static void deleteMe(DerivedUser *Self);
651};
652
653inline unsigned MemoryAccess::getID() const {
654 assert((isa<MemoryDef>(this) || isa<MemoryPhi>(this)) &&
655 "only memory defs and phis have ids");
656 if (const auto *MD = dyn_cast<MemoryDef>(this))
657 return MD->getID();
658 return cast<MemoryPhi>(this)->getID();
659}
660
661inline bool MemoryUseOrDef::isOptimized() const {
662 if (const auto *MD = dyn_cast<MemoryDef>(this))
663 return MD->isOptimized();
664 return cast<MemoryUse>(this)->isOptimized();
665}
666
668 if (const auto *MD = dyn_cast<MemoryDef>(this))
669 return MD->getOptimized();
670 return cast<MemoryUse>(this)->getOptimized();
671}
672
674 if (auto *MD = dyn_cast<MemoryDef>(this))
675 MD->setOptimized(MA);
676 else
677 cast<MemoryUse>(this)->setOptimized(MA);
678}
679
681 if (auto *MD = dyn_cast<MemoryDef>(this))
682 MD->resetOptimized();
683 else
684 cast<MemoryUse>(this)->resetOptimized();
685}
686
687template <> struct OperandTraits<MemoryPhi> : public HungoffOperandTraits {};
689
690/// Encapsulates MemorySSA, including all data associated with memory
691/// accesses.
693public:
696
697 // MemorySSA must remain where it's constructed; Walkers it creates store
698 // pointers to it.
699 MemorySSA(MemorySSA &&) = delete;
700
702
705
706 /// Given a memory Mod/Ref'ing instruction, get the MemorySSA
707 /// access associated with it. If passed a basic block gets the memory phi
708 /// node that exists for that block, if there is one. Otherwise, this will get
709 /// a MemoryUseOrDef.
711 return cast_or_null<MemoryUseOrDef>(ValueToMemoryAccess.lookup(I));
712 }
713
715 return cast_or_null<MemoryPhi>(ValueToMemoryAccess.lookup(cast<Value>(BB)));
716 }
717
718 DominatorTree &getDomTree() const { return *DT; }
719
720 LLVM_ABI void dump() const;
721 LLVM_ABI void print(raw_ostream &) const;
722
723 /// Return true if \p MA represents the live on entry value
724 ///
725 /// Loads and stores from pointer arguments and other global values may be
726 /// defined by memory operations that do not occur in the current function, so
727 /// they may be live on entry to the function. MemorySSA represents such
728 /// memory state by the live on entry definition, which is guaranteed to occur
729 /// before any other memory access in the function.
730 inline bool isLiveOnEntryDef(const MemoryAccess *MA) const {
731 return MA == LiveOnEntryDef.get();
732 }
733
735 return LiveOnEntryDef.get();
736 }
737
738 // Sadly, iplists, by default, owns and deletes pointers added to the
739 // list. It's not currently possible to have two iplists for the same type,
740 // where one owns the pointers, and one does not. This is because the traits
741 // are per-type, not per-tag. If this ever changes, we should make the
742 // DefList an iplist.
744 using DefsList =
746
747 /// Return the list of MemoryAccess's for a given basic block.
749 const BlockInfo *Info = getBlockInfo(BB);
750 return Info ? Info->Accesses.get() : nullptr;
751 }
752
753 /// Return the list of MemoryDef's and MemoryPhi's for a given basic
754 /// block.
755 DefsList *getBlockDefs(const BasicBlock *BB) const {
756 const BlockInfo *Info = getBlockInfo(BB);
757 return Info ? Info->Defs.get() : nullptr;
758 }
759
760 /// Given two memory accesses in the same basic block, determine
761 /// whether MemoryAccess \p A dominates MemoryAccess \p B.
762 LLVM_ABI bool locallyDominates(const MemoryAccess *A,
763 const MemoryAccess *B) const;
764
765 /// Given two memory accesses in potentially different blocks,
766 /// determine whether MemoryAccess \p A dominates MemoryAccess \p B.
767 LLVM_ABI bool dominates(const MemoryAccess *A, const MemoryAccess *B) const;
768
769 /// Given a MemoryAccess and a Use, determine whether MemoryAccess \p A
770 /// dominates Use \p B.
771 LLVM_ABI bool dominates(const MemoryAccess *A, const Use &B) const;
772
773 enum class VerificationLevel { Fast, Full };
774 /// Verify that MemorySSA is self consistent (IE definitions dominate
775 /// all uses, uses appear in the right places). This is used by unit tests.
776 LLVM_ABI void
777 verifyMemorySSA(VerificationLevel = VerificationLevel::Fast) const;
778
779 /// Used in various insertion functions to specify whether we are talking
780 /// about the beginning or end of a block.
782
783 AliasAnalysis &getAA() { return *AA; }
784
785protected:
786 // Used by Memory SSA dumpers and wrapper pass
787 friend class MemorySSAUpdater;
788
789 template <typename IterT>
791 IterT Blocks, VerificationLevel = VerificationLevel::Fast) const;
792 template <typename IterT> void verifyDominationNumbers(IterT Blocks) const;
793 template <typename IterT> void verifyPrevDefInPhis(IterT Blocks) const;
794
795 // These is used by the updater to perform various internal MemorySSA
796 // machinsations. They do not always leave the IR in a correct state, and
797 // relies on the updater to fixup what it breaks, so it is not public.
798
801 LLVM_ABI void moveTo(MemoryAccess *What, BasicBlock *BB,
802 InsertionPlace Point);
803
804 // Rename the dominator tree branch rooted at BB.
805 void renamePass(BasicBlock *BB, MemoryAccess *IncomingVal,
807 renamePass(DT->getNode(BB), IncomingVal, Visited, true, true);
808 }
809
810 LLVM_ABI void removeFromLookups(MemoryAccess *);
811 LLVM_ABI void removeFromLists(MemoryAccess *, bool ShouldDelete = true);
812 LLVM_ABI void insertIntoListsForBlock(MemoryAccess *, const BasicBlock *,
813 InsertionPlace);
814 LLVM_ABI void insertIntoListsBefore(MemoryAccess *, const BasicBlock *,
815 AccessList::iterator);
817 createDefinedAccess(Instruction *, MemoryAccess *,
818 const MemoryUseOrDef *Template = nullptr,
819 bool CreationMustSucceed = true);
820
821private:
822 class ClobberWalkerBase;
823 class CachingWalker;
824 class SkipSelfWalker;
825
826 CachingWalker *getWalkerImpl();
827 template <typename IterT>
828 void buildMemorySSA(BatchAAResults &BAA, IterT Blocks);
829
830 void prepareForMoveTo(MemoryAccess *, BasicBlock *);
831 void verifyUseInDefs(MemoryAccess *, MemoryAccess *) const;
832
833 // The per-block lists live in UseOrDefAllocator, so only destroy them.
834 struct ListDeleter {
835 template <typename ListT> void operator()(ListT *L) const { L->~ListT(); }
836 };
837 template <typename ListT> using ListPtr = std::unique_ptr<ListT, ListDeleter>;
838
839 /// Per-block state.
840 struct BlockInfo {
841 /// The list of all accesses in the block. Owns the accesses.
842 ListPtr<AccessList> Accesses;
843 /// The list of MemoryDefs and MemoryPhis in the block.
844 ListPtr<DefsList> Defs;
845 };
846
847 /// Return the index of \p BB in the per-block lists. Blocks must not be
848 /// renumbered or moved to a different function while MemorySSA is alive.
849 unsigned getBlockIndex(const BasicBlock *BB) const {
850 assert(BB->getParent()->getBlockNumberEpoch() == BlockNumberEpoch &&
851 "Blocks were renumbered while MemorySSA was alive");
852 return BB->getNumber();
853 }
854
855 /// Return the per-block state of \p BB, or nullptr if there is none.
856 const BlockInfo *getBlockInfo(const BasicBlock *BB) const {
857 unsigned N = getBlockIndex(BB);
858 return N < PerBlock.size() ? &PerBlock[N] : nullptr;
859 }
860 BlockInfo &getOrCreateBlockInfo(const BasicBlock *BB);
861 template <typename ListT> ListT *getOrCreateList(ListPtr<ListT> &List);
862
863 void markUnreachableAsLiveOnEntry(BasicBlock *BB);
864 MemoryPhi *createMemoryPhi(BasicBlock *BB);
865 template <typename AliasAnalysisType>
866 MemoryUseOrDef *createNewAccess(Instruction *, AliasAnalysisType *,
867 const MemoryUseOrDef *Template = nullptr);
868 void placePHINodes(const SmallPtrSetImpl<BasicBlock *> &);
869 MemoryAccess *renameBlock(BasicBlock *, MemoryAccess *, bool);
870 void renameSuccessorPhis(BasicBlock *, MemoryAccess *, bool);
871 LLVM_ABI void renamePass(DomTreeNode *, MemoryAccess *IncomingVal,
873 bool SkipVisited = false,
874 bool RenameAllUses = false);
875 void renumberBlock(const BasicBlock *) const;
876 const AnalysisOptions &Opts;
877 AliasAnalysis *AA = nullptr;
878 DominatorTree *DT;
879 Function *F = nullptr;
880 Loop *L = nullptr;
881
882 // Memory for MemoryUses, MemoryDefs and the per-block lists.
884
885 // Memory SSA mappings
886 DenseMap<const Value *, MemoryAccess *> ValueToMemoryAccess;
887
888 // The main block to access/def mappings for MemorySSA, indexed by block
889 // number. The Accesses lists really own all the MemoryAccesses. A block's
890 // Accesses and Defs are non-null iff the corresponding list is not empty.
892 /// Block number epoch on construction.
893 unsigned BlockNumberEpoch;
894 std::unique_ptr<MemoryAccess, ValueDeleter> LiveOnEntryDef;
895
896 // Domination mappings
897 // Note that the numbering is local to a block, even though the map is
898 // global.
899 mutable SmallPtrSet<const BasicBlock *, 16> BlockNumberingValid;
901
902 // Memory SSA building info
903 std::unique_ptr<ClobberWalkerBase> WalkerBase;
904 std::unique_ptr<CachingWalker> Walker;
905 std::unique_ptr<SkipSelfWalker> SkipWalker;
906 unsigned NextID = 0;
907};
908
909/// Enables verification of MemorySSA.
910///
911/// The checks which this flag enables is exensive and disabled by default
912/// unless `EXPENSIVE_CHECKS` is defined. The flag `-verify-memoryssa` can be
913/// used to selectively enable the verification without re-compilation.
914LLVM_ABI extern bool VerifyMemorySSA;
915
916// Internal MemorySSA utils, for use by MemorySSA classes and walkers
918protected:
919 friend class GVNHoist;
920 friend class MemorySSAWalker;
921
922 // This function should not be used by new passes.
923 LLVM_ABI static bool defClobbersUseOrDef(MemoryDef *MD,
924 const MemoryUseOrDef *MU,
926};
927
928/// An analysis that produces \c MemorySSA for a function.
929///
930class MemorySSAAnalysis : public AnalysisInfoMixin<MemorySSAAnalysis> {
932
933 LLVM_ABI static AnalysisKey Key;
934
935public:
936 // Wrap MemorySSA result to ensure address stability of internal MemorySSA
937 // pointers after construction. Use a wrapper class instead of plain
938 // unique_ptr<MemorySSA> to avoid build breakage on MSVC.
939 struct Result {
940 Result(std::unique_ptr<MemorySSA> &&MSSA) : MSSA(std::move(MSSA)) {}
941
942 MemorySSA &getMSSA() { return *MSSA; }
943
944 std::unique_ptr<MemorySSA> MSSA;
945
947 FunctionAnalysisManager::Invalidator &Inv);
948 };
949
951};
952
953/// Printer pass for \c MemorySSA.
955 : public RequiredPassInfoMixin<MemorySSAPrinterPass> {
956 raw_ostream &OS;
957
958public:
959 explicit MemorySSAPrinterPass(raw_ostream &OS) : OS(OS) {}
960
962};
963
964/// Printer pass for \c MemorySSA via the walker.
966 : public RequiredPassInfoMixin<MemorySSAWalkerPrinterPass> {
967 raw_ostream &OS;
968
969public:
970 explicit MemorySSAWalkerPrinterPass(raw_ostream &OS) : OS(OS) {}
971
973};
974
975/// Verifier pass for \c MemorySSA.
979
980/// Legacy analysis pass which computes \c MemorySSA.
982public:
984
985 static char ID;
986
987 bool runOnFunction(Function &) override;
988 void releaseMemory() override;
989 MemorySSA &getMSSA() { return *MSSA; }
990 const MemorySSA &getMSSA() const { return *MSSA; }
991
992 void getAnalysisUsage(AnalysisUsage &AU) const override;
993
994 void verifyAnalysis() const override;
995 void print(raw_ostream &OS, const Module *M = nullptr) const override;
996
997private:
998 std::unique_ptr<MemorySSA> MSSA;
999};
1000
1001/// This is the generic walker interface for walkers of MemorySSA.
1002/// Walkers are used to be able to further disambiguate the def-use chains
1003/// MemorySSA gives you, or otherwise produce better info than MemorySSA gives
1004/// you.
1005/// In particular, while the def-use chains provide basic information, and are
1006/// guaranteed to give, for example, the nearest may-aliasing MemoryDef for a
1007/// MemoryUse as AliasAnalysis considers it, a user mant want better or other
1008/// information. In particular, they may want to use SCEV info to further
1009/// disambiguate memory accesses, or they may want the nearest dominating
1010/// may-aliasing MemoryDef for a call or a store. This API enables a
1011/// standardized interface to getting and using that info.
1013public:
1015 virtual ~MemorySSAWalker() = default;
1016
1018
1019 /// Given a memory Mod/Ref/ModRef'ing instruction, calling this
1020 /// will give you the nearest dominating MemoryAccess that Mod's the location
1021 /// the instruction accesses (by skipping any def which AA can prove does not
1022 /// alias the location(s) accessed by the instruction given).
1023 ///
1024 /// Note that this will return a single access, and it must dominate the
1025 /// Instruction, so if an operand of a MemoryPhi node Mod's the instruction,
1026 /// this will return the MemoryPhi, not the operand. This means that
1027 /// given:
1028 /// if (a) {
1029 /// 1 = MemoryDef(liveOnEntry)
1030 /// store %a
1031 /// } else {
1032 /// 2 = MemoryDef(liveOnEntry)
1033 /// store %b
1034 /// }
1035 /// 3 = MemoryPhi(2, 1)
1036 /// MemoryUse(3)
1037 /// load %a
1038 ///
1039 /// calling this API on load(%a) will return the MemoryPhi, not the MemoryDef
1040 /// in the if (a) branch.
1042 BatchAAResults &AA) {
1043 MemoryAccess *MA = MSSA->getMemoryAccess(I);
1044 assert(MA && "Handed an instruction that MemorySSA doesn't recognize?");
1045 return getClobberingMemoryAccess(MA, AA);
1046 }
1047
1048 /// Does the same thing as getClobberingMemoryAccess(const Instruction *I),
1049 /// but takes a MemoryAccess instead of an Instruction.
1051 BatchAAResults &AA) = 0;
1052
1053 /// Given a potentially clobbering memory access and a new location,
1054 /// calling this will give you the nearest dominating clobbering MemoryAccess
1055 /// (by skipping non-aliasing def links).
1056 ///
1057 /// This version of the function is mainly used to disambiguate phi translated
1058 /// pointers, where the value of a pointer may have changed from the initial
1059 /// memory access. Note that this expects to be handed a potentially
1060 /// clobbering access (either a MemoryDef or a MemoryPhi). Unlike the above
1061 /// API, if given a MemoryDef that clobbers the pointer as the starting
1062 /// access, it will return that MemoryDef, whereas the above would return the
1063 /// clobber starting from the use side of the memory def.
1065 const MemoryLocation &,
1066 BatchAAResults &AA) = 0;
1067
1069 BatchAAResults BAA(MSSA->getAA());
1070 return getClobberingMemoryAccess(I, BAA);
1071 }
1072
1077
1079 const MemoryLocation &Loc) {
1080 BatchAAResults BAA(MSSA->getAA());
1081 return getClobberingMemoryAccess(MA, Loc, BAA);
1082 }
1083
1084 /// Given a memory access, invalidate anything this walker knows about
1085 /// that access.
1086 /// This API is used by walkers that store information to perform basic cache
1087 /// invalidation. This will be called by MemorySSA at appropriate times for
1088 /// the walker it uses or returns.
1089 virtual void invalidateInfo(MemoryAccess *) {}
1090
1091protected:
1092 friend class MemorySSA; // For updating MSSA pointer in MemorySSA move
1093 // constructor.
1095};
1096
1097/// A MemorySSAWalker that does no alias queries, or anything else. It
1098/// simply returns the links as they were constructed by the builder.
1100public:
1101 // Keep the overrides below from hiding the Instruction overload of
1102 // getClobberingMemoryAccess.
1104
1106 BatchAAResults &) override;
1108 const MemoryLocation &,
1109 BatchAAResults &) override;
1110};
1111
1112/// Iterator base class used to implement const and non-const iterators
1113/// over the defining accesses of a MemoryAccess.
1114template <class T>
1116 : public iterator_facade_base<memoryaccess_def_iterator_base<T>,
1117 std::forward_iterator_tag, T, ptrdiff_t, T *,
1118 T *> {
1119 using BaseT = typename memoryaccess_def_iterator_base::iterator_facade_base;
1120
1121public:
1122 memoryaccess_def_iterator_base(T *Start) : Access(Start) {}
1124
1126 return Access == Other.Access && (!Access || ArgNo == Other.ArgNo);
1127 }
1128
1129 // This is a bit ugly, but for MemoryPHI's, unlike PHINodes, you can't get the
1130 // block from the operand in constant time (In a PHINode, the uselist has
1131 // both, so it's just subtraction). We provide it as part of the
1132 // iterator to avoid callers having to linear walk to get the block.
1133 // If the operation becomes constant time on MemoryPHI's, this bit of
1134 // abstraction breaking should be removed.
1136 MemoryPhi *MP = dyn_cast<MemoryPhi>(Access);
1137 assert(MP && "Tried to get phi arg block when not iterating over a PHI");
1138 return MP->getIncomingBlock(ArgNo);
1139 }
1140
1141 typename std::iterator_traits<BaseT>::pointer operator*() const {
1142 assert(Access && "Tried to access past the end of our iterator");
1143 // Go to the first argument for phis, and the defining access for everything
1144 // else.
1145 if (const MemoryPhi *MP = dyn_cast<MemoryPhi>(Access))
1146 return MP->getIncomingValue(ArgNo);
1147 return cast<MemoryUseOrDef>(Access)->getDefiningAccess();
1148 }
1149
1150 using BaseT::operator++;
1152 assert(Access && "Hit end of iterator");
1153 if (const MemoryPhi *MP = dyn_cast<MemoryPhi>(Access)) {
1154 if (++ArgNo >= MP->getNumIncomingValues()) {
1155 ArgNo = 0;
1156 Access = nullptr;
1157 }
1158 } else {
1159 Access = nullptr;
1160 }
1161 return *this;
1162 }
1163
1164private:
1165 T *Access = nullptr;
1166 unsigned ArgNo = 0;
1167};
1168
1172
1176
1180
1184
1185/// GraphTraits for a MemoryAccess, which walks defs in the normal case,
1186/// and uses in the inverse case.
1187template <> struct GraphTraits<MemoryAccess *> {
1190
1191 static NodeRef getEntryNode(NodeRef N) { return N; }
1192 static ChildIteratorType child_begin(NodeRef N) { return N->defs_begin(); }
1193 static ChildIteratorType child_end(NodeRef N) { return N->defs_end(); }
1194};
1195
1196template <> struct GraphTraits<Inverse<MemoryAccess *>> {
1199
1200 static NodeRef getEntryNode(NodeRef N) { return N; }
1201 static ChildIteratorType child_begin(NodeRef N) { return N->user_begin(); }
1202 static ChildIteratorType child_end(NodeRef N) { return N->user_end(); }
1203};
1204
1210
1211template <> struct DenseMapInfo<UpwardDefsElem> {
1217
1218 static bool isEqual(const UpwardDefsElem &LHS, const UpwardDefsElem &RHS) {
1219 return LHS.MA == RHS.MA && LHS.Loc == RHS.Loc &&
1220 LHS.MayBeCrossIteration == RHS.MayBeCrossIteration;
1221 }
1222};
1223
1224/// Provide an iterator that walks defs, giving both the memory access,
1225/// and the current pointer location, updating the pointer location as it
1226/// changes due to phi node translation.
1227///
1228/// This iterator, while somewhat specialized, is what most clients actually
1229/// want when walking upwards through MemorySSA def chains. It takes a pair of
1230/// <MemoryAccess,MemoryLocation>, and walks defs, properly translating the
1231/// memory location through phi nodes for the user.
1233 : public iterator_facade_base<upward_defs_iterator,
1234 std::forward_iterator_tag,
1235 const UpwardDefsElem> {
1236 using BaseT = upward_defs_iterator::iterator_facade_base;
1237
1238public:
1240 : DefIterator(Elem.MA), Location(Elem.Loc), OriginalAccess(Elem.MA),
1241 DT(DT) {
1242 CurrentElem.MA = nullptr;
1243 CurrentElem.MayBeCrossIteration = Elem.MayBeCrossIteration;
1244
1245 WalkingPhi = Elem.MA && isa<MemoryPhi>(Elem.MA);
1246 fillInCurrentElem();
1247 }
1248
1249 upward_defs_iterator() { CurrentElem.MA = nullptr; }
1250
1252 return DefIterator == Other.DefIterator;
1253 }
1254
1255 std::iterator_traits<BaseT>::reference operator*() const {
1256 assert(DefIterator != OriginalAccess->defs_end() &&
1257 "Tried to access past the end of our iterator");
1258 return CurrentElem;
1259 }
1260
1261 using BaseT::operator++;
1263 assert(DefIterator != OriginalAccess->defs_end() &&
1264 "Tried to access past the end of the iterator");
1265 ++DefIterator;
1266 if (DefIterator != OriginalAccess->defs_end())
1267 fillInCurrentElem();
1268 return *this;
1269 }
1270
1271 BasicBlock *getPhiArgBlock() const { return DefIterator.getPhiArgBlock(); }
1272
1273private:
1274 /// Returns true if \p Ptr is guaranteed to be loop invariant for any possible
1275 /// loop. In particular, this guarantees that it only references a single
1276 /// MemoryLocation during execution of the containing function.
1277 LLVM_ABI bool IsGuaranteedLoopInvariant(const Value *Ptr) const;
1278
1279 void fillInCurrentElem() {
1280 CurrentElem.MA = *DefIterator;
1281 CurrentElem.Loc = Location;
1282 // No need for phi translation or handling of cross-iteration dependences
1283 // if we're not walking past a phi.
1284 if (!WalkingPhi)
1285 return;
1286
1287 if (Location.Ptr) {
1288 PHITransAddr Translator(
1289 const_cast<Value *>(Location.Ptr),
1290 OriginalAccess->getBlock()->getDataLayout(), nullptr);
1291
1292 if (Value *Addr =
1293 Translator.translateValue(OriginalAccess->getBlock(),
1294 DefIterator.getPhiArgBlock(), DT, true))
1295 if (Addr != CurrentElem.Loc.Ptr)
1296 CurrentElem.Loc = CurrentElem.Loc.getWithNewPtr(Addr);
1297
1298 // Mark size as unknown, if the location is not guaranteed to be
1299 // loop-invariant for any possible loop in the function. Setting the size
1300 // to unknown guarantees that any memory accesses that access locations
1301 // after the pointer are considered as clobbers, which is important to
1302 // catch loop carried dependences.
1303 if (!IsGuaranteedLoopInvariant(CurrentElem.Loc.Ptr))
1304 // TODO: We should be using MayBeCrossIteration here as well.
1305 CurrentElem.Loc = CurrentElem.Loc.getWithNewSize(
1307 } else {
1308 // We can't easily analyze invariance for calls, so conservatively assume
1309 // they may be introducing cross-iteration dependences for any phi
1310 // translation.
1311 CurrentElem.MayBeCrossIteration = true;
1312 }
1313 }
1314
1315 UpwardDefsElem CurrentElem;
1316 memoryaccess_def_iterator DefIterator;
1317 MemoryLocation Location;
1318 MemoryAccess *OriginalAccess = nullptr;
1319 DominatorTree *DT = nullptr;
1320 bool WalkingPhi = false;
1321};
1322
1324 DominatorTree &DT) {
1325 return upward_defs_iterator(Pair, &DT);
1326}
1327
1329
1330/// Walks the defining accesses of MemoryDefs. Stops after we hit something that
1331/// has no defining use (e.g. a MemoryPhi or liveOnEntry). Note that, when
1332/// comparing against a null def_chain_iterator, this will compare equal only
1333/// after walking said Phi/liveOnEntry.
1334///
1335/// The UseOptimizedChain flag specifies whether to walk the clobbering
1336/// access chain, or all the accesses.
1337///
1338/// Normally, MemoryDef are all just def/use linked together, so a def_chain on
1339/// a MemoryDef will walk all MemoryDefs above it in the program until it hits
1340/// a phi node. The optimized chain walks the clobbering access of a store.
1341/// So if you are just trying to find, given a store, what the next
1342/// thing that would clobber the same memory is, you want the optimized chain.
1343template <class T, bool UseOptimizedChain = false>
1345 : public iterator_facade_base<def_chain_iterator<T, UseOptimizedChain>,
1346 std::forward_iterator_tag, MemoryAccess *> {
1347 def_chain_iterator() : MA(nullptr) {}
1348 def_chain_iterator(T MA) : MA(MA) {}
1349
1350 T operator*() const { return MA; }
1351
1353 // N.B. liveOnEntry has a null defining access.
1354 if (auto *MUD = dyn_cast<MemoryUseOrDef>(MA)) {
1355 if (UseOptimizedChain && MUD->isOptimized())
1356 MA = MUD->getOptimized();
1357 else
1358 MA = MUD->getDefiningAccess();
1359 } else {
1360 MA = nullptr;
1361 }
1362
1363 return *this;
1364 }
1365
1366 bool operator==(const def_chain_iterator &O) const { return MA == O.MA; }
1367
1368private:
1369 T MA;
1370};
1371
1372template <class T>
1374def_chain(T MA, MemoryAccess *UpTo = nullptr) {
1375#ifdef EXPENSIVE_CHECKS
1376 assert((!UpTo || find(def_chain(MA), UpTo) != def_chain_iterator<T>()) &&
1377 "UpTo isn't in the def chain!");
1378#endif
1380}
1381
1382template <class T>
1387
1388} // end namespace llvm
1389
1390#endif // LLVM_ANALYSIS_MEMORYSSA_H
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the BumpPtrAllocator interface.
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:211
DXIL Forward Handle Accesses
DXIL Resource Access
This file defines the DenseMap class.
early cse Early CSE w MemorySSA
static bool runOnFunction(Function &F, bool PostInlining)
IRTranslator LLVM IR MI
static MemoryAccess * getClobberingMemoryAccess(MemorySSA &MSSA, BatchAAResults &BAA, SinkAndHoistLICMFlags &Flags, MemoryUseOrDef *MA)
Definition LICM.cpp:873
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file provides utility analysis objects describing memory locations.
#define T
#define DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CLASS, VALUECLASS)
Macro for generating out-of-class operand accessor definitions.
static bool dominates(InstrPosIndexes &PosIndexes, const MachineInstr &A, const MachineInstr &B)
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
Value * RHS
Value * LHS
Represent the analysis usage information of a pass.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition Allocator.h:72
Extension point for the Value hierarchy.
Definition DerivedUser.h:26
void(*)(DerivedUser *) DeleteValueTy
Definition DerivedUser.h:28
DerivedUser(Type *Ty, unsigned VK, AllocInfo AllocInfo, DeleteValueTy DeleteValue)
Definition DerivedUser.h:36
friend class Value
Definition DerivedUser.h:31
A MemorySSAWalker that does no alias queries, or anything else.
Definition MemorySSA.h:1099
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
FunctionPass(char &pid)
Definition Pass.h:314
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
static constexpr LocationSize beforeOrAfterPointer()
Any location before or after the base pointer (but still within the underlying object).
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
LLVM_ABI void dump() const
AllAccessType::reverse_self_iterator getReverseIterator()
Definition MemorySSA.h:193
friend class MemorySSA
Definition MemorySSA.h:215
AllAccessType::const_self_iterator getIterator() const
Definition MemorySSA.h:190
MemoryAccess(const MemoryAccess &)=delete
static bool classof(const Value *V)
Definition MemorySSA.h:163
friend class MemoryUse
Definition MemorySSA.h:216
friend class MemoryUseOrDef
Definition MemorySSA.h:217
DefsOnlyType::const_self_iterator getDefsIterator() const
Definition MemorySSA.h:202
friend class MemoryPhi
Definition MemorySSA.h:214
DefsOnlyType::self_iterator getDefsIterator()
Definition MemorySSA.h:199
DefsOnlyType::reverse_self_iterator getReverseDefsIterator()
Definition MemorySSA.h:205
ilist_node< MemoryAccess, ilist_tag< MSSAHelpers::AllAccessTag > > AllAccessType
Definition MemorySSA.h:151
DefsOnlyType::const_reverse_self_iterator getReverseDefsIterator() const
Definition MemorySSA.h:208
memoryaccess_def_iterator defs_end()
Definition MemorySSA.h:1177
~MemoryAccess()=default
MemoryAccess(LLVMContext &C, unsigned Vty, DeleteValueTy DeleteValue, BasicBlock *BB, AllocInfo AllocInfo)
Definition MemorySSA.h:227
ilist_node< MemoryAccess, ilist_tag< MSSAHelpers::DefsOnlyTag > > DefsOnlyType
Definition MemorySSA.h:153
friend class MemoryDef
Definition MemorySSA.h:213
BasicBlock * getBlock() const
Definition MemorySSA.h:168
user_iterator iterator
The user iterators for a memory access.
Definition MemorySSA.h:174
AllAccessType::const_reverse_self_iterator getReverseIterator() const
Definition MemorySSA.h:196
LLVM_ABI void print(raw_ostream &OS) const
unsigned getID() const
Used for debugging and tracking things about MemoryAccesses.
Definition MemorySSA.h:653
MemoryAccess & operator=(const MemoryAccess &)=delete
void setBlock(BasicBlock *BB)
Used by MemorySSA to change the block of a MemoryAccess when it is moved.
Definition MemorySSA.h:221
const_user_iterator const_iterator
Definition MemorySSA.h:175
memoryaccess_def_iterator defs_begin()
This iterator walks over all of the defs in a given MemoryAccess.
Definition MemorySSA.h:1169
AllAccessType::self_iterator getIterator()
Get the iterators for the all access list and the defs only list We default to the all access list.
Definition MemorySSA.h:187
Represents a read-write access to memory, whether it is a must-alias, or a may-alias.
Definition MemorySSA.h:372
friend class MemorySSA
Definition MemorySSA.h:376
static bool classof(const Value *MA)
Definition MemorySSA.h:385
void resetOptimized()
Definition MemorySSA.h:402
MemoryAccess * getOptimized() const
Definition MemorySSA.h:394
unsigned getID() const
Definition MemorySSA.h:409
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess)
bool isOptimized() const
Definition MemorySSA.h:398
MemoryDef(LLVMContext &C, MemoryAccess *DMA, Instruction *MI, BasicBlock *BB, unsigned Ver)
Definition MemorySSA.h:380
void setOptimized(MemoryAccess *MA)
Definition MemorySSA.h:389
Representation for a specific memory location.
MemoryLocation getWithNewSize(LocationSize NewSize) const
MemoryLocation getWithNewPtr(const Value *NewPtr) const
const Value * Ptr
The address of the start of the location.
Represents phi nodes for memory accesses.
Definition MemorySSA.h:476
void setIncomingBlock(unsigned I, BasicBlock *BB)
Definition MemorySSA.h:554
void allocHungoffUses(unsigned N)
this is more complicated than the generic User::allocHungoffUses, because we have to allocate Uses fo...
Definition MemorySSA.h:632
friend class MemorySSA
Definition MemorySSA.h:627
void setIncomingValue(unsigned I, MemoryAccess *V)
Definition MemorySSA.h:530
static bool classof(const Value *V)
Definition MemorySSA.h:618
const_block_iterator block_end() const
Definition MemorySSA.h:509
BasicBlock * getIncomingBlock(const Use &U) const
Return incoming basic block corresponding to an operand of the PHI.
Definition MemorySSA.h:543
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess)
Provide fast operand accessors.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
Definition MemorySSA.h:526
MemoryAccess * getIncomingValueForBlock(const BasicBlock *BB) const
Definition MemorySSA.h:578
block_iterator block_end()
Definition MemorySSA.h:507
const_block_iterator block_begin() const
Definition MemorySSA.h:503
iterator_range< block_iterator > blocks()
Definition MemorySSA.h:513
void unorderedDeleteIncomingIf(Fn &&Pred)
Definition MemorySSA.h:601
void unorderedDeleteIncoming(unsigned I)
Definition MemorySSA.h:585
BasicBlock * getIncomingBlock(unsigned I) const
Return incoming basic block number i.
Definition MemorySSA.h:539
const_op_range incoming_values() const
Definition MemorySSA.h:523
BasicBlock ** block_iterator
Definition MemorySSA.h:496
BasicBlock * getIncomingBlock(MemoryAccess::const_user_iterator I) const
Return incoming basic block corresponding to value use iterator.
Definition MemorySSA.h:550
static unsigned getIncomingValueNumForOperand(unsigned I)
Definition MemorySSA.h:536
void addIncoming(MemoryAccess *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
Definition MemorySSA.h:560
op_range incoming_values()
Definition MemorySSA.h:521
void unorderedDeleteIncomingBlock(const BasicBlock *BB)
Definition MemorySSA.h:613
MemoryPhi(LLVMContext &C, BasicBlock *BB, unsigned Ver, unsigned NumPreds=0)
Definition MemorySSA.h:488
MemoryAccess * getIncomingValue(unsigned I) const
Return incoming value number x.
Definition MemorySSA.h:529
static unsigned getOperandNumForIncomingValue(unsigned I)
Definition MemorySSA.h:535
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
Definition MemorySSA.h:571
iterator_range< const_block_iterator > blocks() const
Definition MemorySSA.h:517
unsigned getID() const
Definition MemorySSA.h:624
BasicBlock *const * const_block_iterator
Definition MemorySSA.h:497
block_iterator block_begin()
Definition MemorySSA.h:499
An analysis that produces MemorySSA for a function.
Definition MemorySSA.h:930
LLVM_ABI Result run(Function &F, FunctionAnalysisManager &AM)
MemorySSAPrinterPass(raw_ostream &OS)
Definition MemorySSA.h:959
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
static LLVM_ABI bool defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU, AliasAnalysis &AA)
friend class MemorySSAWalker
Definition MemorySSA.h:920
friend class GVNHoist
Definition MemorySSA.h:919
MemorySSAWalkerPrinterPass(raw_ostream &OS)
Definition MemorySSA.h:970
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
This is the generic walker interface for walkers of MemorySSA.
Definition MemorySSA.h:1012
SmallVector< MemoryAccess *, 8 > MemoryAccessSet
Definition MemorySSA.h:1017
friend class MemorySSA
Definition MemorySSA.h:1092
MemoryAccess * getClobberingMemoryAccess(const Instruction *I, BatchAAResults &AA)
Given a memory Mod/Ref/ModRef'ing instruction, calling this will give you the nearest dominating Memo...
Definition MemorySSA.h:1041
LLVM_ABI MemorySSAWalker(MemorySSA *)
virtual ~MemorySSAWalker()=default
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *MA, const MemoryLocation &Loc)
Definition MemorySSA.h:1078
virtual void invalidateInfo(MemoryAccess *)
Given a memory access, invalidate anything this walker knows about that access.
Definition MemorySSA.h:1089
virtual MemoryAccess * getClobberingMemoryAccess(MemoryAccess *, const MemoryLocation &, BatchAAResults &AA)=0
Given a potentially clobbering memory access and a new location, calling this will give you the neare...
virtual MemoryAccess * getClobberingMemoryAccess(MemoryAccess *, BatchAAResults &AA)=0
Does the same thing as getClobberingMemoryAccess(const Instruction *I), but takes a MemoryAccess inst...
MemoryAccess * getClobberingMemoryAccess(const Instruction *I)
Definition MemorySSA.h:1068
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *MA)
Definition MemorySSA.h:1073
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
const MemorySSA & getMSSA() const
Definition MemorySSA.h:990
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition MemorySSA.h:692
simple_ilist< MemoryAccess, ilist_tag< MSSAHelpers::DefsOnlyTag > > DefsList
Definition MemorySSA.h:744
AliasAnalysis & getAA()
Definition MemorySSA.h:783
LLVM_ABI void moveTo(MemoryUseOrDef *What, BasicBlock *BB, AccessList::iterator Where)
void renamePass(BasicBlock *BB, MemoryAccess *IncomingVal, SmallPtrSetImpl< BasicBlock * > &Visited)
Definition MemorySSA.h:805
DefsList * getBlockDefs(const BasicBlock *BB) const
Return the list of MemoryDef's and MemoryPhi's for a given basic block.
Definition MemorySSA.h:755
LLVM_ABI MemorySSAWalker * getSkipSelfWalker()
LLVM_ABI MemorySSA(Function &, AliasAnalysis *, DominatorTree *)
iplist< MemoryAccess, ilist_tag< MSSAHelpers::AllAccessTag > > AccessList
Definition MemorySSA.h:743
AccessList * getBlockAccesses(const BasicBlock *BB) const
Return the list of MemoryAccess's for a given basic block.
Definition MemorySSA.h:748
void verifyOrderingDominationAndDefUses(IterT Blocks, VerificationLevel=VerificationLevel::Fast) const
Verify ordering: the order and existence of MemoryAccesses matches the order and existence of memory ...
LLVM_ABI MemorySSAWalker * getWalker()
InsertionPlace
Used in various insertion functions to specify whether we are talking about the beginning or end of a...
Definition MemorySSA.h:781
MemorySSA(MemorySSA &&)=delete
DominatorTree & getDomTree() const
Definition MemorySSA.h:718
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
Definition MemorySSA.h:710
friend class MemorySSAUpdater
Definition MemorySSA.h:787
MemoryPhi * getMemoryAccess(const BasicBlock *BB) const
Definition MemorySSA.h:714
MemoryAccess * getLiveOnEntryDef() const
Definition MemorySSA.h:734
void verifyDominationNumbers(IterT Blocks) const
Verify that all of the blocks we believe to have valid domination numbers actually have valid dominat...
void verifyPrevDefInPhis(IterT Blocks) const
bool isLiveOnEntryDef(const MemoryAccess *MA) const
Return true if MA represents the live on entry value.
Definition MemorySSA.h:730
Class that has the common methods + fields of memory uses/defs.
Definition MemorySSA.h:256
friend class MemorySSA
Definition MemorySSA.h:285
MemoryUseOrDef(LLVMContext &C, MemoryAccess *DMA, unsigned Vty, DeleteValueTy DeleteValue, Instruction *MI, BasicBlock *BB, AllocInfo AllocInfo)
Definition MemorySSA.h:288
~MemoryUseOrDef()=default
MemoryAccess * getDefiningAccess() const
Get the access that produces the memory state used by this Use.
Definition MemorySSA.h:266
void resetOptimized()
Reset the ID of what this MemoryUse was optimized to, causing it to be rewalked by the walker if nece...
Definition MemorySSA.h:680
MemoryAccess * getOptimized() const
Return the MemoryAccess associated with the optimized use, or nullptr.
Definition MemorySSA.h:667
void setDefiningAccess(MemoryAccess *DMA, bool Optimized=false)
Definition MemorySSA.h:299
void setOptimized(MemoryAccess *)
Sets the optimized use for a MemoryDef.
Definition MemorySSA.h:673
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess)
Instruction * getMemoryInst() const
Get the instruction that this MemoryUse represents.
Definition MemorySSA.h:263
friend class MemorySSAUpdater
Definition MemorySSA.h:286
static bool classof(const Value *MA)
Definition MemorySSA.h:268
bool isOptimized() const
Do we have an optimized use?
Definition MemorySSA.h:661
Represents read-only accesses to memory.
Definition MemorySSA.h:316
friend class MemorySSA
Definition MemorySSA.h:351
MemoryAccess * getOptimized() const
Definition MemorySSA.h:342
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(MemoryAccess)
MemoryUse(LLVMContext &C, MemoryAccess *DMA, Instruction *MI, BasicBlock *BB)
Definition MemorySSA.h:322
LLVM_ABI void print(raw_ostream &OS) const
void resetOptimized()
Definition MemorySSA.h:346
bool isOptimized() const
Whether the MemoryUse is optimized.
Definition MemorySSA.h:338
static bool classof(const Value *MA)
Definition MemorySSA.h:325
void setOptimized(MemoryAccess *DMA)
Definition MemorySSA.h:331
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
PHITransAddr - An address value which tracks and handles phi translation.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
iterator_range< const_op_iterator > const_op_range
Definition User.h:257
op_range operands()
Definition User.h:267
op_iterator op_begin()
Definition User.h:259
LLVM_ABI void allocHungoffUses(unsigned N, bool WithExtraValues=false)
Allocate the array of Uses, followed by a pointer (with bottom bit set) to the User.
Definition User.cpp:44
void setOperand(unsigned i, Value *Val)
Definition User.h:212
void setNumHungOffUseOperands(unsigned NumOps)
Subclasses with hung off uses need to manage the operand count themselves.
Definition User.h:240
iterator_range< op_iterator > op_range
Definition User.h:256
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
user_iterator_impl< const User > const_user_iterator
Definition Value.h:394
unsigned getValueID() const
Return an ID for the concrete type of this object.
Definition Value.h:545
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
Definition Value.cpp:103
user_iterator_impl< User > user_iterator
Definition Value.h:393
ilist_select_iterator_type< OptionsT, false, true > const_self_iterator
Definition ilist_node.h:94
ilist_select_iterator_type< OptionsT, true, false > reverse_self_iterator
Definition ilist_node.h:95
reverse_self_iterator getReverseIterator()
Definition ilist_node.h:126
ilist_select_iterator_type< OptionsT, true, true > const_reverse_self_iterator
Definition ilist_node.h:97
self_iterator getIterator()
Definition ilist_node.h:123
ilist_select_iterator_type< OptionsT, false, false > self_iterator
Definition ilist_node.h:93
typename base_list_type::iterator iterator
Definition ilist.h:121
An intrusive list with ownership and callbacks specified/controlled by ilist_traits,...
Definition ilist.h:328
CRTP base class which implements the entire standard iterator facade in terms of a minimal subset of ...
Definition iterator.h:80
A range adaptor for a pair of iterators.
Iterator base class used to implement const and non-const iterators over the defining accesses of a M...
Definition MemorySSA.h:1118
BasicBlock * getPhiArgBlock() const
Definition MemorySSA.h:1135
std::iterator_traits< BaseT >::pointer operator*() const
Definition MemorySSA.h:1141
bool operator==(const memoryaccess_def_iterator_base &Other) const
Definition MemorySSA.h:1125
memoryaccess_def_iterator_base & operator++()
Definition MemorySSA.h:1151
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A simple intrusive list implementation.
Provide an iterator that walks defs, giving both the memory access, and the current pointer location,...
Definition MemorySSA.h:1235
std::iterator_traits< BaseT >::reference operator*() const
Definition MemorySSA.h:1255
upward_defs_iterator(const UpwardDefsElem &Elem, DominatorTree *DT)
Definition MemorySSA.h:1239
BasicBlock * getPhiArgBlock() const
Definition MemorySSA.h:1271
upward_defs_iterator & operator++()
Definition MemorySSA.h:1262
bool operator==(const upward_defs_iterator &Other) const
Definition MemorySSA.h:1251
This file defines the ilist_node class template, which is a convenient base class for creating classe...
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
Abstract Attribute helper functions.
Definition Attributor.h:166
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
@ INVALID_MEMORYACCESS_ID
Definition MemorySSA.h:136
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
auto cast_or_null(const Y &Val)
Definition Casting.h:714
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:65
iterator_range< def_chain_iterator< T > > def_chain(T MA, MemoryAccess *UpTo=nullptr)
Definition MemorySSA.h:1374
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition MemorySSA.cpp:74
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
@ Other
Any other memory.
Definition ModRef.h:68
upward_defs_iterator upward_defs_end()
Definition MemorySSA.h:1328
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
memoryaccess_def_iterator_base< const MemoryAccess > const_memoryaccess_def_iterator
Definition MemorySSA.h:141
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition Hashing.h:307
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
upward_defs_iterator upward_defs_begin(const UpwardDefsElem &Pair, DominatorTree &DT)
Definition MemorySSA.h:1323
memoryaccess_def_iterator_base< MemoryAccess > memoryaccess_def_iterator
Definition MemorySSA.h:140
iterator_range< def_chain_iterator< T, true > > optimized_def_chain(T MA)
Definition MemorySSA.h:1383
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
llvm::SmallVector< T, 0 > ListT
Definition ClauseT.h:150
#define N
A CRTP mix-in that provides informational APIs needed for analysis passes.
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
static unsigned getHashValue(const UpwardDefsElem &Val)
Definition MemorySSA.h:1212
static bool isEqual(const UpwardDefsElem &LHS, const UpwardDefsElem &RHS)
Definition MemorySSA.h:1218
An information struct used to provide DenseMap with the various necessary components for a given valu...
FixedNumOperandTraits - determine the allocation regime of the Use array when it is a prefix to the U...
static ChildIteratorType child_begin(NodeRef N)
Definition MemorySSA.h:1201
static ChildIteratorType child_end(NodeRef N)
Definition MemorySSA.h:1202
static ChildIteratorType child_begin(NodeRef N)
Definition MemorySSA.h:1192
static ChildIteratorType child_end(NodeRef N)
Definition MemorySSA.h:1193
static NodeRef getEntryNode(NodeRef N)
Definition MemorySSA.h:1191
memoryaccess_def_iterator ChildIteratorType
Definition MemorySSA.h:1189
HungoffOperandTraits - determine the allocation regime of the Use array when it is not a prefix to th...
Result(std::unique_ptr< MemorySSA > &&MSSA)
Definition MemorySSA.h:940
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
std::unique_ptr< MemorySSA > MSSA
Definition MemorySSA.h:944
Verifier pass for MemorySSA.
Definition MemorySSA.h:976
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
static unsigned operands(const MemoryUseOrDef *MUD)
Definition MemorySSA.h:436
static Use * op_end(MemoryUseOrDef *MUD)
Definition MemorySSA.h:430
static Use * op_begin(MemoryUseOrDef *MUD)
Definition MemorySSA.h:424
Compile-time customization of User operands.
Definition User.h:42
A CRTP mix-in for passes that should not be skipped.
MemoryLocation Loc
Definition MemorySSA.h:1207
MemoryAccess * MA
Definition MemorySSA.h:1206
Information about how a User object was allocated, to be passed into the User constructor.
Definition User.h:79
Indicates this User has operands "hung off" in another allocation.
Definition User.h:57
Indicates this User has operands co-allocated.
Definition User.h:60
Walks the defining accesses of MemoryDefs.
Definition MemorySSA.h:1346
bool operator==(const def_chain_iterator &O) const
Definition MemorySSA.h:1366
def_chain_iterator & operator++()
Definition MemorySSA.h:1352
static void deleteNode(MemoryAccess *MA)
Definition MemorySSA.h:241
Use delete by default for iplist and ilist.
Definition ilist.h:41