1 //===- MemorySSAUpdater.h - Memory SSA Updater-------------------*- 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 // An automatic updater for MemorySSA that handles arbitrary insertion,
11 // deletion, and moves.  It performs phi insertion where necessary, and
12 // automatically updates the MemorySSA IR to be correct.
13 // While updating loads or removing instructions is often easy enough to not
14 // need this, updating stores should generally not be attemped outside this
15 // API.
16 //
17 // Basic API usage:
18 // Create the memory access you want for the instruction (this is mainly so
19 // we know where it is, without having to duplicate the entire set of create
20 // functions MemorySSA supports).
21 // Call insertDef or insertUse depending on whether it's a MemoryUse or a
22 // MemoryDef.
23 // That's it.
24 //
25 // For moving, first, move the instruction itself using the normal SSA
26 // instruction moving API, then just call moveBefore, moveAfter,or moveTo with
27 // the right arguments.
28 //
29 //===----------------------------------------------------------------------===//
30 
31 #ifndef LLVM_ANALYSIS_MEMORYSSAUPDATER_H
32 #define LLVM_ANALYSIS_MEMORYSSAUPDATER_H
33 
34 #include "llvm/ADT/SetVector.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallSet.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/Analysis/MemorySSA.h"
39 #include "llvm/IR/ValueHandle.h"
40 #include "llvm/IR/ValueMap.h"
41 #include "llvm/Support/CFGDiff.h"
42 #include <utility>
43 
44 namespace llvm {
45 
46 class BasicBlock;
47 class BranchInst;
48 class DominatorTree;
49 class Instruction;
50 class LoopBlocksRPO;
51 
52 using ValueToValueMapTy = ValueMap<const Value *, WeakTrackingVH>;
53 using PhiToDefMap = SmallDenseMap<MemoryPhi *, MemoryAccess *>;
54 using CFGUpdate = cfg::Update<BasicBlock *>;
55 using GraphDiffInvBBPair =
56     std::pair<const GraphDiff<BasicBlock *> *, Inverse<BasicBlock *>>;
57 
58 class MemorySSAUpdater {
59 private:
60   MemorySSA *MSSA;
61 
62   /// We use WeakVH rather than a costly deletion to deal with dangling pointers.
63   /// MemoryPhis are created eagerly and sometimes get zapped shortly afterwards.
64   SmallVector<WeakVH, 16> InsertedPHIs;
65 
66   SmallPtrSet<BasicBlock *, 8> VisitedBlocks;
67   SmallSet<AssertingVH<MemoryPhi>, 8> NonOptPhis;
68 
69 public:
MemorySSAUpdater(MemorySSA * MSSA)70   MemorySSAUpdater(MemorySSA *MSSA) : MSSA(MSSA) {}
71 
72   /// Insert a definition into the MemorySSA IR.  RenameUses will rename any use
73   /// below the new def block (and any inserted phis).  RenameUses should be set
74   /// to true if the definition may cause new aliases for loads below it.  This
75   /// is not the case for hoisting or sinking or other forms of code *movement*.
76   /// It *is* the case for straight code insertion.
77   /// For example:
78   /// store a
79   /// if (foo) { }
80   /// load a
81   ///
82   /// Moving the store into the if block, and calling insertDef, does not
83   /// require RenameUses.
84   /// However, changing it to:
85   /// store a
86   /// if (foo) { store b }
87   /// load a
88   /// Where a mayalias b, *does* require RenameUses be set to true.
89   void insertDef(MemoryDef *Def, bool RenameUses = false);
90   void insertUse(MemoryUse *Use, bool RenameUses = false);
91   /// Update the MemoryPhi in `To` following an edge deletion between `From` and
92   /// `To`. If `To` becomes unreachable, a call to removeBlocks should be made.
93   void removeEdge(BasicBlock *From, BasicBlock *To);
94   /// Update the MemoryPhi in `To` to have a single incoming edge from `From`,
95   /// following a CFG change that replaced multiple edges (switch) with a direct
96   /// branch.
97   void removeDuplicatePhiEdgesBetween(const BasicBlock *From,
98                                       const BasicBlock *To);
99   /// Update MemorySSA when inserting a unique backedge block for a loop.
100   void updatePhisWhenInsertingUniqueBackedgeBlock(BasicBlock *LoopHeader,
101                                                   BasicBlock *LoopPreheader,
102                                                   BasicBlock *BackedgeBlock);
103   /// Update MemorySSA after a loop was cloned, given the blocks in RPO order,
104   /// the exit blocks and a 1:1 mapping of all blocks and instructions
105   /// cloned. This involves duplicating all defs and uses in the cloned blocks
106   /// Updating phi nodes in exit block successors is done separately.
107   void updateForClonedLoop(const LoopBlocksRPO &LoopBlocks,
108                            ArrayRef<BasicBlock *> ExitBlocks,
109                            const ValueToValueMapTy &VM,
110                            bool IgnoreIncomingWithNoClones = false);
111   // Block BB was fully or partially cloned into its predecessor P1. Map
112   // contains the 1:1 mapping of instructions cloned and VM[BB]=P1.
113   void updateForClonedBlockIntoPred(BasicBlock *BB, BasicBlock *P1,
114                                     const ValueToValueMapTy &VM);
115   /// Update phi nodes in exit block successors following cloning. Exit blocks
116   /// that were not cloned don't have additional predecessors added.
117   void updateExitBlocksForClonedLoop(ArrayRef<BasicBlock *> ExitBlocks,
118                                      const ValueToValueMapTy &VMap,
119                                      DominatorTree &DT);
120   void updateExitBlocksForClonedLoop(
121       ArrayRef<BasicBlock *> ExitBlocks,
122       ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps, DominatorTree &DT);
123 
124   /// Apply CFG updates, analogous with the DT edge updates.
125   void applyUpdates(ArrayRef<CFGUpdate> Updates, DominatorTree &DT);
126   /// Apply CFG insert updates, analogous with the DT edge updates.
127   void applyInsertUpdates(ArrayRef<CFGUpdate> Updates, DominatorTree &DT);
128 
129   void moveBefore(MemoryUseOrDef *What, MemoryUseOrDef *Where);
130   void moveAfter(MemoryUseOrDef *What, MemoryUseOrDef *Where);
131   void moveToPlace(MemoryUseOrDef *What, BasicBlock *BB,
132                    MemorySSA::InsertionPlace Where);
133   /// `From` block was spliced into `From` and `To`. There is a CFG edge from
134   /// `From` to `To`. Move all accesses from `From` to `To` starting at
135   /// instruction `Start`. `To` is newly created BB, so empty of
136   /// MemorySSA::MemoryAccesses. Edges are already updated, so successors of
137   /// `To` with MPhi nodes need to update incoming block.
138   /// |------|        |------|
139   /// | From |        | From |
140   /// |      |        |------|
141   /// |      |           ||
142   /// |      |   =>      \/
143   /// |      |        |------|  <- Start
144   /// |      |        |  To  |
145   /// |------|        |------|
146   void moveAllAfterSpliceBlocks(BasicBlock *From, BasicBlock *To,
147                                 Instruction *Start);
148   /// `From` block was merged into `To`. There is a CFG edge from `To` to
149   /// `From`.`To` still branches to `From`, but all instructions were moved and
150   /// `From` is now an empty block; `From` is about to be deleted. Move all
151   /// accesses from `From` to `To` starting at instruction `Start`. `To` may
152   /// have multiple successors, `From` has a single predecessor. `From` may have
153   /// successors with MPhi nodes, replace their incoming block with `To`.
154   /// |------|        |------|
155   /// |  To  |        |  To  |
156   /// |------|        |      |
157   ///    ||      =>   |      |
158   ///    \/           |      |
159   /// |------|        |      |  <- Start
160   /// | From |        |      |
161   /// |------|        |------|
162   void moveAllAfterMergeBlocks(BasicBlock *From, BasicBlock *To,
163                                Instruction *Start);
164   /// A new empty BasicBlock (New) now branches directly to Old. Some of
165   /// Old's predecessors (Preds) are now branching to New instead of Old.
166   /// If New is the only predecessor, move Old's Phi, if present, to New.
167   /// Otherwise, add a new Phi in New with appropriate incoming values, and
168   /// update the incoming values in Old's Phi node too, if present.
169   void wireOldPredecessorsToNewImmediatePredecessor(
170       BasicBlock *Old, BasicBlock *New, ArrayRef<BasicBlock *> Preds,
171       bool IdenticalEdgesWereMerged = true);
172   // The below are utility functions. Other than creation of accesses to pass
173   // to insertDef, and removeAccess to remove accesses, you should generally
174   // not attempt to update memoryssa yourself. It is very non-trivial to get
175   // the edge cases right, and the above calls already operate in near-optimal
176   // time bounds.
177 
178   /// Create a MemoryAccess in MemorySSA at a specified point in a block,
179   /// with a specified clobbering definition.
180   ///
181   /// Returns the new MemoryAccess.
182   /// This should be called when a memory instruction is created that is being
183   /// used to replace an existing memory instruction. It will *not* create PHI
184   /// nodes, or verify the clobbering definition. The insertion place is used
185   /// solely to determine where in the memoryssa access lists the instruction
186   /// will be placed. The caller is expected to keep ordering the same as
187   /// instructions.
188   /// It will return the new MemoryAccess.
189   /// Note: If a MemoryAccess already exists for I, this function will make it
190   /// inaccessible and it *must* have removeMemoryAccess called on it.
191   MemoryAccess *createMemoryAccessInBB(Instruction *I, MemoryAccess *Definition,
192                                        const BasicBlock *BB,
193                                        MemorySSA::InsertionPlace Point);
194 
195   /// Create a MemoryAccess in MemorySSA before or after an existing
196   /// MemoryAccess.
197   ///
198   /// Returns the new MemoryAccess.
199   /// This should be called when a memory instruction is created that is being
200   /// used to replace an existing memory instruction. It will *not* create PHI
201   /// nodes, or verify the clobbering definition.
202   ///
203   /// Note: If a MemoryAccess already exists for I, this function will make it
204   /// inaccessible and it *must* have removeMemoryAccess called on it.
205   MemoryUseOrDef *createMemoryAccessBefore(Instruction *I,
206                                            MemoryAccess *Definition,
207                                            MemoryUseOrDef *InsertPt);
208   MemoryUseOrDef *createMemoryAccessAfter(Instruction *I,
209                                           MemoryAccess *Definition,
210                                           MemoryAccess *InsertPt);
211 
212   /// Remove a MemoryAccess from MemorySSA, including updating all
213   /// definitions and uses.
214   /// This should be called when a memory instruction that has a MemoryAccess
215   /// associated with it is erased from the program.  For example, if a store or
216   /// load is simply erased (not replaced), removeMemoryAccess should be called
217   /// on the MemoryAccess for that store/load.
218   void removeMemoryAccess(MemoryAccess *, bool OptimizePhis = false);
219 
220   /// Remove MemoryAccess for a given instruction, if a MemoryAccess exists.
221   /// This should be called when an instruction (load/store) is deleted from
222   /// the program.
223   void removeMemoryAccess(const Instruction *I, bool OptimizePhis = false) {
224     if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
225       removeMemoryAccess(MA, OptimizePhis);
226   }
227 
228   /// Remove all MemoryAcceses in a set of BasicBlocks about to be deleted.
229   /// Assumption we make here: all uses of deleted defs and phi must either
230   /// occur in blocks about to be deleted (thus will be deleted as well), or
231   /// they occur in phis that will simply lose an incoming value.
232   /// Deleted blocks still have successor info, but their predecessor edges and
233   /// Phi nodes may already be updated. Instructions in DeadBlocks should be
234   /// deleted after this call.
235   void removeBlocks(const SmallSetVector<BasicBlock *, 8> &DeadBlocks);
236 
237   /// Instruction I will be changed to an unreachable. Remove all accesses in
238   /// I's block that follow I (inclusive), and update the Phis in the blocks'
239   /// successors.
240   void changeToUnreachable(const Instruction *I);
241 
242   /// Conditional branch BI is changed or replaced with an unconditional branch
243   /// to `To`. Update Phis in BI's successors to remove BI's BB.
244   void changeCondBranchToUnconditionalTo(const BranchInst *BI,
245                                          const BasicBlock *To);
246 
247   /// Get handle on MemorySSA.
getMemorySSA()248   MemorySSA* getMemorySSA() const { return MSSA; }
249 
250 private:
251   // Move What before Where in the MemorySSA IR.
252   template <class WhereType>
253   void moveTo(MemoryUseOrDef *What, BasicBlock *BB, WhereType Where);
254   // Move all memory accesses from `From` to `To` starting at `Start`.
255   // Restrictions apply, see public wrappers of this method.
256   void moveAllAccesses(BasicBlock *From, BasicBlock *To, Instruction *Start);
257   MemoryAccess *getPreviousDef(MemoryAccess *);
258   MemoryAccess *getPreviousDefInBlock(MemoryAccess *);
259   MemoryAccess *
260   getPreviousDefFromEnd(BasicBlock *,
261                         DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> &);
262   MemoryAccess *
263   getPreviousDefRecursive(BasicBlock *,
264                           DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> &);
265   MemoryAccess *recursePhi(MemoryAccess *Phi);
266   MemoryAccess *tryRemoveTrivialPhi(MemoryPhi *Phi);
267   template <class RangeType>
268   MemoryAccess *tryRemoveTrivialPhi(MemoryPhi *Phi, RangeType &Operands);
269   void tryRemoveTrivialPhis(ArrayRef<WeakVH> UpdatedPHIs);
270   void fixupDefs(const SmallVectorImpl<WeakVH> &);
271   // Clone all uses and defs from BB to NewBB given a 1:1 map of all
272   // instructions and blocks cloned, and a map of MemoryPhi : Definition
273   // (MemoryAccess Phi or Def). VMap maps old instructions to cloned
274   // instructions and old blocks to cloned blocks. MPhiMap, is created in the
275   // caller of this private method, and maps existing MemoryPhis to new
276   // definitions that new MemoryAccesses must point to. These definitions may
277   // not necessarily be MemoryPhis themselves, they may be MemoryDefs. As such,
278   // the map is between MemoryPhis and MemoryAccesses, where the MemoryAccesses
279   // may be MemoryPhis or MemoryDefs and not MemoryUses.
280   // If CloneWasSimplified = true, the clone was exact. Otherwise, assume that
281   // the clone involved simplifications that may have: (1) turned a MemoryUse
282   // into an instruction that MemorySSA has no representation for, or (2) turned
283   // a MemoryDef into a MemoryUse or an instruction that MemorySSA has no
284   // representation for. No other cases are supported.
285   void cloneUsesAndDefs(BasicBlock *BB, BasicBlock *NewBB,
286                         const ValueToValueMapTy &VMap, PhiToDefMap &MPhiMap,
287                         bool CloneWasSimplified = false);
288   template <typename Iter>
289   void privateUpdateExitBlocksForClonedLoop(ArrayRef<BasicBlock *> ExitBlocks,
290                                             Iter ValuesBegin, Iter ValuesEnd,
291                                             DominatorTree &DT);
292   void applyInsertUpdates(ArrayRef<CFGUpdate>, DominatorTree &DT,
293                           const GraphDiff<BasicBlock *> *GD);
294 };
295 } // end namespace llvm
296 
297 #endif // LLVM_ANALYSIS_MEMORYSSAUPDATER_H
298